res_rtp_asterisk.c 223 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2008, 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. /*!
  19. * \file
  20. *
  21. * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
  22. *
  23. * \author Mark Spencer <markster@digium.com>
  24. *
  25. * \note RTP is defined in RFC 3550.
  26. *
  27. * \ingroup rtp_engines
  28. */
  29. /*** MODULEINFO
  30. <use type="external">openssl</use>
  31. <use type="external">pjproject</use>
  32. <support_level>core</support_level>
  33. ***/
  34. #include "asterisk.h"
  35. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  36. #include <sys/time.h>
  37. #include <signal.h>
  38. #include <fcntl.h>
  39. #ifdef HAVE_OPENSSL
  40. #include <openssl/opensslconf.h>
  41. #include <openssl/opensslv.h>
  42. #if !defined(OPENSSL_NO_SRTP) && (OPENSSL_VERSION_NUMBER >= 0x10001000L)
  43. #include <openssl/ssl.h>
  44. #include <openssl/err.h>
  45. #include <openssl/bio.h>
  46. #ifndef OPENSSL_NO_DH
  47. #include <openssl/dh.h>
  48. #endif
  49. #endif
  50. #endif
  51. #ifdef HAVE_PJPROJECT
  52. #include <pjlib.h>
  53. #include <pjlib-util.h>
  54. #include <pjnath.h>
  55. #include <ifaddrs.h>
  56. #endif
  57. #include "asterisk/options.h"
  58. #include "asterisk/stun.h"
  59. #include "asterisk/pbx.h"
  60. #include "asterisk/frame.h"
  61. #include "asterisk/format_cache.h"
  62. #include "asterisk/channel.h"
  63. #include "asterisk/acl.h"
  64. #include "asterisk/config.h"
  65. #include "asterisk/lock.h"
  66. #include "asterisk/utils.h"
  67. #include "asterisk/cli.h"
  68. #include "asterisk/manager.h"
  69. #include "asterisk/unaligned.h"
  70. #include "asterisk/module.h"
  71. #include "asterisk/rtp_engine.h"
  72. #include "asterisk/smoother.h"
  73. #include "asterisk/test.h"
  74. #ifdef HAVE_PJPROJECT
  75. #include "asterisk/res_pjproject.h"
  76. #endif
  77. #define MAX_TIMESTAMP_SKEW 640
  78. #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
  79. #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
  80. #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
  81. #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
  82. #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
  83. #define DEFAULT_RTP_END 31000 /*!< Default maximum port number to end allocating RTP ports at */
  84. #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
  85. #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
  86. #define DEFAULT_TURN_PORT 3478
  87. #define TURN_STATE_WAIT_TIME 2000
  88. /*! Full INTRA-frame Request / Fast Update Request (From RFC2032) */
  89. #define RTCP_PT_FUR 192
  90. /*! Sender Report (From RFC3550) */
  91. #define RTCP_PT_SR AST_RTP_RTCP_SR
  92. /*! Receiver Report (From RFC3550) */
  93. #define RTCP_PT_RR AST_RTP_RTCP_RR
  94. /*! Source Description (From RFC3550) */
  95. #define RTCP_PT_SDES 202
  96. /*! Goodbye (To remove SSRC's from tables) (From RFC3550) */
  97. #define RTCP_PT_BYE 203
  98. /*! Application defined (From RFC3550) */
  99. #define RTCP_PT_APP 204
  100. /* VP8: RTCP Feedback */
  101. /*! Payload Specific Feed Back (From RFC4585 also RFC5104) */
  102. #define RTCP_PT_PSFB 206
  103. #define RTP_MTU 1200
  104. #define DTMF_SAMPLE_RATE_MS 8 /*!< DTMF samples per millisecond */
  105. #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
  106. #define ZFONE_PROFILE_ID 0x505a
  107. #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
  108. /*!
  109. * \brief Calculate the min learning duration in ms.
  110. *
  111. * \details
  112. * The min supported packet size represents 10 ms and we need to account
  113. * for some jitter and fast clocks while learning. Some messed up devices
  114. * have very bad jitter for a small packet sample size. Jitter can also
  115. * be introduced by the network itself.
  116. *
  117. * So we'll allow packets to come in every 9ms on average for fast clocking
  118. * with the last one coming in 5ms early for jitter.
  119. */
  120. #define CALC_LEARNING_MIN_DURATION(count) (((count) - 1) * 9 - 5)
  121. #define DEFAULT_LEARNING_MIN_DURATION CALC_LEARNING_MIN_DURATION(DEFAULT_LEARNING_MIN_SEQUENTIAL)
  122. #define SRTP_MASTER_KEY_LEN 16
  123. #define SRTP_MASTER_SALT_LEN 14
  124. #define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
  125. enum strict_rtp_state {
  126. STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
  127. STRICT_RTP_LEARN, /*! Accept next packet as source */
  128. STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
  129. };
  130. enum strict_rtp_mode {
  131. STRICT_RTP_NO = 0, /*! Don't adhere to any strict RTP rules */
  132. STRICT_RTP_YES, /*! Strict RTP that restricts packets based on time and sequence number */
  133. STRICT_RTP_SEQNO, /*! Strict RTP that restricts packets based on sequence number */
  134. };
  135. /*!
  136. * \brief Strict RTP learning timeout time in milliseconds
  137. *
  138. * \note Set to 5 seconds to allow reinvite chains for direct media
  139. * to settle before media actually starts to arrive. There may be a
  140. * reinvite collision involved on the other leg.
  141. */
  142. #define STRICT_RTP_LEARN_TIMEOUT 5000
  143. #define DEFAULT_STRICT_RTP STRICT_RTP_YES /*!< Enabled by default */
  144. #define DEFAULT_ICESUPPORT 1
  145. extern struct ast_srtp_res *res_srtp;
  146. extern struct ast_srtp_policy_res *res_srtp_policy;
  147. static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  148. static int rtpstart = DEFAULT_RTP_START; /*!< First port for RTP sessions (set in rtp.conf) */
  149. static int rtpend = DEFAULT_RTP_END; /*!< Last port for RTP sessions (set in rtp.conf) */
  150. static int rtpdebug; /*!< Are we debugging? */
  151. static int rtcpdebug; /*!< Are we debugging RTCP? */
  152. static int rtcpstats; /*!< Are we debugging RTCP? */
  153. static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
  154. static struct ast_sockaddr rtpdebugaddr; /*!< Debug packets to/from this host */
  155. static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
  156. static int rtpdebugport; /*!< Debug only RTP packets from IP or IP+Port if port is > 0 */
  157. static int rtcpdebugport; /*!< Debug only RTCP packets from IP or IP+Port if port is > 0 */
  158. #ifdef SO_NO_CHECK
  159. static int nochecksums;
  160. #endif
  161. static int strictrtp = DEFAULT_STRICT_RTP; /*!< Only accept RTP frames from a defined source. If we receive an indication of a changing source, enter learning mode. */
  162. static int learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL; /*!< Number of sequential RTP frames needed from a single source during learning mode to accept new source. */
  163. static int learning_min_duration = DEFAULT_LEARNING_MIN_DURATION; /*!< Lowest acceptable timeout between the first and the last sequential RTP frame. */
  164. #ifdef HAVE_PJPROJECT
  165. static int icesupport = DEFAULT_ICESUPPORT;
  166. static struct sockaddr_in stunaddr;
  167. static pj_str_t turnaddr;
  168. static int turnport = DEFAULT_TURN_PORT;
  169. static pj_str_t turnusername;
  170. static pj_str_t turnpassword;
  171. static struct ast_ha *ice_blacklist = NULL; /*!< Blacklisted ICE networks */
  172. static ast_rwlock_t ice_blacklist_lock = AST_RWLOCK_INIT_VALUE;
  173. /*! Blacklisted networks for STUN requests */
  174. static struct ast_ha *stun_blacklist = NULL;
  175. static ast_rwlock_t stun_blacklist_lock = AST_RWLOCK_INIT_VALUE;
  176. /*! \brief Pool factory used by pjlib to allocate memory. */
  177. static pj_caching_pool cachingpool;
  178. /*! \brief Global memory pool for configuration and timers */
  179. static pj_pool_t *pool;
  180. /*! \brief Global timer heap */
  181. static pj_timer_heap_t *timer_heap;
  182. /*! \brief Thread executing the timer heap */
  183. static pj_thread_t *timer_thread;
  184. /*! \brief Used to tell the timer thread to terminate */
  185. static int timer_terminate;
  186. /*! \brief Structure which contains ioqueue thread information */
  187. struct ast_rtp_ioqueue_thread {
  188. /*! \brief Pool used by the thread */
  189. pj_pool_t *pool;
  190. /*! \brief The thread handling the queue and timer heap */
  191. pj_thread_t *thread;
  192. /*! \brief Ioqueue which polls on sockets */
  193. pj_ioqueue_t *ioqueue;
  194. /*! \brief Timer heap for scheduled items */
  195. pj_timer_heap_t *timerheap;
  196. /*! \brief Termination request */
  197. int terminate;
  198. /*! \brief Current number of descriptors being waited on */
  199. unsigned int count;
  200. /*! \brief Linked list information */
  201. AST_LIST_ENTRY(ast_rtp_ioqueue_thread) next;
  202. };
  203. /*! \brief List of ioqueue threads */
  204. static AST_LIST_HEAD_STATIC(ioqueues, ast_rtp_ioqueue_thread);
  205. /*! \brief Structure which contains ICE host candidate mapping information */
  206. struct ast_ice_host_candidate {
  207. pj_sockaddr local;
  208. pj_sockaddr advertised;
  209. AST_RWLIST_ENTRY(ast_ice_host_candidate) next;
  210. };
  211. /*! \brief List of ICE host candidate mappings */
  212. static AST_RWLIST_HEAD_STATIC(host_candidates, ast_ice_host_candidate);
  213. #endif
  214. #define FLAG_3389_WARNING (1 << 0)
  215. #define FLAG_NAT_ACTIVE (3 << 1)
  216. #define FLAG_NAT_INACTIVE (0 << 1)
  217. #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
  218. #define FLAG_NEED_MARKER_BIT (1 << 3)
  219. #define FLAG_DTMF_COMPENSATE (1 << 4)
  220. #define FLAG_REQ_LOCAL_BRIDGE_BIT (1 << 5)
  221. #define TRANSPORT_SOCKET_RTP 0
  222. #define TRANSPORT_SOCKET_RTCP 1
  223. #define TRANSPORT_TURN_RTP 2
  224. #define TRANSPORT_TURN_RTCP 3
  225. /*! \brief RTP learning mode tracking information */
  226. struct rtp_learning_info {
  227. struct ast_sockaddr proposed_address; /*!< Proposed remote address for strict RTP */
  228. struct timeval start; /*!< The time learning mode was started */
  229. struct timeval received; /*!< The time of the first received packet */
  230. int max_seq; /*!< The highest sequence number received */
  231. int packets; /*!< The number of remaining packets before the source is accepted */
  232. /*! Type of media stream carried by the RTP instance */
  233. enum ast_media_type stream_type;
  234. };
  235. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  236. struct dtls_details {
  237. SSL *ssl; /*!< SSL session */
  238. BIO *read_bio; /*!< Memory buffer for reading */
  239. BIO *write_bio; /*!< Memory buffer for writing */
  240. enum ast_rtp_dtls_setup dtls_setup; /*!< Current setup state */
  241. enum ast_rtp_dtls_connection connection; /*!< Whether this is a new or existing connection */
  242. int timeout_timer; /*!< Scheduler id for timeout timer */
  243. };
  244. #endif
  245. #ifdef HAVE_PJPROJECT
  246. /*! An ao2 wrapper protecting the PJPROJECT ice structure with ref counting. */
  247. struct ice_wrap {
  248. pj_ice_sess *real_ice; /*!< ICE session */
  249. };
  250. #endif
  251. /*! \brief RTP session description */
  252. struct ast_rtp {
  253. int s;
  254. /*! \note The f.subclass.format holds a ref. */
  255. struct ast_frame f;
  256. unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
  257. unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
  258. unsigned int themssrc; /*!< Their SSRC */
  259. unsigned int themssrc_valid; /*!< True if their SSRC is available. */
  260. unsigned int lastts;
  261. unsigned int lastividtimestamp;
  262. unsigned int lastovidtimestamp;
  263. unsigned int lastitexttimestamp;
  264. unsigned int lastotexttimestamp;
  265. int lastrxseqno; /*!< Last received sequence number */
  266. unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
  267. unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
  268. unsigned int rxcount; /*!< How many packets have we received? */
  269. unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
  270. unsigned int txcount; /*!< How many packets have we sent? */
  271. unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
  272. unsigned int cycles; /*!< Shifted count of sequence number cycles */
  273. double rxjitter; /*!< Interarrival jitter at the moment in seconds */
  274. double rxtransit; /*!< Relative transit time for previous packet */
  275. struct ast_format *lasttxformat;
  276. struct ast_format *lastrxformat;
  277. /* DTMF Reception Variables */
  278. char resp; /*!< The current digit being processed */
  279. unsigned int last_seqno; /*!< The last known sequence number for any DTMF packet */
  280. unsigned int last_end_timestamp; /*!< The last known timestamp received from an END packet */
  281. unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
  282. unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
  283. unsigned int dtmfsamples;
  284. enum ast_rtp_dtmf_mode dtmfmode; /*!< The current DTMF mode of the RTP stream */
  285. /* DTMF Transmission Variables */
  286. unsigned int lastdigitts;
  287. char sending_digit; /*!< boolean - are we sending digits */
  288. char send_digit; /*!< digit we are sending */
  289. int send_payload;
  290. int send_duration;
  291. unsigned int flags;
  292. struct timeval rxcore;
  293. struct timeval txcore;
  294. double drxcore; /*!< The double representation of the first received packet */
  295. struct timeval dtmfmute;
  296. struct ast_smoother *smoother;
  297. unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
  298. struct ast_sched_context *sched;
  299. struct ast_rtcp *rtcp;
  300. unsigned int asymmetric_codec; /*!< Indicate if asymmetric send/receive codecs are allowed */
  301. enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
  302. struct ast_sockaddr strict_rtp_address; /*!< Remote address information for strict RTP purposes */
  303. /*
  304. * Learning mode values based on pjmedia's probation mode. Many of these values are redundant to the above,
  305. * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
  306. */
  307. struct rtp_learning_info rtp_source_learn; /* Learning mode track for the expected RTP source */
  308. struct rtp_red *red;
  309. #ifdef HAVE_PJPROJECT
  310. ast_cond_t cond; /*!< ICE/TURN condition for signaling */
  311. struct ice_wrap *ice; /*!< ao2 wrapped ICE session */
  312. enum ast_rtp_ice_role role; /*!< Our role in ICE negotiation */
  313. pj_turn_sock *turn_rtp; /*!< RTP TURN relay */
  314. pj_turn_sock *turn_rtcp; /*!< RTCP TURN relay */
  315. pj_turn_state_t turn_state; /*!< Current state of the TURN relay session */
  316. unsigned int passthrough:1; /*!< Bit to indicate that the received packet should be passed through */
  317. unsigned int rtp_passthrough:1; /*!< Bit to indicate that TURN RTP should be passed through */
  318. unsigned int rtcp_passthrough:1; /*!< Bit to indicate that TURN RTCP should be passed through */
  319. unsigned int ice_port; /*!< Port that ICE was started with if it was previously started */
  320. struct ast_sockaddr rtp_loop; /*!< Loopback address for forwarding RTP from TURN */
  321. struct ast_sockaddr rtcp_loop; /*!< Loopback address for forwarding RTCP from TURN */
  322. struct ast_rtp_ioqueue_thread *ioqueue; /*!< The ioqueue thread handling us */
  323. char remote_ufrag[256]; /*!< The remote ICE username */
  324. char remote_passwd[256]; /*!< The remote ICE password */
  325. char local_ufrag[256]; /*!< The local ICE username */
  326. char local_passwd[256]; /*!< The local ICE password */
  327. struct ao2_container *ice_local_candidates; /*!< The local ICE candidates */
  328. struct ao2_container *ice_active_remote_candidates; /*!< The remote ICE candidates */
  329. struct ao2_container *ice_proposed_remote_candidates; /*!< Incoming remote ICE candidates for new session */
  330. struct ast_sockaddr ice_original_rtp_addr; /*!< rtp address that ICE started on first session */
  331. unsigned int ice_num_components; /*!< The number of ICE components */
  332. #endif
  333. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  334. SSL_CTX *ssl_ctx; /*!< SSL context */
  335. enum ast_rtp_dtls_verify dtls_verify; /*!< What to verify */
  336. enum ast_srtp_suite suite; /*!< SRTP crypto suite */
  337. enum ast_rtp_dtls_hash local_hash; /*!< Local hash used for the fingerprint */
  338. char local_fingerprint[160]; /*!< Fingerprint of our certificate */
  339. enum ast_rtp_dtls_hash remote_hash; /*!< Remote hash used for the fingerprint */
  340. unsigned char remote_fingerprint[EVP_MAX_MD_SIZE]; /*!< Fingerprint of the peer certificate */
  341. unsigned int rekey; /*!< Interval at which to renegotiate and rekey */
  342. int rekeyid; /*!< Scheduled item id for rekeying */
  343. struct dtls_details dtls; /*!< DTLS state information */
  344. #endif
  345. };
  346. /*!
  347. * \brief Structure defining an RTCP session.
  348. *
  349. * The concept "RTCP session" is not defined in RFC 3550, but since
  350. * this structure is analogous to ast_rtp, which tracks a RTP session,
  351. * it is logical to think of this as a RTCP session.
  352. *
  353. * RTCP packet is defined on page 9 of RFC 3550.
  354. *
  355. */
  356. struct ast_rtcp {
  357. int rtcp_info;
  358. int s; /*!< Socket */
  359. struct ast_sockaddr us; /*!< Socket representation of the local endpoint. */
  360. struct ast_sockaddr them; /*!< Socket representation of the remote endpoint. */
  361. unsigned int soc; /*!< What they told us */
  362. unsigned int spc; /*!< What they told us */
  363. unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
  364. struct timeval rxlsr; /*!< Time when we got their last SR */
  365. struct timeval txlsr; /*!< Time when we sent or last SR*/
  366. unsigned int expected_prior; /*!< no. packets in previous interval */
  367. unsigned int received_prior; /*!< no. packets received in previous interval */
  368. int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
  369. unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
  370. unsigned int sr_count; /*!< number of SRs we've sent */
  371. unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
  372. double accumulated_transit; /*!< accumulated a-dlsr-lsr */
  373. double rtt; /*!< Last reported rtt */
  374. unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
  375. unsigned int reported_lost; /*!< Reported lost packets in their RR */
  376. double reported_maxjitter;
  377. double reported_minjitter;
  378. double reported_normdev_jitter;
  379. double reported_stdev_jitter;
  380. unsigned int reported_jitter_count;
  381. double reported_maxlost;
  382. double reported_minlost;
  383. double reported_normdev_lost;
  384. double reported_stdev_lost;
  385. double rxlost;
  386. double maxrxlost;
  387. double minrxlost;
  388. double normdev_rxlost;
  389. double stdev_rxlost;
  390. unsigned int rxlost_count;
  391. double maxrxjitter;
  392. double minrxjitter;
  393. double normdev_rxjitter;
  394. double stdev_rxjitter;
  395. unsigned int rxjitter_count;
  396. double maxrtt;
  397. double minrtt;
  398. double normdevrtt;
  399. double stdevrtt;
  400. unsigned int rtt_count;
  401. /* VP8: sequence number for the RTCP FIR FCI */
  402. int firseq;
  403. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  404. struct dtls_details dtls; /*!< DTLS state information */
  405. #endif
  406. /* Cached local address string allows us to generate
  407. * RTCP stasis messages without having to look up our
  408. * own address every time
  409. */
  410. char *local_addr_str;
  411. enum ast_rtp_instance_rtcp type;
  412. };
  413. struct rtp_red {
  414. struct ast_frame t140; /*!< Primary data */
  415. struct ast_frame t140red; /*!< Redundant t140*/
  416. unsigned char pt[AST_RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
  417. unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
  418. unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
  419. int num_gen; /*!< Number of generations */
  420. int schedid; /*!< Timer id */
  421. int ti; /*!< How long to buffer data before send */
  422. unsigned char t140red_data[64000];
  423. unsigned char buf_data[64000]; /*!< buffered primary data */
  424. int hdrlen;
  425. long int prev_ts;
  426. };
  427. AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
  428. /* Forward Declarations */
  429. static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
  430. static int ast_rtp_destroy(struct ast_rtp_instance *instance);
  431. static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
  432. static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
  433. static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
  434. static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
  435. static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
  436. static void ast_rtp_update_source(struct ast_rtp_instance *instance);
  437. static void ast_rtp_change_source(struct ast_rtp_instance *instance);
  438. static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
  439. static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
  440. static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
  441. static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
  442. static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
  443. static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
  444. static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
  445. static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
  446. static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
  447. static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
  448. static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
  449. static void ast_rtp_stop(struct ast_rtp_instance *instance);
  450. static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
  451. static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
  452. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  453. static int ast_rtp_activate(struct ast_rtp_instance *instance);
  454. static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
  455. static void dtls_srtp_start_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
  456. static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
  457. #endif
  458. static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *via_ice, int use_srtp);
  459. #ifdef HAVE_PJPROJECT
  460. /*! \brief Helper function which clears the ICE host candidate mapping */
  461. static void host_candidate_overrides_clear(void)
  462. {
  463. struct ast_ice_host_candidate *candidate;
  464. AST_RWLIST_WRLOCK(&host_candidates);
  465. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&host_candidates, candidate, next) {
  466. AST_RWLIST_REMOVE_CURRENT(next);
  467. ast_free(candidate);
  468. }
  469. AST_RWLIST_TRAVERSE_SAFE_END;
  470. AST_RWLIST_UNLOCK(&host_candidates);
  471. }
  472. /*! \brief Applies the ICE host candidate mapping */
  473. static void host_candidate_overrides_apply(unsigned int count, pj_sockaddr addrs[])
  474. {
  475. int pos;
  476. struct ast_ice_host_candidate *candidate;
  477. AST_RWLIST_RDLOCK(&host_candidates);
  478. for (pos = 0; pos < count; pos++) {
  479. AST_LIST_TRAVERSE(&host_candidates, candidate, next) {
  480. if (!pj_sockaddr_cmp(&candidate->local, &addrs[pos])) {
  481. pj_sockaddr_copy_addr(&addrs[pos], &candidate->advertised);
  482. break;
  483. }
  484. }
  485. }
  486. AST_RWLIST_UNLOCK(&host_candidates);
  487. }
  488. /*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
  489. static void update_address_with_ice_candidate(pj_ice_sess *ice, enum ast_rtp_ice_component_type component,
  490. struct ast_sockaddr *cand_address)
  491. {
  492. char address[PJ_INET6_ADDRSTRLEN];
  493. if (component < 1 || !ice->comp[component - 1].valid_check) {
  494. return;
  495. }
  496. ast_sockaddr_parse(cand_address,
  497. pj_sockaddr_print(&ice->comp[component - 1].valid_check->rcand->addr, address,
  498. sizeof(address), 0), 0);
  499. ast_sockaddr_set_port(cand_address,
  500. pj_sockaddr_get_port(&ice->comp[component - 1].valid_check->rcand->addr));
  501. }
  502. /*! \brief Destructor for locally created ICE candidates */
  503. static void ast_rtp_ice_candidate_destroy(void *obj)
  504. {
  505. struct ast_rtp_engine_ice_candidate *candidate = obj;
  506. if (candidate->foundation) {
  507. ast_free(candidate->foundation);
  508. }
  509. if (candidate->transport) {
  510. ast_free(candidate->transport);
  511. }
  512. }
  513. /*! \pre instance is locked */
  514. static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
  515. {
  516. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  517. if (!ast_strlen_zero(ufrag)) {
  518. ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
  519. }
  520. if (!ast_strlen_zero(password)) {
  521. ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
  522. }
  523. }
  524. static int ice_candidate_cmp(void *obj, void *arg, int flags)
  525. {
  526. struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
  527. if (strcmp(candidate1->foundation, candidate2->foundation) ||
  528. candidate1->id != candidate2->id ||
  529. candidate1->type != candidate2->type ||
  530. ast_sockaddr_cmp(&candidate1->address, &candidate2->address)) {
  531. return 0;
  532. }
  533. return CMP_MATCH | CMP_STOP;
  534. }
  535. /*! \pre instance is locked */
  536. static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
  537. {
  538. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  539. struct ast_rtp_engine_ice_candidate *remote_candidate;
  540. /* ICE sessions only support UDP candidates */
  541. if (strcasecmp(candidate->transport, "udp")) {
  542. return;
  543. }
  544. if (!rtp->ice_proposed_remote_candidates) {
  545. rtp->ice_proposed_remote_candidates = ao2_container_alloc_list(
  546. AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, ice_candidate_cmp);
  547. if (!rtp->ice_proposed_remote_candidates) {
  548. return;
  549. }
  550. }
  551. /* If this is going to exceed the maximum number of ICE candidates don't even add it */
  552. if (ao2_container_count(rtp->ice_proposed_remote_candidates) == PJ_ICE_MAX_CAND) {
  553. return;
  554. }
  555. if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
  556. return;
  557. }
  558. remote_candidate->foundation = ast_strdup(candidate->foundation);
  559. remote_candidate->id = candidate->id;
  560. remote_candidate->transport = ast_strdup(candidate->transport);
  561. remote_candidate->priority = candidate->priority;
  562. ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
  563. ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
  564. remote_candidate->type = candidate->type;
  565. ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
  566. ao2_ref(remote_candidate, -1);
  567. }
  568. AST_THREADSTORAGE(pj_thread_storage);
  569. /*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
  570. static void pj_thread_register_check(void)
  571. {
  572. pj_thread_desc *desc;
  573. pj_thread_t *thread;
  574. if (pj_thread_is_registered() == PJ_TRUE) {
  575. return;
  576. }
  577. desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
  578. if (!desc) {
  579. ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
  580. return;
  581. }
  582. pj_bzero(*desc, sizeof(*desc));
  583. if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
  584. ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
  585. }
  586. return;
  587. }
  588. static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
  589. int port, int replace);
  590. /*! \pre instance is locked */
  591. static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
  592. {
  593. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  594. struct ice_wrap *ice;
  595. ice = rtp->ice;
  596. rtp->ice = NULL;
  597. if (ice) {
  598. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  599. ao2_unlock(instance);
  600. ao2_ref(ice, -1);
  601. ao2_lock(instance);
  602. }
  603. }
  604. /*!
  605. * \brief ao2 ICE wrapper object destructor.
  606. *
  607. * \param vdoomed Object being destroyed.
  608. *
  609. * \note The associated struct ast_rtp_instance object must not
  610. * be locked when unreffing the object. Otherwise we could
  611. * deadlock trying to destroy the PJPROJECT ICE structure.
  612. */
  613. static void ice_wrap_dtor(void *vdoomed)
  614. {
  615. struct ice_wrap *ice = vdoomed;
  616. if (ice->real_ice) {
  617. pj_thread_register_check();
  618. pj_ice_sess_destroy(ice->real_ice);
  619. }
  620. }
  621. static void ast2pj_rtp_ice_role(enum ast_rtp_ice_role ast_role, enum pj_ice_sess_role *pj_role)
  622. {
  623. switch (ast_role) {
  624. case AST_RTP_ICE_ROLE_CONTROLLED:
  625. *pj_role = PJ_ICE_SESS_ROLE_CONTROLLED;
  626. break;
  627. case AST_RTP_ICE_ROLE_CONTROLLING:
  628. *pj_role = PJ_ICE_SESS_ROLE_CONTROLLING;
  629. break;
  630. }
  631. }
  632. static void pj2ast_rtp_ice_role(enum pj_ice_sess_role pj_role, enum ast_rtp_ice_role *ast_role)
  633. {
  634. switch (pj_role) {
  635. case PJ_ICE_SESS_ROLE_CONTROLLED:
  636. *ast_role = AST_RTP_ICE_ROLE_CONTROLLED;
  637. return;
  638. case PJ_ICE_SESS_ROLE_CONTROLLING:
  639. *ast_role = AST_RTP_ICE_ROLE_CONTROLLING;
  640. return;
  641. case PJ_ICE_SESS_ROLE_UNKNOWN:
  642. /* Don't change anything */
  643. return;
  644. default:
  645. /* If we aren't explicitly handling something, it's a bug */
  646. ast_assert(0);
  647. return;
  648. }
  649. }
  650. /*! \pre instance is locked */
  651. static int ice_reset_session(struct ast_rtp_instance *instance)
  652. {
  653. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  654. int res;
  655. ast_debug(3, "Resetting ICE for RTP instance '%p'\n", instance);
  656. if (!rtp->ice->real_ice->is_nominating && !rtp->ice->real_ice->is_complete) {
  657. ast_debug(3, "Nevermind. ICE isn't ready for a reset\n");
  658. return 0;
  659. }
  660. ast_debug(3, "Recreating ICE session %s (%d) for RTP instance '%p'\n", ast_sockaddr_stringify(&rtp->ice_original_rtp_addr), rtp->ice_port, instance);
  661. res = ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
  662. if (!res) {
  663. /* Use the current expected role for the ICE session */
  664. enum pj_ice_sess_role role = PJ_ICE_SESS_ROLE_UNKNOWN;
  665. ast2pj_rtp_ice_role(rtp->role, &role);
  666. pj_ice_sess_change_role(rtp->ice->real_ice, role);
  667. }
  668. /* If we only have one component now, and we previously set up TURN for RTCP,
  669. * we need to destroy that TURN socket.
  670. */
  671. if (rtp->ice_num_components == 1 && rtp->turn_rtcp) {
  672. struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
  673. struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
  674. rtp->turn_state = PJ_TURN_STATE_NULL;
  675. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  676. ao2_unlock(instance);
  677. pj_turn_sock_destroy(rtp->turn_rtcp);
  678. ao2_lock(instance);
  679. while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
  680. ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
  681. }
  682. }
  683. return res;
  684. }
  685. static int ice_candidates_compare(struct ao2_container *left, struct ao2_container *right)
  686. {
  687. struct ao2_iterator i;
  688. struct ast_rtp_engine_ice_candidate *right_candidate;
  689. if (ao2_container_count(left) != ao2_container_count(right)) {
  690. return -1;
  691. }
  692. i = ao2_iterator_init(right, 0);
  693. while ((right_candidate = ao2_iterator_next(&i))) {
  694. struct ast_rtp_engine_ice_candidate *left_candidate = ao2_find(left, right_candidate, OBJ_POINTER);
  695. if (!left_candidate) {
  696. ao2_ref(right_candidate, -1);
  697. ao2_iterator_destroy(&i);
  698. return -1;
  699. }
  700. ao2_ref(left_candidate, -1);
  701. ao2_ref(right_candidate, -1);
  702. }
  703. ao2_iterator_destroy(&i);
  704. return 0;
  705. }
  706. /*! \pre instance is locked */
  707. static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
  708. {
  709. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  710. pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
  711. pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
  712. struct ao2_iterator i;
  713. struct ast_rtp_engine_ice_candidate *candidate;
  714. int cand_cnt = 0, has_rtp = 0, has_rtcp = 0;
  715. if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
  716. return;
  717. }
  718. /* Check for equivalence in the lists */
  719. if (rtp->ice_active_remote_candidates &&
  720. !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
  721. ast_debug(3, "Proposed == active candidates for RTP instance '%p'\n", instance);
  722. ao2_cleanup(rtp->ice_proposed_remote_candidates);
  723. rtp->ice_proposed_remote_candidates = NULL;
  724. /* If this ICE session is being preserved then go back to the role it currently is */
  725. pj2ast_rtp_ice_role(rtp->ice->real_ice->role, &rtp->role);
  726. return;
  727. }
  728. /* Out with the old, in with the new */
  729. ao2_cleanup(rtp->ice_active_remote_candidates);
  730. rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
  731. rtp->ice_proposed_remote_candidates = NULL;
  732. /* Reset the ICE session. Is this going to work? */
  733. if (ice_reset_session(instance)) {
  734. ast_log(LOG_NOTICE, "Failed to create replacement ICE session\n");
  735. return;
  736. }
  737. pj_thread_register_check();
  738. i = ao2_iterator_init(rtp->ice_active_remote_candidates, 0);
  739. while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
  740. pj_str_t address;
  741. /* there needs to be at least one rtp and rtcp candidate in the list */
  742. has_rtp |= candidate->id == AST_RTP_ICE_COMPONENT_RTP;
  743. has_rtcp |= candidate->id == AST_RTP_ICE_COMPONENT_RTCP;
  744. pj_strdup2(rtp->ice->real_ice->pool, &candidates[cand_cnt].foundation,
  745. candidate->foundation);
  746. candidates[cand_cnt].comp_id = candidate->id;
  747. candidates[cand_cnt].prio = candidate->priority;
  748. pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
  749. if (!ast_sockaddr_isnull(&candidate->relay_address)) {
  750. pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
  751. }
  752. if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
  753. candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
  754. } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
  755. candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
  756. } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
  757. candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
  758. }
  759. if (candidate->id == AST_RTP_ICE_COMPONENT_RTP && rtp->turn_rtp) {
  760. ast_debug(3, "RTP candidate %s (%p)\n", ast_sockaddr_stringify(&candidate->address), instance);
  761. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  762. ao2_unlock(instance);
  763. pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
  764. ao2_lock(instance);
  765. } else if (candidate->id == AST_RTP_ICE_COMPONENT_RTCP && rtp->turn_rtcp) {
  766. ast_debug(3, "RTCP candidate %s (%p)\n", ast_sockaddr_stringify(&candidate->address), instance);
  767. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  768. ao2_unlock(instance);
  769. pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
  770. ao2_lock(instance);
  771. }
  772. cand_cnt++;
  773. ao2_ref(candidate, -1);
  774. }
  775. ao2_iterator_destroy(&i);
  776. if (cand_cnt < ao2_container_count(rtp->ice_active_remote_candidates)) {
  777. ast_log(LOG_WARNING, "Lost %d ICE candidates. Consider increasing PJ_ICE_MAX_CAND in PJSIP (%p)\n",
  778. ao2_container_count(rtp->ice_active_remote_candidates) - cand_cnt, instance);
  779. }
  780. if (!has_rtp) {
  781. ast_log(LOG_WARNING, "No RTP candidates; skipping ICE checklist (%p)\n", instance);
  782. }
  783. /* If we're only dealing with one ICE component, then we don't care about the lack of RTCP candidates */
  784. if (!has_rtcp && rtp->ice_num_components > 1) {
  785. ast_log(LOG_WARNING, "No RTCP candidates; skipping ICE checklist (%p)\n", instance);
  786. }
  787. if (rtp->ice && has_rtp && (has_rtcp || rtp->ice_num_components == 1)) {
  788. pj_status_t res;
  789. char reason[80];
  790. struct ice_wrap *ice;
  791. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  792. ice = rtp->ice;
  793. ao2_ref(ice, +1);
  794. ao2_unlock(instance);
  795. res = pj_ice_sess_create_check_list(ice->real_ice, &ufrag, &passwd, cand_cnt, &candidates[0]);
  796. if (res == PJ_SUCCESS) {
  797. ast_debug(3, "Successfully created ICE checklist (%p)\n", instance);
  798. ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: SUCCESS");
  799. pj_ice_sess_start_check(ice->real_ice);
  800. pj_timer_heap_poll(timer_heap, NULL);
  801. ao2_ref(ice, -1);
  802. ao2_lock(instance);
  803. rtp->strict_rtp_state = STRICT_RTP_OPEN;
  804. return;
  805. }
  806. ao2_ref(ice, -1);
  807. ao2_lock(instance);
  808. pj_strerror(res, reason, sizeof(reason));
  809. ast_log(LOG_WARNING, "Failed to create ICE session check list: %s (%p)\n", reason, instance);
  810. }
  811. ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: FAILURE");
  812. /* even though create check list failed don't stop ice as
  813. it might still work */
  814. /* however we do need to reset remote candidates since
  815. this function may be re-entered */
  816. ao2_ref(rtp->ice_active_remote_candidates, -1);
  817. rtp->ice_active_remote_candidates = NULL;
  818. if (rtp->ice) {
  819. rtp->ice->real_ice->rcand_cnt = rtp->ice->real_ice->clist.count = 0;
  820. }
  821. }
  822. /*! \pre instance is locked */
  823. static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
  824. {
  825. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  826. return rtp->local_ufrag;
  827. }
  828. /*! \pre instance is locked */
  829. static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
  830. {
  831. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  832. return rtp->local_passwd;
  833. }
  834. /*! \pre instance is locked */
  835. static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
  836. {
  837. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  838. if (rtp->ice_local_candidates) {
  839. ao2_ref(rtp->ice_local_candidates, +1);
  840. }
  841. return rtp->ice_local_candidates;
  842. }
  843. /*! \pre instance is locked */
  844. static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
  845. {
  846. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  847. if (!rtp->ice) {
  848. return;
  849. }
  850. pj_thread_register_check();
  851. pj_ice_sess_change_role(rtp->ice->real_ice, PJ_ICE_SESS_ROLE_CONTROLLING);
  852. }
  853. /*! \pre instance is locked */
  854. static void ast_rtp_ice_set_role(struct ast_rtp_instance *instance, enum ast_rtp_ice_role role)
  855. {
  856. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  857. ast_debug(3, "Set role to %s (%p)\n",
  858. role == AST_RTP_ICE_ROLE_CONTROLLED ? "CONTROLLED" : "CONTROLLING", instance);
  859. if (!rtp->ice) {
  860. ast_debug(3, "Set role failed; no ice instance (%p)\n", instance);
  861. return;
  862. }
  863. rtp->role = role;
  864. if (!rtp->ice->real_ice->is_nominating && !rtp->ice->real_ice->is_complete) {
  865. pj_thread_register_check();
  866. pj_ice_sess_change_role(rtp->ice->real_ice, role == AST_RTP_ICE_ROLE_CONTROLLED ?
  867. PJ_ICE_SESS_ROLE_CONTROLLED : PJ_ICE_SESS_ROLE_CONTROLLING);
  868. } else {
  869. ast_debug(3, "Not setting ICE role because state is %s\n", rtp->ice->real_ice->is_nominating ? "nominating" : "complete" );
  870. }
  871. }
  872. /*! \pre instance is locked */
  873. static void ast_rtp_ice_add_cand(struct ast_rtp_instance *instance, struct ast_rtp *rtp,
  874. unsigned comp_id, unsigned transport_id, pj_ice_cand_type type, pj_uint16_t local_pref,
  875. const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr,
  876. int addr_len)
  877. {
  878. pj_str_t foundation;
  879. struct ast_rtp_engine_ice_candidate *candidate, *existing;
  880. struct ice_wrap *ice;
  881. char address[PJ_INET6_ADDRSTRLEN];
  882. pj_status_t status;
  883. if (!rtp->ice) {
  884. return;
  885. }
  886. pj_thread_register_check();
  887. pj_ice_calc_foundation(rtp->ice->real_ice->pool, &foundation, type, addr);
  888. if (!rtp->ice_local_candidates) {
  889. rtp->ice_local_candidates = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
  890. NULL, ice_candidate_cmp);
  891. if (!rtp->ice_local_candidates) {
  892. return;
  893. }
  894. }
  895. if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
  896. return;
  897. }
  898. candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
  899. candidate->id = comp_id;
  900. candidate->transport = ast_strdup("UDP");
  901. ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
  902. ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
  903. if (rel_addr) {
  904. ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
  905. ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
  906. }
  907. if (type == PJ_ICE_CAND_TYPE_HOST) {
  908. candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
  909. } else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
  910. candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
  911. } else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
  912. candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
  913. }
  914. if ((existing = ao2_find(rtp->ice_local_candidates, candidate, OBJ_POINTER))) {
  915. ao2_ref(existing, -1);
  916. ao2_ref(candidate, -1);
  917. return;
  918. }
  919. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  920. ice = rtp->ice;
  921. ao2_ref(ice, +1);
  922. ao2_unlock(instance);
  923. status = pj_ice_sess_add_cand(ice->real_ice, comp_id, transport_id, type, local_pref,
  924. &foundation, addr, base_addr, rel_addr, addr_len, NULL);
  925. ao2_ref(ice, -1);
  926. ao2_lock(instance);
  927. if (!rtp->ice || status != PJ_SUCCESS) {
  928. ao2_ref(candidate, -1);
  929. return;
  930. }
  931. /* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
  932. candidate->priority = rtp->ice->real_ice->lcand[rtp->ice->real_ice->lcand_cnt - 1].prio;
  933. ao2_link(rtp->ice_local_candidates, candidate);
  934. ao2_ref(candidate, -1);
  935. }
  936. /* PJPROJECT TURN callback */
  937. static void ast_rtp_on_turn_rx_rtp_data(pj_turn_sock *turn_sock, void *pkt, unsigned pkt_len, const pj_sockaddr_t *peer_addr, unsigned addr_len)
  938. {
  939. struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
  940. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  941. struct ice_wrap *ice;
  942. pj_status_t status;
  943. ao2_lock(instance);
  944. ice = ao2_bump(rtp->ice);
  945. ao2_unlock(instance);
  946. if (ice) {
  947. status = pj_ice_sess_on_rx_pkt(ice->real_ice, AST_RTP_ICE_COMPONENT_RTP,
  948. TRANSPORT_TURN_RTP, pkt, pkt_len, peer_addr, addr_len);
  949. ao2_ref(ice, -1);
  950. if (status != PJ_SUCCESS) {
  951. char buf[100];
  952. pj_strerror(status, buf, sizeof(buf));
  953. ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
  954. (int)status, buf);
  955. return;
  956. }
  957. if (!rtp->rtp_passthrough) {
  958. return;
  959. }
  960. rtp->rtp_passthrough = 0;
  961. }
  962. ast_sendto(rtp->s, pkt, pkt_len, 0, &rtp->rtp_loop);
  963. }
  964. /* PJPROJECT TURN callback */
  965. static void ast_rtp_on_turn_rtp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
  966. {
  967. struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
  968. struct ast_rtp *rtp;
  969. /* If this is a leftover from an already notified RTP instance just ignore the state change */
  970. if (!instance) {
  971. return;
  972. }
  973. rtp = ast_rtp_instance_get_data(instance);
  974. ao2_lock(instance);
  975. /* We store the new state so the other thread can actually handle it */
  976. rtp->turn_state = new_state;
  977. ast_cond_signal(&rtp->cond);
  978. if (new_state == PJ_TURN_STATE_DESTROYING) {
  979. pj_turn_sock_set_user_data(rtp->turn_rtp, NULL);
  980. rtp->turn_rtp = NULL;
  981. }
  982. ao2_unlock(instance);
  983. }
  984. /* RTP TURN Socket interface declaration */
  985. static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
  986. .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
  987. .on_state = ast_rtp_on_turn_rtp_state,
  988. };
  989. /* PJPROJECT TURN callback */
  990. static void ast_rtp_on_turn_rx_rtcp_data(pj_turn_sock *turn_sock, void *pkt, unsigned pkt_len, const pj_sockaddr_t *peer_addr, unsigned addr_len)
  991. {
  992. struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
  993. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  994. struct ice_wrap *ice;
  995. pj_status_t status;
  996. ao2_lock(instance);
  997. ice = ao2_bump(rtp->ice);
  998. ao2_unlock(instance);
  999. if (ice) {
  1000. status = pj_ice_sess_on_rx_pkt(ice->real_ice, AST_RTP_ICE_COMPONENT_RTCP,
  1001. TRANSPORT_TURN_RTCP, pkt, pkt_len, peer_addr, addr_len);
  1002. ao2_ref(ice, -1);
  1003. if (status != PJ_SUCCESS) {
  1004. char buf[100];
  1005. pj_strerror(status, buf, sizeof(buf));
  1006. ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
  1007. (int)status, buf);
  1008. return;
  1009. }
  1010. if (!rtp->rtcp_passthrough) {
  1011. return;
  1012. }
  1013. rtp->rtcp_passthrough = 0;
  1014. }
  1015. ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp_loop);
  1016. }
  1017. /* PJPROJECT TURN callback */
  1018. static void ast_rtp_on_turn_rtcp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
  1019. {
  1020. struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
  1021. struct ast_rtp *rtp;
  1022. /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
  1023. if (!instance) {
  1024. return;
  1025. }
  1026. rtp = ast_rtp_instance_get_data(instance);
  1027. ao2_lock(instance);
  1028. /* We store the new state so the other thread can actually handle it */
  1029. rtp->turn_state = new_state;
  1030. ast_cond_signal(&rtp->cond);
  1031. if (new_state == PJ_TURN_STATE_DESTROYING) {
  1032. pj_turn_sock_set_user_data(rtp->turn_rtcp, NULL);
  1033. rtp->turn_rtcp = NULL;
  1034. }
  1035. ao2_unlock(instance);
  1036. }
  1037. /* RTCP TURN Socket interface declaration */
  1038. static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
  1039. .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
  1040. .on_state = ast_rtp_on_turn_rtcp_state,
  1041. };
  1042. /*! \brief Worker thread for ioqueue and timerheap */
  1043. static int ioqueue_worker_thread(void *data)
  1044. {
  1045. struct ast_rtp_ioqueue_thread *ioqueue = data;
  1046. while (!ioqueue->terminate) {
  1047. const pj_time_val delay = {0, 10};
  1048. pj_ioqueue_poll(ioqueue->ioqueue, &delay);
  1049. pj_timer_heap_poll(ioqueue->timerheap, NULL);
  1050. }
  1051. return 0;
  1052. }
  1053. /*! \brief Destroyer for ioqueue thread */
  1054. static void rtp_ioqueue_thread_destroy(struct ast_rtp_ioqueue_thread *ioqueue)
  1055. {
  1056. if (ioqueue->thread) {
  1057. ioqueue->terminate = 1;
  1058. pj_thread_join(ioqueue->thread);
  1059. pj_thread_destroy(ioqueue->thread);
  1060. }
  1061. if (ioqueue->pool) {
  1062. /* This mimics the behavior of pj_pool_safe_release
  1063. * which was introduced in pjproject 2.6.
  1064. */
  1065. pj_pool_t *temp_pool = ioqueue->pool;
  1066. ioqueue->pool = NULL;
  1067. pj_pool_release(temp_pool);
  1068. }
  1069. ast_free(ioqueue);
  1070. }
  1071. /*! \brief Removal function for ioqueue thread, determines if it should be terminated and destroyed */
  1072. static void rtp_ioqueue_thread_remove(struct ast_rtp_ioqueue_thread *ioqueue)
  1073. {
  1074. int destroy = 0;
  1075. /* If nothing is using this ioqueue thread destroy it */
  1076. AST_LIST_LOCK(&ioqueues);
  1077. if ((ioqueue->count - 2) == 0) {
  1078. destroy = 1;
  1079. AST_LIST_REMOVE(&ioqueues, ioqueue, next);
  1080. }
  1081. AST_LIST_UNLOCK(&ioqueues);
  1082. if (!destroy) {
  1083. return;
  1084. }
  1085. rtp_ioqueue_thread_destroy(ioqueue);
  1086. }
  1087. /*! \brief Finder and allocator for an ioqueue thread */
  1088. static struct ast_rtp_ioqueue_thread *rtp_ioqueue_thread_get_or_create(void)
  1089. {
  1090. struct ast_rtp_ioqueue_thread *ioqueue;
  1091. pj_lock_t *lock;
  1092. AST_LIST_LOCK(&ioqueues);
  1093. /* See if an ioqueue thread exists that can handle more */
  1094. AST_LIST_TRAVERSE(&ioqueues, ioqueue, next) {
  1095. if ((ioqueue->count + 2) < PJ_IOQUEUE_MAX_HANDLES) {
  1096. break;
  1097. }
  1098. }
  1099. /* If we found one bump it up and return it */
  1100. if (ioqueue) {
  1101. ioqueue->count += 2;
  1102. goto end;
  1103. }
  1104. ioqueue = ast_calloc(1, sizeof(*ioqueue));
  1105. if (!ioqueue) {
  1106. goto end;
  1107. }
  1108. ioqueue->pool = pj_pool_create(&cachingpool.factory, "rtp", 512, 512, NULL);
  1109. /* We use a timer on the ioqueue thread for TURN so that two threads aren't operating
  1110. * on a session at the same time
  1111. */
  1112. if (pj_timer_heap_create(ioqueue->pool, 4, &ioqueue->timerheap) != PJ_SUCCESS) {
  1113. goto fatal;
  1114. }
  1115. if (pj_lock_create_recursive_mutex(ioqueue->pool, "rtp%p", &lock) != PJ_SUCCESS) {
  1116. goto fatal;
  1117. }
  1118. pj_timer_heap_set_lock(ioqueue->timerheap, lock, PJ_TRUE);
  1119. if (pj_ioqueue_create(ioqueue->pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue->ioqueue) != PJ_SUCCESS) {
  1120. goto fatal;
  1121. }
  1122. if (pj_thread_create(ioqueue->pool, "ice", &ioqueue_worker_thread, ioqueue, 0, 0, &ioqueue->thread) != PJ_SUCCESS) {
  1123. goto fatal;
  1124. }
  1125. AST_LIST_INSERT_HEAD(&ioqueues, ioqueue, next);
  1126. /* Since this is being returned to an active session the count always starts at 2 */
  1127. ioqueue->count = 2;
  1128. goto end;
  1129. fatal:
  1130. rtp_ioqueue_thread_destroy(ioqueue);
  1131. ioqueue = NULL;
  1132. end:
  1133. AST_LIST_UNLOCK(&ioqueues);
  1134. return ioqueue;
  1135. }
  1136. /*! \pre instance is locked */
  1137. static void ast_rtp_ice_turn_request(struct ast_rtp_instance *instance, enum ast_rtp_ice_component_type component,
  1138. enum ast_transport transport, const char *server, unsigned int port, const char *username, const char *password)
  1139. {
  1140. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1141. pj_turn_sock **turn_sock;
  1142. const pj_turn_sock_cb *turn_cb;
  1143. pj_turn_tp_type conn_type;
  1144. int conn_transport;
  1145. pj_stun_auth_cred cred = { 0, };
  1146. pj_str_t turn_addr;
  1147. struct ast_sockaddr addr = { { 0, } };
  1148. pj_stun_config stun_config;
  1149. struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
  1150. struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
  1151. pj_turn_session_info info;
  1152. struct ast_sockaddr local, loop;
  1153. pj_status_t status;
  1154. pj_turn_sock_cfg turn_sock_cfg;
  1155. struct ice_wrap *ice;
  1156. ast_rtp_instance_get_local_address(instance, &local);
  1157. if (ast_sockaddr_is_ipv4(&local)) {
  1158. ast_sockaddr_parse(&loop, "127.0.0.1", PARSE_PORT_FORBID);
  1159. } else {
  1160. ast_sockaddr_parse(&loop, "::1", PARSE_PORT_FORBID);
  1161. }
  1162. /* Determine what component we are requesting a TURN session for */
  1163. if (component == AST_RTP_ICE_COMPONENT_RTP) {
  1164. turn_sock = &rtp->turn_rtp;
  1165. turn_cb = &ast_rtp_turn_rtp_sock_cb;
  1166. conn_transport = TRANSPORT_TURN_RTP;
  1167. ast_sockaddr_set_port(&loop, ast_sockaddr_port(&local));
  1168. } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
  1169. turn_sock = &rtp->turn_rtcp;
  1170. turn_cb = &ast_rtp_turn_rtcp_sock_cb;
  1171. conn_transport = TRANSPORT_TURN_RTCP;
  1172. ast_sockaddr_set_port(&loop, ast_sockaddr_port(&rtp->rtcp->us));
  1173. } else {
  1174. return;
  1175. }
  1176. if (transport == AST_TRANSPORT_UDP) {
  1177. conn_type = PJ_TURN_TP_UDP;
  1178. } else if (transport == AST_TRANSPORT_TCP) {
  1179. conn_type = PJ_TURN_TP_TCP;
  1180. } else {
  1181. ast_assert(0);
  1182. return;
  1183. }
  1184. ast_sockaddr_parse(&addr, server, PARSE_PORT_FORBID);
  1185. if (*turn_sock) {
  1186. rtp->turn_state = PJ_TURN_STATE_NULL;
  1187. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  1188. ao2_unlock(instance);
  1189. pj_turn_sock_destroy(*turn_sock);
  1190. ao2_lock(instance);
  1191. while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
  1192. ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
  1193. }
  1194. }
  1195. if (component == AST_RTP_ICE_COMPONENT_RTP && !rtp->ioqueue) {
  1196. /*
  1197. * We cannot hold the instance lock because we could wait
  1198. * for the ioqueue thread to die and we might deadlock as
  1199. * a result.
  1200. */
  1201. ao2_unlock(instance);
  1202. rtp->ioqueue = rtp_ioqueue_thread_get_or_create();
  1203. ao2_lock(instance);
  1204. if (!rtp->ioqueue) {
  1205. return;
  1206. }
  1207. }
  1208. pj_stun_config_init(&stun_config, &cachingpool.factory, 0, rtp->ioqueue->ioqueue, rtp->ioqueue->timerheap);
  1209. /* Use ICE session group lock for TURN session to avoid deadlock */
  1210. pj_turn_sock_cfg_default(&turn_sock_cfg);
  1211. ice = rtp->ice;
  1212. if (ice) {
  1213. turn_sock_cfg.grp_lock = ice->real_ice->grp_lock;
  1214. ao2_ref(ice, +1);
  1215. }
  1216. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  1217. ao2_unlock(instance);
  1218. status = pj_turn_sock_create(&stun_config,
  1219. ast_sockaddr_is_ipv4(&addr) ? pj_AF_INET() : pj_AF_INET6(), conn_type,
  1220. turn_cb, &turn_sock_cfg, instance, turn_sock);
  1221. ao2_cleanup(ice);
  1222. if (status != PJ_SUCCESS) {
  1223. ast_log(LOG_WARNING, "Could not create a TURN client socket\n");
  1224. ao2_lock(instance);
  1225. return;
  1226. }
  1227. cred.type = PJ_STUN_AUTH_CRED_STATIC;
  1228. pj_strset2(&cred.data.static_cred.username, (char*)username);
  1229. cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
  1230. pj_strset2(&cred.data.static_cred.data, (char*)password);
  1231. pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port, NULL, &cred, NULL);
  1232. ao2_lock(instance);
  1233. /*
  1234. * Because the TURN socket is asynchronous and we are synchronous we need to
  1235. * wait until it is done
  1236. */
  1237. while (rtp->turn_state < PJ_TURN_STATE_READY) {
  1238. ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
  1239. }
  1240. /* If a TURN session was allocated add it as a candidate */
  1241. if (rtp->turn_state != PJ_TURN_STATE_READY) {
  1242. return;
  1243. }
  1244. pj_turn_sock_get_info(*turn_sock, &info);
  1245. ast_rtp_ice_add_cand(instance, rtp, component, conn_transport,
  1246. PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr, &info.relay_addr,
  1247. &info.mapped_addr, pj_sockaddr_get_len(&info.relay_addr));
  1248. if (component == AST_RTP_ICE_COMPONENT_RTP) {
  1249. ast_sockaddr_copy(&rtp->rtp_loop, &loop);
  1250. } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
  1251. ast_sockaddr_copy(&rtp->rtcp_loop, &loop);
  1252. }
  1253. }
  1254. static char *generate_random_string(char *buf, size_t size)
  1255. {
  1256. long val[4];
  1257. int x;
  1258. for (x=0; x<4; x++) {
  1259. val[x] = ast_random();
  1260. }
  1261. snprintf(buf, size, "%08lx%08lx%08lx%08lx", (long unsigned)val[0], (long unsigned)val[1], (long unsigned)val[2], (long unsigned)val[3]);
  1262. return buf;
  1263. }
  1264. /*! \pre instance is locked */
  1265. static void ast_rtp_ice_change_components(struct ast_rtp_instance *instance, int num_components)
  1266. {
  1267. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1268. /* Don't do anything if ICE is unsupported or if we're not changing the
  1269. * number of components
  1270. */
  1271. if (!icesupport || !rtp->ice || rtp->ice_num_components == num_components) {
  1272. return;
  1273. }
  1274. rtp->ice_num_components = num_components;
  1275. ice_reset_session(instance);
  1276. }
  1277. /* ICE RTP Engine interface declaration */
  1278. static struct ast_rtp_engine_ice ast_rtp_ice = {
  1279. .set_authentication = ast_rtp_ice_set_authentication,
  1280. .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
  1281. .start = ast_rtp_ice_start,
  1282. .stop = ast_rtp_ice_stop,
  1283. .get_ufrag = ast_rtp_ice_get_ufrag,
  1284. .get_password = ast_rtp_ice_get_password,
  1285. .get_local_candidates = ast_rtp_ice_get_local_candidates,
  1286. .ice_lite = ast_rtp_ice_lite,
  1287. .set_role = ast_rtp_ice_set_role,
  1288. .turn_request = ast_rtp_ice_turn_request,
  1289. .change_components = ast_rtp_ice_change_components,
  1290. };
  1291. #endif
  1292. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  1293. static int dtls_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
  1294. {
  1295. /* We don't want to actually verify the certificate so just accept what they have provided */
  1296. return 1;
  1297. }
  1298. static int dtls_details_initialize(struct dtls_details *dtls, SSL_CTX *ssl_ctx,
  1299. enum ast_rtp_dtls_setup setup)
  1300. {
  1301. dtls->dtls_setup = setup;
  1302. if (!(dtls->ssl = SSL_new(ssl_ctx))) {
  1303. ast_log(LOG_ERROR, "Failed to allocate memory for SSL\n");
  1304. goto error;
  1305. }
  1306. if (!(dtls->read_bio = BIO_new(BIO_s_mem()))) {
  1307. ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic\n");
  1308. goto error;
  1309. }
  1310. BIO_set_mem_eof_return(dtls->read_bio, -1);
  1311. if (!(dtls->write_bio = BIO_new(BIO_s_mem()))) {
  1312. ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
  1313. goto error;
  1314. }
  1315. BIO_set_mem_eof_return(dtls->write_bio, -1);
  1316. SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
  1317. if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
  1318. SSL_set_accept_state(dtls->ssl);
  1319. } else {
  1320. SSL_set_connect_state(dtls->ssl);
  1321. }
  1322. dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
  1323. return 0;
  1324. error:
  1325. if (dtls->read_bio) {
  1326. BIO_free(dtls->read_bio);
  1327. dtls->read_bio = NULL;
  1328. }
  1329. if (dtls->write_bio) {
  1330. BIO_free(dtls->write_bio);
  1331. dtls->write_bio = NULL;
  1332. }
  1333. if (dtls->ssl) {
  1334. SSL_free(dtls->ssl);
  1335. dtls->ssl = NULL;
  1336. }
  1337. return -1;
  1338. }
  1339. static int dtls_setup_rtcp(struct ast_rtp_instance *instance)
  1340. {
  1341. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1342. if (!rtp->ssl_ctx || !rtp->rtcp) {
  1343. return 0;
  1344. }
  1345. return dtls_details_initialize(&rtp->rtcp->dtls, rtp->ssl_ctx, rtp->dtls.dtls_setup);
  1346. }
  1347. /*! \pre instance is locked */
  1348. static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
  1349. {
  1350. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1351. int res;
  1352. #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
  1353. EC_KEY *ecdh;
  1354. #endif
  1355. if (!dtls_cfg->enabled) {
  1356. return 0;
  1357. }
  1358. if (!ast_rtp_engine_srtp_is_registered()) {
  1359. ast_log(LOG_ERROR, "SRTP support module is not loaded or available. Try loading res_srtp.so.\n");
  1360. return -1;
  1361. }
  1362. if (rtp->ssl_ctx) {
  1363. return 0;
  1364. }
  1365. #if OPENSSL_VERSION_NUMBER < 0x10002000L || defined(LIBRESSL_VERSION_NUMBER)
  1366. rtp->ssl_ctx = SSL_CTX_new(DTLSv1_method());
  1367. #else
  1368. rtp->ssl_ctx = SSL_CTX_new(DTLS_method());
  1369. #endif
  1370. if (!rtp->ssl_ctx) {
  1371. return -1;
  1372. }
  1373. SSL_CTX_set_read_ahead(rtp->ssl_ctx, 1);
  1374. #ifndef OPENSSL_NO_DH
  1375. if (!ast_strlen_zero(dtls_cfg->pvtfile)) {
  1376. BIO *bio = BIO_new_file(dtls_cfg->pvtfile, "r");
  1377. if (bio != NULL) {
  1378. DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  1379. if (dh != NULL) {
  1380. if (SSL_CTX_set_tmp_dh(rtp->ssl_ctx, dh)) {
  1381. long options = SSL_OP_CIPHER_SERVER_PREFERENCE |
  1382. SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
  1383. options = SSL_CTX_set_options(rtp->ssl_ctx, options);
  1384. ast_verb(2, "DTLS DH initialized, PFS enabled\n");
  1385. }
  1386. DH_free(dh);
  1387. }
  1388. BIO_free(bio);
  1389. }
  1390. }
  1391. #endif /* !OPENSSL_NO_DH */
  1392. #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
  1393. /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
  1394. ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1395. if (ecdh != NULL) {
  1396. if (SSL_CTX_set_tmp_ecdh(rtp->ssl_ctx, ecdh)) {
  1397. #ifndef SSL_CTRL_SET_ECDH_AUTO
  1398. #define SSL_CTRL_SET_ECDH_AUTO 94
  1399. #endif
  1400. /* SSL_CTX_set_ecdh_auto(rtp->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
  1401. if (SSL_CTX_ctrl(rtp->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
  1402. ast_verb(2, "DTLS ECDH initialized (automatic), faster PFS enabled\n");
  1403. } else {
  1404. ast_verb(2, "DTLS ECDH initialized (secp256r1), faster PFS enabled\n");
  1405. }
  1406. }
  1407. EC_KEY_free(ecdh);
  1408. }
  1409. #endif /* !OPENSSL_NO_ECDH */
  1410. rtp->dtls_verify = dtls_cfg->verify;
  1411. SSL_CTX_set_verify(rtp->ssl_ctx, (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) || (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
  1412. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, !(rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
  1413. dtls_verify_callback : NULL);
  1414. if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
  1415. SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
  1416. } else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
  1417. SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
  1418. } else {
  1419. ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
  1420. return -1;
  1421. }
  1422. rtp->local_hash = dtls_cfg->hash;
  1423. if (!ast_strlen_zero(dtls_cfg->certfile)) {
  1424. char *private = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
  1425. BIO *certbio;
  1426. X509 *cert = NULL;
  1427. const EVP_MD *type;
  1428. unsigned int size, i;
  1429. unsigned char fingerprint[EVP_MAX_MD_SIZE];
  1430. char *local_fingerprint = rtp->local_fingerprint;
  1431. if (!SSL_CTX_use_certificate_file(rtp->ssl_ctx, dtls_cfg->certfile, SSL_FILETYPE_PEM)) {
  1432. ast_log(LOG_ERROR, "Specified certificate file '%s' for RTP instance '%p' could not be used\n",
  1433. dtls_cfg->certfile, instance);
  1434. return -1;
  1435. }
  1436. if (!SSL_CTX_use_PrivateKey_file(rtp->ssl_ctx, private, SSL_FILETYPE_PEM) ||
  1437. !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
  1438. ast_log(LOG_ERROR, "Specified private key file '%s' for RTP instance '%p' could not be used\n",
  1439. private, instance);
  1440. return -1;
  1441. }
  1442. if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA1) {
  1443. type = EVP_sha1();
  1444. } else if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA256) {
  1445. type = EVP_sha256();
  1446. } else {
  1447. ast_log(LOG_ERROR, "Unsupported fingerprint hash type on RTP instance '%p'\n",
  1448. instance);
  1449. return -1;
  1450. }
  1451. if (!(certbio = BIO_new(BIO_s_file()))) {
  1452. ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
  1453. instance);
  1454. return -1;
  1455. }
  1456. if (!BIO_read_filename(certbio, dtls_cfg->certfile) ||
  1457. !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL)) ||
  1458. !X509_digest(cert, type, fingerprint, &size) ||
  1459. !size) {
  1460. ast_log(LOG_ERROR, "Could not produce fingerprint from certificate '%s' for RTP instance '%p'\n",
  1461. dtls_cfg->certfile, instance);
  1462. BIO_free_all(certbio);
  1463. if (cert) {
  1464. X509_free(cert);
  1465. }
  1466. return -1;
  1467. }
  1468. for (i = 0; i < size; i++) {
  1469. sprintf(local_fingerprint, "%02hhX:", fingerprint[i]);
  1470. local_fingerprint += 3;
  1471. }
  1472. *(local_fingerprint-1) = 0;
  1473. BIO_free_all(certbio);
  1474. X509_free(cert);
  1475. }
  1476. if (!ast_strlen_zero(dtls_cfg->cipher)) {
  1477. if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
  1478. ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
  1479. dtls_cfg->cipher, instance);
  1480. return -1;
  1481. }
  1482. }
  1483. if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
  1484. if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
  1485. ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
  1486. S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
  1487. return -1;
  1488. }
  1489. }
  1490. rtp->rekey = dtls_cfg->rekey;
  1491. rtp->suite = dtls_cfg->suite;
  1492. res = dtls_details_initialize(&rtp->dtls, rtp->ssl_ctx, dtls_cfg->default_setup);
  1493. if (!res) {
  1494. dtls_setup_rtcp(instance);
  1495. }
  1496. return res;
  1497. }
  1498. /*! \pre instance is locked */
  1499. static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
  1500. {
  1501. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1502. return !rtp->ssl_ctx ? 0 : 1;
  1503. }
  1504. /*! \pre instance is locked */
  1505. static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
  1506. {
  1507. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1508. SSL *ssl = rtp->dtls.ssl;
  1509. ao2_unlock(instance);
  1510. dtls_srtp_stop_timeout_timer(instance, rtp, 0);
  1511. ao2_lock(instance);
  1512. if (rtp->ssl_ctx) {
  1513. SSL_CTX_free(rtp->ssl_ctx);
  1514. rtp->ssl_ctx = NULL;
  1515. }
  1516. if (rtp->dtls.ssl) {
  1517. SSL_free(rtp->dtls.ssl);
  1518. rtp->dtls.ssl = NULL;
  1519. }
  1520. if (rtp->rtcp) {
  1521. ao2_unlock(instance);
  1522. dtls_srtp_stop_timeout_timer(instance, rtp, 1);
  1523. ao2_lock(instance);
  1524. if (rtp->rtcp->dtls.ssl) {
  1525. if (rtp->rtcp->dtls.ssl != ssl) {
  1526. SSL_free(rtp->rtcp->dtls.ssl);
  1527. }
  1528. rtp->rtcp->dtls.ssl = NULL;
  1529. }
  1530. }
  1531. }
  1532. /*! \pre instance is locked */
  1533. static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
  1534. {
  1535. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1536. if (SSL_is_init_finished(rtp->dtls.ssl)) {
  1537. SSL_shutdown(rtp->dtls.ssl);
  1538. rtp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
  1539. }
  1540. if (rtp->rtcp && SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
  1541. SSL_shutdown(rtp->rtcp->dtls.ssl);
  1542. rtp->rtcp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
  1543. }
  1544. }
  1545. /*! \pre instance is locked */
  1546. static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
  1547. {
  1548. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1549. return rtp->dtls.connection;
  1550. }
  1551. /*! \pre instance is locked */
  1552. static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
  1553. {
  1554. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1555. return rtp->dtls.dtls_setup;
  1556. }
  1557. static void dtls_set_setup(enum ast_rtp_dtls_setup *dtls_setup, enum ast_rtp_dtls_setup setup, SSL *ssl)
  1558. {
  1559. enum ast_rtp_dtls_setup old = *dtls_setup;
  1560. switch (setup) {
  1561. case AST_RTP_DTLS_SETUP_ACTIVE:
  1562. *dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
  1563. break;
  1564. case AST_RTP_DTLS_SETUP_PASSIVE:
  1565. *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
  1566. break;
  1567. case AST_RTP_DTLS_SETUP_ACTPASS:
  1568. /* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
  1569. if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
  1570. *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
  1571. }
  1572. break;
  1573. case AST_RTP_DTLS_SETUP_HOLDCONN:
  1574. *dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
  1575. break;
  1576. default:
  1577. /* This should never occur... if it does exit early as we don't know what state things are in */
  1578. return;
  1579. }
  1580. /* If the setup state did not change we go on as if nothing happened */
  1581. if (old == *dtls_setup) {
  1582. return;
  1583. }
  1584. /* If they don't want us to establish a connection wait until later */
  1585. if (*dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
  1586. return;
  1587. }
  1588. if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
  1589. SSL_set_connect_state(ssl);
  1590. } else if (*dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
  1591. SSL_set_accept_state(ssl);
  1592. } else {
  1593. return;
  1594. }
  1595. }
  1596. /*! \pre instance is locked */
  1597. static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
  1598. {
  1599. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1600. if (rtp->dtls.ssl) {
  1601. dtls_set_setup(&rtp->dtls.dtls_setup, setup, rtp->dtls.ssl);
  1602. }
  1603. if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
  1604. dtls_set_setup(&rtp->rtcp->dtls.dtls_setup, setup, rtp->rtcp->dtls.ssl);
  1605. }
  1606. }
  1607. /*! \pre instance is locked */
  1608. static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
  1609. {
  1610. char *tmp = ast_strdupa(fingerprint), *value;
  1611. int pos = 0;
  1612. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1613. if (hash != AST_RTP_DTLS_HASH_SHA1 && hash != AST_RTP_DTLS_HASH_SHA256) {
  1614. return;
  1615. }
  1616. rtp->remote_hash = hash;
  1617. while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
  1618. sscanf(value, "%02hhx", &rtp->remote_fingerprint[pos++]);
  1619. }
  1620. }
  1621. /*! \pre instance is locked */
  1622. static enum ast_rtp_dtls_hash ast_rtp_dtls_get_fingerprint_hash(struct ast_rtp_instance *instance)
  1623. {
  1624. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1625. return rtp->local_hash;
  1626. }
  1627. /*! \pre instance is locked */
  1628. static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance)
  1629. {
  1630. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1631. return rtp->local_fingerprint;
  1632. }
  1633. /* DTLS RTP Engine interface declaration */
  1634. static struct ast_rtp_engine_dtls ast_rtp_dtls = {
  1635. .set_configuration = ast_rtp_dtls_set_configuration,
  1636. .active = ast_rtp_dtls_active,
  1637. .stop = ast_rtp_dtls_stop,
  1638. .reset = ast_rtp_dtls_reset,
  1639. .get_connection = ast_rtp_dtls_get_connection,
  1640. .get_setup = ast_rtp_dtls_get_setup,
  1641. .set_setup = ast_rtp_dtls_set_setup,
  1642. .set_fingerprint = ast_rtp_dtls_set_fingerprint,
  1643. .get_fingerprint_hash = ast_rtp_dtls_get_fingerprint_hash,
  1644. .get_fingerprint = ast_rtp_dtls_get_fingerprint,
  1645. };
  1646. #endif
  1647. /* RTP Engine Declaration */
  1648. static struct ast_rtp_engine asterisk_rtp_engine = {
  1649. .name = "asterisk",
  1650. .new = ast_rtp_new,
  1651. .destroy = ast_rtp_destroy,
  1652. .dtmf_begin = ast_rtp_dtmf_begin,
  1653. .dtmf_end = ast_rtp_dtmf_end,
  1654. .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
  1655. .dtmf_mode_set = ast_rtp_dtmf_mode_set,
  1656. .dtmf_mode_get = ast_rtp_dtmf_mode_get,
  1657. .update_source = ast_rtp_update_source,
  1658. .change_source = ast_rtp_change_source,
  1659. .write = ast_rtp_write,
  1660. .read = ast_rtp_read,
  1661. .prop_set = ast_rtp_prop_set,
  1662. .fd = ast_rtp_fd,
  1663. .remote_address_set = ast_rtp_remote_address_set,
  1664. .red_init = rtp_red_init,
  1665. .red_buffer = rtp_red_buffer,
  1666. .local_bridge = ast_rtp_local_bridge,
  1667. .get_stat = ast_rtp_get_stat,
  1668. .dtmf_compatible = ast_rtp_dtmf_compatible,
  1669. .stun_request = ast_rtp_stun_request,
  1670. .stop = ast_rtp_stop,
  1671. .qos = ast_rtp_qos_set,
  1672. .sendcng = ast_rtp_sendcng,
  1673. #ifdef HAVE_PJPROJECT
  1674. .ice = &ast_rtp_ice,
  1675. #endif
  1676. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  1677. .dtls = &ast_rtp_dtls,
  1678. .activate = ast_rtp_activate,
  1679. #endif
  1680. };
  1681. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  1682. /*! \pre instance is locked */
  1683. static void dtls_perform_handshake(struct ast_rtp_instance *instance, struct dtls_details *dtls, int rtcp)
  1684. {
  1685. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1686. /* If we are not acting as a client connecting to the remote side then
  1687. * don't start the handshake as it will accomplish nothing and would conflict
  1688. * with the handshake we receive from the remote side.
  1689. */
  1690. if (!dtls->ssl || (dtls->dtls_setup != AST_RTP_DTLS_SETUP_ACTIVE)) {
  1691. return;
  1692. }
  1693. SSL_do_handshake(dtls->ssl);
  1694. /*
  1695. * A race condition is prevented between this function and __rtp_recvfrom()
  1696. * because both functions have to get the instance lock before they can do
  1697. * anything. Without holding the instance lock, this function could start
  1698. * the SSL handshake above in one thread and the __rtp_recvfrom() function
  1699. * called by the channel thread could read the response and stop the timeout
  1700. * timer before we have a chance to even start it.
  1701. */
  1702. dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
  1703. /*
  1704. * We must call dtls_srtp_check_pending() after starting the timer.
  1705. * Otherwise we won't prevent the race condition.
  1706. */
  1707. dtls_srtp_check_pending(instance, rtp, rtcp);
  1708. }
  1709. #endif
  1710. #ifdef HAVE_PJPROJECT
  1711. static void rtp_learning_start(struct ast_rtp *rtp);
  1712. /* PJPROJECT ICE callback */
  1713. static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
  1714. {
  1715. struct ast_rtp_instance *instance = ice->user_data;
  1716. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1717. ao2_lock(instance);
  1718. if (status == PJ_SUCCESS) {
  1719. struct ast_sockaddr remote_address;
  1720. ast_sockaddr_setnull(&remote_address);
  1721. update_address_with_ice_candidate(ice, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
  1722. if (!ast_sockaddr_isnull(&remote_address)) {
  1723. /* Symmetric RTP must be disabled for the remote address to not get overwritten */
  1724. ast_rtp_instance_set_prop(instance, AST_RTP_PROPERTY_NAT, 0);
  1725. ast_rtp_instance_set_remote_address(instance, &remote_address);
  1726. }
  1727. if (rtp->rtcp) {
  1728. update_address_with_ice_candidate(ice, AST_RTP_ICE_COMPONENT_RTCP, &rtp->rtcp->them);
  1729. }
  1730. }
  1731. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  1732. dtls_perform_handshake(instance, &rtp->dtls, 0);
  1733. if (rtp->rtcp && rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
  1734. dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
  1735. }
  1736. #endif
  1737. if (!strictrtp) {
  1738. ao2_unlock(instance);
  1739. return;
  1740. }
  1741. ast_verb(4, "%p -- Strict RTP learning after ICE completion\n", rtp);
  1742. rtp_learning_start(rtp);
  1743. ao2_unlock(instance);
  1744. }
  1745. /* PJPROJECT ICE callback */
  1746. static void ast_rtp_on_ice_rx_data(pj_ice_sess *ice, unsigned comp_id, unsigned transport_id, void *pkt, pj_size_t size, const pj_sockaddr_t *src_addr, unsigned src_addr_len)
  1747. {
  1748. struct ast_rtp_instance *instance = ice->user_data;
  1749. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1750. /* Instead of handling the packet here (which really doesn't work with our architecture) we set a bit to indicate that it should be handled after pj_ice_sess_on_rx_pkt
  1751. * returns */
  1752. if (transport_id == TRANSPORT_SOCKET_RTP || transport_id == TRANSPORT_SOCKET_RTCP) {
  1753. rtp->passthrough = 1;
  1754. } else if (transport_id == TRANSPORT_TURN_RTP) {
  1755. rtp->rtp_passthrough = 1;
  1756. } else if (transport_id == TRANSPORT_TURN_RTCP) {
  1757. rtp->rtcp_passthrough = 1;
  1758. }
  1759. }
  1760. /* PJPROJECT ICE callback */
  1761. static pj_status_t ast_rtp_on_ice_tx_pkt(pj_ice_sess *ice, unsigned comp_id, unsigned transport_id, const void *pkt, pj_size_t size, const pj_sockaddr_t *dst_addr, unsigned dst_addr_len)
  1762. {
  1763. struct ast_rtp_instance *instance = ice->user_data;
  1764. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1765. pj_status_t status = PJ_EINVALIDOP;
  1766. pj_ssize_t _size = (pj_ssize_t)size;
  1767. if (transport_id == TRANSPORT_SOCKET_RTP) {
  1768. /* Traffic is destined to go right out the RTP socket we already have */
  1769. status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
  1770. /* sendto on a connectionless socket should send all the data, or none at all */
  1771. ast_assert(_size == size || status != PJ_SUCCESS);
  1772. } else if (transport_id == TRANSPORT_SOCKET_RTCP) {
  1773. /* Traffic is destined to go right out the RTCP socket we already have */
  1774. if (rtp->rtcp) {
  1775. status = pj_sock_sendto(rtp->rtcp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
  1776. /* sendto on a connectionless socket should send all the data, or none at all */
  1777. ast_assert(_size == size || status != PJ_SUCCESS);
  1778. } else {
  1779. status = PJ_SUCCESS;
  1780. }
  1781. } else if (transport_id == TRANSPORT_TURN_RTP) {
  1782. /* Traffic is going through the RTP TURN relay */
  1783. if (rtp->turn_rtp) {
  1784. status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
  1785. }
  1786. } else if (transport_id == TRANSPORT_TURN_RTCP) {
  1787. /* Traffic is going through the RTCP TURN relay */
  1788. if (rtp->turn_rtcp) {
  1789. status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
  1790. }
  1791. }
  1792. return status;
  1793. }
  1794. /* ICE Session interface declaration */
  1795. static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
  1796. .on_ice_complete = ast_rtp_on_ice_complete,
  1797. .on_rx_data = ast_rtp_on_ice_rx_data,
  1798. .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
  1799. };
  1800. /*! \brief Worker thread for timerheap */
  1801. static int timer_worker_thread(void *data)
  1802. {
  1803. pj_ioqueue_t *ioqueue;
  1804. if (pj_ioqueue_create(pool, 1, &ioqueue) != PJ_SUCCESS) {
  1805. return -1;
  1806. }
  1807. while (!timer_terminate) {
  1808. const pj_time_val delay = {0, 10};
  1809. pj_timer_heap_poll(timer_heap, NULL);
  1810. pj_ioqueue_poll(ioqueue, &delay);
  1811. }
  1812. return 0;
  1813. }
  1814. #endif
  1815. static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
  1816. {
  1817. if (!rtpdebug) {
  1818. return 0;
  1819. }
  1820. if (!ast_sockaddr_isnull(&rtpdebugaddr)) {
  1821. if (rtpdebugport) {
  1822. return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
  1823. } else {
  1824. return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
  1825. }
  1826. }
  1827. return 1;
  1828. }
  1829. static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
  1830. {
  1831. if (!rtcpdebug) {
  1832. return 0;
  1833. }
  1834. if (!ast_sockaddr_isnull(&rtcpdebugaddr)) {
  1835. if (rtcpdebugport) {
  1836. return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
  1837. } else {
  1838. return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
  1839. }
  1840. }
  1841. return 1;
  1842. }
  1843. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  1844. /*! \pre instance is locked */
  1845. static int dtls_srtp_handle_timeout(struct ast_rtp_instance *instance, int rtcp)
  1846. {
  1847. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1848. struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
  1849. struct timeval dtls_timeout;
  1850. DTLSv1_handle_timeout(dtls->ssl);
  1851. dtls_srtp_check_pending(instance, rtp, rtcp);
  1852. /* If a timeout can't be retrieved then this recurring scheduled item must stop */
  1853. if (!DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
  1854. dtls->timeout_timer = -1;
  1855. return 0;
  1856. }
  1857. return dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
  1858. }
  1859. /* Scheduler callback */
  1860. static int dtls_srtp_handle_rtp_timeout(const void *data)
  1861. {
  1862. struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
  1863. int reschedule;
  1864. ao2_lock(instance);
  1865. reschedule = dtls_srtp_handle_timeout(instance, 0);
  1866. ao2_unlock(instance);
  1867. if (!reschedule) {
  1868. ao2_ref(instance, -1);
  1869. }
  1870. return reschedule;
  1871. }
  1872. /* Scheduler callback */
  1873. static int dtls_srtp_handle_rtcp_timeout(const void *data)
  1874. {
  1875. struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
  1876. int reschedule;
  1877. ao2_lock(instance);
  1878. reschedule = dtls_srtp_handle_timeout(instance, 1);
  1879. ao2_unlock(instance);
  1880. if (!reschedule) {
  1881. ao2_ref(instance, -1);
  1882. }
  1883. return reschedule;
  1884. }
  1885. static void dtls_srtp_start_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
  1886. {
  1887. struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
  1888. struct timeval dtls_timeout;
  1889. if (DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
  1890. int timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
  1891. ast_assert(dtls->timeout_timer == -1);
  1892. ao2_ref(instance, +1);
  1893. if ((dtls->timeout_timer = ast_sched_add(rtp->sched, timeout,
  1894. !rtcp ? dtls_srtp_handle_rtp_timeout : dtls_srtp_handle_rtcp_timeout, instance)) < 0) {
  1895. ao2_ref(instance, -1);
  1896. ast_log(LOG_WARNING, "Scheduling '%s' DTLS retransmission for RTP instance [%p] failed.\n",
  1897. !rtcp ? "RTP" : "RTCP", instance);
  1898. }
  1899. }
  1900. }
  1901. /*! \pre Must not be called with the instance locked. */
  1902. static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
  1903. {
  1904. struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
  1905. AST_SCHED_DEL_UNREF(rtp->sched, dtls->timeout_timer, ao2_ref(instance, -1));
  1906. }
  1907. /*! \pre instance is locked */
  1908. static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
  1909. {
  1910. struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
  1911. size_t pending;
  1912. if (!dtls->ssl || !dtls->write_bio) {
  1913. return;
  1914. }
  1915. pending = BIO_ctrl_pending(dtls->write_bio);
  1916. if (pending > 0) {
  1917. char outgoing[pending];
  1918. size_t out;
  1919. struct ast_sockaddr remote_address = { {0, } };
  1920. int ice;
  1921. if (!rtcp) {
  1922. ast_rtp_instance_get_remote_address(instance, &remote_address);
  1923. } else {
  1924. ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
  1925. }
  1926. /* If we do not yet know an address to send this to defer it until we do */
  1927. if (ast_sockaddr_isnull(&remote_address)) {
  1928. return;
  1929. }
  1930. out = BIO_read(dtls->write_bio, outgoing, sizeof(outgoing));
  1931. __rtp_sendto(instance, outgoing, out, 0, &remote_address, rtcp, &ice, 0);
  1932. }
  1933. }
  1934. /* Scheduler callback */
  1935. static int dtls_srtp_renegotiate(const void *data)
  1936. {
  1937. struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
  1938. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1939. ao2_lock(instance);
  1940. SSL_renegotiate(rtp->dtls.ssl);
  1941. SSL_do_handshake(rtp->dtls.ssl);
  1942. dtls_srtp_check_pending(instance, rtp, 0);
  1943. if (rtp->rtcp && rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
  1944. SSL_renegotiate(rtp->rtcp->dtls.ssl);
  1945. SSL_do_handshake(rtp->rtcp->dtls.ssl);
  1946. dtls_srtp_check_pending(instance, rtp, 1);
  1947. }
  1948. rtp->rekeyid = -1;
  1949. ao2_unlock(instance);
  1950. ao2_ref(instance, -1);
  1951. return 0;
  1952. }
  1953. static int dtls_srtp_setup(struct ast_rtp *rtp, struct ast_srtp *srtp, struct ast_rtp_instance *instance, int rtcp)
  1954. {
  1955. unsigned char material[SRTP_MASTER_LEN * 2];
  1956. unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
  1957. struct ast_srtp_policy *local_policy, *remote_policy = NULL;
  1958. struct ast_rtp_instance_stats stats = { 0, };
  1959. int res = -1;
  1960. struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
  1961. /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
  1962. if (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) {
  1963. X509 *certificate;
  1964. if (!(certificate = SSL_get_peer_certificate(dtls->ssl))) {
  1965. ast_log(LOG_WARNING, "No certificate was provided by the peer on RTP instance '%p'\n", instance);
  1966. return -1;
  1967. }
  1968. /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
  1969. if (rtp->remote_fingerprint[0]) {
  1970. const EVP_MD *type;
  1971. unsigned char fingerprint[EVP_MAX_MD_SIZE];
  1972. unsigned int size;
  1973. if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA1) {
  1974. type = EVP_sha1();
  1975. } else if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA256) {
  1976. type = EVP_sha256();
  1977. } else {
  1978. ast_log(LOG_WARNING, "Unsupported fingerprint hash type on RTP instance '%p'\n", instance);
  1979. return -1;
  1980. }
  1981. if (!X509_digest(certificate, type, fingerprint, &size) ||
  1982. !size ||
  1983. memcmp(fingerprint, rtp->remote_fingerprint, size)) {
  1984. X509_free(certificate);
  1985. ast_log(LOG_WARNING, "Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
  1986. instance);
  1987. return -1;
  1988. }
  1989. }
  1990. X509_free(certificate);
  1991. }
  1992. /* Ensure that certificate verification was successful */
  1993. if ((rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) && SSL_get_verify_result(dtls->ssl) != X509_V_OK) {
  1994. ast_log(LOG_WARNING, "Peer certificate on RTP instance '%p' failed verification test\n",
  1995. instance);
  1996. return -1;
  1997. }
  1998. /* Produce key information and set up SRTP */
  1999. if (!SSL_export_keying_material(dtls->ssl, material, SRTP_MASTER_LEN * 2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
  2000. ast_log(LOG_WARNING, "Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
  2001. instance);
  2002. return -1;
  2003. }
  2004. /* Whether we are acting as a server or client determines where the keys/salts are */
  2005. if (rtp->dtls.dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
  2006. local_key = material;
  2007. remote_key = local_key + SRTP_MASTER_KEY_LEN;
  2008. local_salt = remote_key + SRTP_MASTER_KEY_LEN;
  2009. remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
  2010. } else {
  2011. remote_key = material;
  2012. local_key = remote_key + SRTP_MASTER_KEY_LEN;
  2013. remote_salt = local_key + SRTP_MASTER_KEY_LEN;
  2014. local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
  2015. }
  2016. if (!(local_policy = res_srtp_policy->alloc())) {
  2017. return -1;
  2018. }
  2019. if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
  2020. ast_log(LOG_WARNING, "Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
  2021. goto error;
  2022. }
  2023. if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
  2024. ast_log(LOG_WARNING, "Could not set suite to '%u' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
  2025. goto error;
  2026. }
  2027. if (ast_rtp_instance_get_stats(instance, &stats, AST_RTP_INSTANCE_STAT_LOCAL_SSRC)) {
  2028. goto error;
  2029. }
  2030. res_srtp_policy->set_ssrc(local_policy, stats.local_ssrc, 0);
  2031. if (!(remote_policy = res_srtp_policy->alloc())) {
  2032. goto error;
  2033. }
  2034. if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
  2035. ast_log(LOG_WARNING, "Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
  2036. goto error;
  2037. }
  2038. if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
  2039. ast_log(LOG_WARNING, "Could not set suite to '%u' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
  2040. goto error;
  2041. }
  2042. res_srtp_policy->set_ssrc(remote_policy, 0, 1);
  2043. if (ast_rtp_instance_add_srtp_policy(instance, remote_policy, local_policy, rtcp)) {
  2044. ast_log(LOG_WARNING, "Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
  2045. goto error;
  2046. }
  2047. if (rtp->rekey) {
  2048. ao2_ref(instance, +1);
  2049. if ((rtp->rekeyid = ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
  2050. ao2_ref(instance, -1);
  2051. goto error;
  2052. }
  2053. }
  2054. res = 0;
  2055. error:
  2056. /* policy->destroy() called even on success to release local reference to these resources */
  2057. res_srtp_policy->destroy(local_policy);
  2058. if (remote_policy) {
  2059. res_srtp_policy->destroy(remote_policy);
  2060. }
  2061. return res;
  2062. }
  2063. #endif
  2064. static int rtcp_mux(struct ast_rtp *rtp, const unsigned char *packet)
  2065. {
  2066. uint8_t version;
  2067. uint8_t pt;
  2068. uint8_t m;
  2069. if (!rtp->rtcp || rtp->rtcp->type != AST_RTP_INSTANCE_RTCP_MUX) {
  2070. return 0;
  2071. }
  2072. version = (packet[0] & 0XC0) >> 6;
  2073. if (version == 0) {
  2074. /* version 0 indicates this is a STUN packet and shouldn't
  2075. * be interpreted as a possible RTCP packet
  2076. */
  2077. return 0;
  2078. }
  2079. /* The second octet of a packet will be one of the following:
  2080. * For RTP: The marker bit (1 bit) and the RTP payload type (7 bits)
  2081. * For RTCP: The payload type (8)
  2082. *
  2083. * RTP has a forbidden range of payload types (64-95) since these
  2084. * will conflict with RTCP payload numbers if the marker bit is set.
  2085. */
  2086. m = packet[1] & 0x80;
  2087. pt = packet[1] & 0x7F;
  2088. if (m && pt >= 64 && pt <= 95) {
  2089. return 1;
  2090. }
  2091. return 0;
  2092. }
  2093. /*! \pre instance is locked */
  2094. static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
  2095. {
  2096. int len;
  2097. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2098. struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance, rtcp);
  2099. char *in = buf;
  2100. #ifdef HAVE_PJPROJECT
  2101. struct ast_sockaddr *loop = rtcp ? &rtp->rtcp_loop : &rtp->rtp_loop;
  2102. #endif
  2103. if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
  2104. return len;
  2105. }
  2106. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  2107. /* If this is an SSL packet pass it to OpenSSL for processing. RFC section for first byte value:
  2108. * https://tools.ietf.org/html/rfc5764#section-5.1.2 */
  2109. if ((*in >= 20) && (*in <= 63)) {
  2110. struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
  2111. int res = 0;
  2112. /* If no SSL session actually exists terminate things */
  2113. if (!dtls->ssl) {
  2114. ast_log(LOG_ERROR, "Received SSL traffic on RTP instance '%p' without an SSL session\n",
  2115. instance);
  2116. return -1;
  2117. }
  2118. /*
  2119. * A race condition is prevented between dtls_perform_handshake()
  2120. * and this function because both functions have to get the
  2121. * instance lock before they can do anything. The
  2122. * dtls_perform_handshake() function needs to start the timer
  2123. * before we stop it below.
  2124. */
  2125. /* Before we feed data into OpenSSL ensure that the timeout timer is either stopped or completed */
  2126. ao2_unlock(instance);
  2127. dtls_srtp_stop_timeout_timer(instance, rtp, rtcp);
  2128. ao2_lock(instance);
  2129. /* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
  2130. if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
  2131. dtls->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
  2132. SSL_set_accept_state(dtls->ssl);
  2133. }
  2134. dtls_srtp_check_pending(instance, rtp, rtcp);
  2135. BIO_write(dtls->read_bio, buf, len);
  2136. len = SSL_read(dtls->ssl, buf, len);
  2137. if ((len < 0) && (SSL_get_error(dtls->ssl, len) == SSL_ERROR_SSL)) {
  2138. unsigned long error = ERR_get_error();
  2139. ast_log(LOG_ERROR, "DTLS failure occurred on RTP instance '%p' due to reason '%s', terminating\n",
  2140. instance, ERR_reason_error_string(error));
  2141. return -1;
  2142. }
  2143. dtls_srtp_check_pending(instance, rtp, rtcp);
  2144. if (SSL_is_init_finished(dtls->ssl)) {
  2145. /* Any further connections will be existing since this is now established */
  2146. dtls->connection = AST_RTP_DTLS_CONNECTION_EXISTING;
  2147. /* Use the keying material to set up key/salt information */
  2148. res = dtls_srtp_setup(rtp, srtp, instance, rtcp);
  2149. } else {
  2150. /* Since we've sent additional traffic start the timeout timer for retransmission */
  2151. dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
  2152. }
  2153. return res;
  2154. }
  2155. #endif
  2156. #ifdef HAVE_PJPROJECT
  2157. if (!ast_sockaddr_isnull(loop) && !ast_sockaddr_cmp(loop, sa)) {
  2158. /* ICE traffic will have been handled in the TURN callback, so skip it but update the address
  2159. * so it reflects the actual source and not the loopback
  2160. */
  2161. if (rtcp) {
  2162. ast_sockaddr_copy(sa, &rtp->rtcp->them);
  2163. } else {
  2164. ast_rtp_instance_get_remote_address(instance, sa);
  2165. }
  2166. } else if (rtp->ice) {
  2167. pj_str_t combined = pj_str(ast_sockaddr_stringify(sa));
  2168. pj_sockaddr address;
  2169. pj_status_t status;
  2170. struct ice_wrap *ice;
  2171. pj_thread_register_check();
  2172. pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
  2173. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  2174. ice = rtp->ice;
  2175. ao2_ref(ice, +1);
  2176. ao2_unlock(instance);
  2177. status = pj_ice_sess_on_rx_pkt(ice->real_ice,
  2178. rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP,
  2179. rtcp ? TRANSPORT_SOCKET_RTCP : TRANSPORT_SOCKET_RTP, buf, len, &address,
  2180. pj_sockaddr_get_len(&address));
  2181. ao2_ref(ice, -1);
  2182. ao2_lock(instance);
  2183. if (status != PJ_SUCCESS) {
  2184. char buf[100];
  2185. pj_strerror(status, buf, sizeof(buf));
  2186. ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
  2187. (int)status, buf);
  2188. return -1;
  2189. }
  2190. if (!rtp->passthrough) {
  2191. /* If a unidirectional ICE negotiation occurs then lock on to the source of the
  2192. * ICE traffic and use it as the target. This will occur if the remote side only
  2193. * wants to receive media but never send to us.
  2194. */
  2195. if (!rtp->ice_active_remote_candidates && !rtp->ice_proposed_remote_candidates) {
  2196. if (rtcp) {
  2197. ast_sockaddr_copy(&rtp->rtcp->them, sa);
  2198. } else {
  2199. ast_rtp_instance_set_remote_address(instance, sa);
  2200. }
  2201. }
  2202. return 0;
  2203. }
  2204. rtp->passthrough = 0;
  2205. }
  2206. #endif
  2207. if ((*in & 0xC0) && res_srtp && srtp && res_srtp->unprotect(
  2208. srtp, buf, &len, rtcp || rtcp_mux(rtp, buf)) < 0) {
  2209. return -1;
  2210. }
  2211. return len;
  2212. }
  2213. /*! \pre instance is locked */
  2214. static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
  2215. {
  2216. return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
  2217. }
  2218. /*! \pre instance is locked */
  2219. static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
  2220. {
  2221. return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
  2222. }
  2223. /*! \pre instance is locked */
  2224. static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *via_ice, int use_srtp)
  2225. {
  2226. int len = size;
  2227. void *temp = buf;
  2228. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2229. struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance, rtcp);
  2230. int res;
  2231. *via_ice = 0;
  2232. if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
  2233. return -1;
  2234. }
  2235. #ifdef HAVE_PJPROJECT
  2236. if (rtp->ice) {
  2237. enum ast_rtp_ice_component_type component = rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP;
  2238. pj_status_t status;
  2239. struct ice_wrap *ice;
  2240. /* If RTCP is sharing the same socket then use the same component */
  2241. if (rtcp && rtp->rtcp->s == rtp->s) {
  2242. component = AST_RTP_ICE_COMPONENT_RTP;
  2243. }
  2244. pj_thread_register_check();
  2245. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  2246. ice = rtp->ice;
  2247. ao2_ref(ice, +1);
  2248. ao2_unlock(instance);
  2249. status = pj_ice_sess_send_data(ice->real_ice, component, temp, len);
  2250. ao2_ref(ice, -1);
  2251. ao2_lock(instance);
  2252. if (status == PJ_SUCCESS) {
  2253. *via_ice = 1;
  2254. return len;
  2255. }
  2256. }
  2257. #endif
  2258. res = ast_sendto(rtcp ? rtp->rtcp->s : rtp->s, temp, len, flags, sa);
  2259. if (res > 0) {
  2260. ast_rtp_instance_set_last_tx(instance, time(NULL));
  2261. }
  2262. return res;
  2263. }
  2264. /*! \pre instance is locked */
  2265. static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
  2266. {
  2267. return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
  2268. }
  2269. /*! \pre instance is locked */
  2270. static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
  2271. {
  2272. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2273. int hdrlen = 12;
  2274. int res;
  2275. if ((res = __rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1)) > 0) {
  2276. rtp->txcount++;
  2277. rtp->txoctetcount += (res - hdrlen);
  2278. }
  2279. return res;
  2280. }
  2281. static int rtp_get_rate(struct ast_format *format)
  2282. {
  2283. /* For those wondering: due to a fluke in RFC publication, G.722 is advertised
  2284. * as having a sample rate of 8kHz, while implementations must know that its
  2285. * real rate is 16kHz. Seriously.
  2286. */
  2287. return (ast_format_cmp(format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) ? 8000 : (int)ast_format_get_sample_rate(format);
  2288. }
  2289. static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
  2290. {
  2291. unsigned int interval;
  2292. /*! \todo XXX Do a more reasonable calculation on this one
  2293. * Look in RFC 3550 Section A.7 for an example*/
  2294. interval = rtcpinterval;
  2295. return interval;
  2296. }
  2297. /*! \brief Calculate normal deviation */
  2298. static double normdev_compute(double normdev, double sample, unsigned int sample_count)
  2299. {
  2300. normdev = normdev * sample_count + sample;
  2301. sample_count++;
  2302. return normdev / sample_count;
  2303. }
  2304. static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
  2305. {
  2306. /*
  2307. for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
  2308. return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
  2309. we can compute the sigma^2 and that way we would have to do the sqrt only 1 time at the end and would save another pow 2 compute
  2310. optimized formula
  2311. */
  2312. #define SQUARE(x) ((x) * (x))
  2313. stddev = sample_count * stddev;
  2314. sample_count++;
  2315. return stddev +
  2316. ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
  2317. ( SQUARE(sample - normdev_curent) / sample_count );
  2318. #undef SQUARE
  2319. }
  2320. static int create_new_socket(const char *type, int af)
  2321. {
  2322. int sock = ast_socket_nonblock(af, SOCK_DGRAM, 0);
  2323. if (sock < 0) {
  2324. ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
  2325. return sock;
  2326. }
  2327. #ifdef SO_NO_CHECK
  2328. if (nochecksums) {
  2329. setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
  2330. }
  2331. #endif
  2332. return sock;
  2333. }
  2334. /*!
  2335. * \internal
  2336. * \brief Initializes sequence values and probation for learning mode.
  2337. * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
  2338. *
  2339. * \param info The learning information to track
  2340. * \param seq sequence number read from the rtp header to initialize the information with
  2341. */
  2342. static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
  2343. {
  2344. info->max_seq = seq;
  2345. info->packets = learning_min_sequential;
  2346. memset(&info->received, 0, sizeof(info->received));
  2347. }
  2348. /*!
  2349. * \internal
  2350. * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
  2351. * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
  2352. *
  2353. * \param info Structure tracking the learning progress of some address
  2354. * \param seq sequence number read from the rtp header
  2355. * \retval 0 if probation mode should exit for this address
  2356. * \retval non-zero if probation mode should continue
  2357. */
  2358. static int rtp_learning_rtp_seq_update(struct rtp_learning_info *info, uint16_t seq)
  2359. {
  2360. if (seq == (uint16_t) (info->max_seq + 1)) {
  2361. /* packet is in sequence */
  2362. info->packets--;
  2363. } else {
  2364. /* Sequence discontinuity; reset */
  2365. info->packets = learning_min_sequential - 1;
  2366. info->received = ast_tvnow();
  2367. }
  2368. /* Only check time if strictrtp is set to yes. Otherwise, we only needed to check seqno */
  2369. if (strictrtp == STRICT_RTP_YES) {
  2370. switch (info->stream_type) {
  2371. case AST_MEDIA_TYPE_UNKNOWN:
  2372. case AST_MEDIA_TYPE_AUDIO:
  2373. /*
  2374. * Protect against packet floods by checking that we
  2375. * received the packet sequence in at least the minimum
  2376. * allowed time.
  2377. */
  2378. if (ast_tvzero(info->received)) {
  2379. info->received = ast_tvnow();
  2380. } else if (!info->packets
  2381. && ast_tvdiff_ms(ast_tvnow(), info->received) < learning_min_duration) {
  2382. /* Packet flood; reset */
  2383. info->packets = learning_min_sequential - 1;
  2384. info->received = ast_tvnow();
  2385. }
  2386. break;
  2387. case AST_MEDIA_TYPE_VIDEO:
  2388. case AST_MEDIA_TYPE_IMAGE:
  2389. case AST_MEDIA_TYPE_TEXT:
  2390. break;
  2391. }
  2392. }
  2393. info->max_seq = seq;
  2394. return info->packets;
  2395. }
  2396. /*!
  2397. * \brief Start the strictrtp learning mode.
  2398. *
  2399. * \param rtp RTP session description
  2400. *
  2401. * \return Nothing
  2402. */
  2403. static void rtp_learning_start(struct ast_rtp *rtp)
  2404. {
  2405. rtp->strict_rtp_state = STRICT_RTP_LEARN;
  2406. memset(&rtp->rtp_source_learn.proposed_address, 0,
  2407. sizeof(rtp->rtp_source_learn.proposed_address));
  2408. rtp->rtp_source_learn.start = ast_tvnow();
  2409. rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t) rtp->lastrxseqno);
  2410. }
  2411. #ifdef HAVE_PJPROJECT
  2412. /*!
  2413. * \internal
  2414. * \brief Checks an address against the ICE blacklist
  2415. * \note If there is no ice_blacklist list, always returns 0
  2416. *
  2417. * \param address The address to consider
  2418. * \retval 0 if address is not ICE blacklisted
  2419. * \retval 1 if address is ICE blacklisted
  2420. */
  2421. static int rtp_address_is_ice_blacklisted(const pj_sockaddr_t *address)
  2422. {
  2423. char buf[PJ_INET6_ADDRSTRLEN];
  2424. struct ast_sockaddr saddr;
  2425. int result = 1;
  2426. ast_sockaddr_parse(&saddr, pj_sockaddr_print(address, buf, sizeof(buf), 0), 0);
  2427. ast_rwlock_rdlock(&ice_blacklist_lock);
  2428. if (!ice_blacklist || (ast_apply_ha(ice_blacklist, &saddr) == AST_SENSE_ALLOW)) {
  2429. result = 0;
  2430. }
  2431. ast_rwlock_unlock(&ice_blacklist_lock);
  2432. return result;
  2433. }
  2434. /*!
  2435. * \internal
  2436. * \brief Checks an address against the STUN blacklist
  2437. * \since 13.16.0
  2438. *
  2439. * \note If there is no stun_blacklist list, always returns 0
  2440. *
  2441. * \param addr The address to consider
  2442. *
  2443. * \retval 0 if address is not STUN blacklisted
  2444. * \retval 1 if address is STUN blacklisted
  2445. */
  2446. static int stun_address_is_blacklisted(const struct ast_sockaddr *addr)
  2447. {
  2448. int result = 1;
  2449. ast_rwlock_rdlock(&stun_blacklist_lock);
  2450. if (!stun_blacklist
  2451. || ast_apply_ha(stun_blacklist, addr) == AST_SENSE_ALLOW) {
  2452. result = 0;
  2453. }
  2454. ast_rwlock_unlock(&stun_blacklist_lock);
  2455. return result;
  2456. }
  2457. /*! \pre instance is locked */
  2458. static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component,
  2459. int transport)
  2460. {
  2461. pj_sockaddr address[PJ_ICE_MAX_CAND];
  2462. unsigned int count = PJ_ARRAY_SIZE(address), pos = 0;
  2463. int basepos = -1;
  2464. /* Add all the local interface IP addresses */
  2465. if (ast_sockaddr_is_ipv4(addr)) {
  2466. pj_enum_ip_interface(pj_AF_INET(), &count, address);
  2467. } else if (ast_sockaddr_is_any(addr)) {
  2468. pj_enum_ip_interface(pj_AF_UNSPEC(), &count, address);
  2469. } else {
  2470. pj_enum_ip_interface(pj_AF_INET6(), &count, address);
  2471. }
  2472. host_candidate_overrides_apply(count, address);
  2473. for (pos = 0; pos < count; pos++) {
  2474. if (!rtp_address_is_ice_blacklisted(&address[pos])) {
  2475. if (basepos == -1) {
  2476. basepos = pos;
  2477. }
  2478. pj_sockaddr_set_port(&address[pos], port);
  2479. ast_rtp_ice_add_cand(instance, rtp, component, transport,
  2480. PJ_ICE_CAND_TYPE_HOST, 65535, &address[pos], &address[pos], NULL,
  2481. pj_sockaddr_get_len(&address[pos]));
  2482. }
  2483. }
  2484. if (basepos == -1) {
  2485. /* start with first address unless excluded above */
  2486. basepos = 0;
  2487. }
  2488. /* If configured to use a STUN server to get our external mapped address do so */
  2489. if (count && stunaddr.sin_addr.s_addr && !stun_address_is_blacklisted(addr) &&
  2490. (ast_sockaddr_is_ipv4(addr) || ast_sockaddr_is_any(addr))) {
  2491. struct sockaddr_in answer;
  2492. int rsp;
  2493. /*
  2494. * The instance should not be locked because we can block
  2495. * waiting for a STUN respone.
  2496. */
  2497. ao2_unlock(instance);
  2498. rsp = ast_stun_request(component == AST_RTP_ICE_COMPONENT_RTCP
  2499. ? rtp->rtcp->s : rtp->s, &stunaddr, NULL, &answer);
  2500. ao2_lock(instance);
  2501. if (!rsp) {
  2502. pj_sockaddr base;
  2503. /* Use the first local IPv4 host candidate as the base */
  2504. for (pos = basepos; pos < count; pos++) {
  2505. if (address[pos].addr.sa_family == PJ_AF_INET &&
  2506. !rtp_address_is_ice_blacklisted(&address[pos])) {
  2507. pj_sockaddr_cp(&base, &address[pos]);
  2508. break;
  2509. }
  2510. }
  2511. if (pos < count) {
  2512. pj_sockaddr ext;
  2513. pj_str_t mapped = pj_str(ast_strdupa(ast_inet_ntoa(answer.sin_addr)));
  2514. int srflx = 1;
  2515. pj_sockaddr_init(pj_AF_INET(), &ext, &mapped, ntohs(answer.sin_port));
  2516. /*
  2517. * If the returned address is the same as one of our host
  2518. * candidates, don't send the srflx
  2519. */
  2520. for (pos = 0; pos < count; pos++) {
  2521. if (pj_sockaddr_cmp(&address[pos], &ext) == 0 &&
  2522. !rtp_address_is_ice_blacklisted(&address[pos])) {
  2523. srflx = 0;
  2524. break;
  2525. }
  2526. }
  2527. if (srflx) {
  2528. ast_rtp_ice_add_cand(instance, rtp, component, transport,
  2529. PJ_ICE_CAND_TYPE_SRFLX, 65535, &ext, &base, &base,
  2530. pj_sockaddr_get_len(&ext));
  2531. }
  2532. }
  2533. }
  2534. }
  2535. /* If configured to use a TURN relay create a session and allocate */
  2536. if (pj_strlen(&turnaddr)) {
  2537. ast_rtp_ice_turn_request(instance, component, AST_TRANSPORT_TCP, pj_strbuf(&turnaddr), turnport,
  2538. pj_strbuf(&turnusername), pj_strbuf(&turnpassword));
  2539. }
  2540. }
  2541. #endif
  2542. /*!
  2543. * \internal
  2544. * \brief Calculates the elapsed time from issue of the first tx packet in an
  2545. * rtp session and a specified time
  2546. *
  2547. * \param rtp pointer to the rtp struct with the transmitted rtp packet
  2548. * \param delivery time of delivery - if NULL or zero value, will be ast_tvnow()
  2549. *
  2550. * \return time elapsed in milliseconds
  2551. */
  2552. static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
  2553. {
  2554. struct timeval t;
  2555. long ms;
  2556. if (ast_tvzero(rtp->txcore)) {
  2557. rtp->txcore = ast_tvnow();
  2558. rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
  2559. }
  2560. t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
  2561. if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
  2562. ms = 0;
  2563. }
  2564. rtp->txcore = t;
  2565. return (unsigned int) ms;
  2566. }
  2567. #ifdef HAVE_PJPROJECT
  2568. /*!
  2569. * \internal
  2570. * \brief Creates an ICE session. Can be used to replace a destroyed ICE session.
  2571. *
  2572. * \param instance RTP instance for which the ICE session is being replaced
  2573. * \param addr ast_sockaddr to use for adding RTP candidates to the ICE session
  2574. * \param port port to use for adding RTP candidates to the ICE session
  2575. * \param replace 0 when creating a new session, 1 when replacing a destroyed session
  2576. *
  2577. * \pre instance is locked
  2578. *
  2579. * \retval 0 on success
  2580. * \retval -1 on failure
  2581. */
  2582. static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
  2583. int port, int replace)
  2584. {
  2585. pj_stun_config stun_config;
  2586. pj_str_t ufrag, passwd;
  2587. pj_status_t status;
  2588. struct ice_wrap *ice_old;
  2589. struct ice_wrap *ice;
  2590. pj_ice_sess *real_ice = NULL;
  2591. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2592. ao2_cleanup(rtp->ice_local_candidates);
  2593. rtp->ice_local_candidates = NULL;
  2594. ice = ao2_alloc_options(sizeof(*ice), ice_wrap_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
  2595. if (!ice) {
  2596. ast_rtp_ice_stop(instance);
  2597. return -1;
  2598. }
  2599. pj_thread_register_check();
  2600. pj_stun_config_init(&stun_config, &cachingpool.factory, 0, NULL, timer_heap);
  2601. ufrag = pj_str(rtp->local_ufrag);
  2602. passwd = pj_str(rtp->local_passwd);
  2603. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  2604. ao2_unlock(instance);
  2605. /* Create an ICE session for ICE negotiation */
  2606. status = pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN,
  2607. rtp->ice_num_components, &ast_rtp_ice_sess_cb, &ufrag, &passwd, NULL, &real_ice);
  2608. ao2_lock(instance);
  2609. if (status == PJ_SUCCESS) {
  2610. /* Safely complete linking the ICE session into the instance */
  2611. real_ice->user_data = instance;
  2612. ice->real_ice = real_ice;
  2613. ice_old = rtp->ice;
  2614. rtp->ice = ice;
  2615. if (ice_old) {
  2616. ao2_unlock(instance);
  2617. ao2_ref(ice_old, -1);
  2618. ao2_lock(instance);
  2619. }
  2620. /* Add all of the available candidates to the ICE session */
  2621. rtp_add_candidates_to_ice(instance, rtp, addr, port, AST_RTP_ICE_COMPONENT_RTP,
  2622. TRANSPORT_SOCKET_RTP);
  2623. /* Only add the RTCP candidates to ICE when replacing the session and if
  2624. * the ICE session contains more than just an RTP component. New sessions
  2625. * handle this in a separate part of the setup phase */
  2626. if (replace && rtp->rtcp && rtp->ice_num_components > 1) {
  2627. rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us,
  2628. ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP,
  2629. TRANSPORT_SOCKET_RTCP);
  2630. }
  2631. return 0;
  2632. }
  2633. /*
  2634. * It is safe to unref this while instance is locked here.
  2635. * It was not initialized with a real_ice pointer.
  2636. */
  2637. ao2_ref(ice, -1);
  2638. ast_rtp_ice_stop(instance);
  2639. return -1;
  2640. }
  2641. #endif
  2642. /*! \pre instance is locked */
  2643. static int ast_rtp_new(struct ast_rtp_instance *instance,
  2644. struct ast_sched_context *sched, struct ast_sockaddr *addr,
  2645. void *data)
  2646. {
  2647. struct ast_rtp *rtp = NULL;
  2648. int x, startplace;
  2649. /* Create a new RTP structure to hold all of our data */
  2650. if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
  2651. return -1;
  2652. }
  2653. /* Set default parameters on the newly created RTP structure */
  2654. rtp->ssrc = ast_random();
  2655. rtp->seqno = ast_random() & 0x7fff;
  2656. rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_CLOSED : STRICT_RTP_OPEN);
  2657. /* Create a new socket for us to listen on and use */
  2658. if ((rtp->s =
  2659. create_new_socket("RTP",
  2660. ast_sockaddr_is_ipv4(addr) ? AF_INET :
  2661. ast_sockaddr_is_ipv6(addr) ? AF_INET6 : -1)) < 0) {
  2662. ast_log(LOG_WARNING, "Failed to create a new socket for RTP instance '%p'\n", instance);
  2663. ast_free(rtp);
  2664. return -1;
  2665. }
  2666. /* Now actually find a free RTP port to use */
  2667. x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
  2668. x = x & ~1;
  2669. startplace = x;
  2670. for (;;) {
  2671. ast_sockaddr_set_port(addr, x);
  2672. /* Try to bind, this will tell us whether the port is available or not */
  2673. if (!ast_bind(rtp->s, addr)) {
  2674. ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
  2675. ast_rtp_instance_set_local_address(instance, addr);
  2676. ast_test_suite_event_notify("RTP_PORT_ALLOCATED", "Port: %d", x);
  2677. break;
  2678. }
  2679. x += 2;
  2680. if (x > rtpend) {
  2681. x = (rtpstart + 1) & ~1;
  2682. }
  2683. /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
  2684. if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
  2685. ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
  2686. close(rtp->s);
  2687. ast_free(rtp);
  2688. return -1;
  2689. }
  2690. }
  2691. #ifdef HAVE_PJPROJECT
  2692. /* Initialize synchronization aspects */
  2693. ast_cond_init(&rtp->cond, NULL);
  2694. generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
  2695. generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
  2696. #endif
  2697. ast_rtp_instance_set_data(instance, rtp);
  2698. #ifdef HAVE_PJPROJECT
  2699. /* Create an ICE session for ICE negotiation */
  2700. if (icesupport) {
  2701. rtp->ice_num_components = 2;
  2702. ast_debug(3, "Creating ICE session %s (%d) for RTP instance '%p'\n", ast_sockaddr_stringify(addr), x, instance);
  2703. if (ice_create(instance, addr, x, 0)) {
  2704. ast_log(LOG_NOTICE, "Failed to create ICE session\n");
  2705. } else {
  2706. rtp->ice_port = x;
  2707. ast_sockaddr_copy(&rtp->ice_original_rtp_addr, addr);
  2708. }
  2709. }
  2710. #endif
  2711. /* Record any information we may need */
  2712. rtp->sched = sched;
  2713. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  2714. rtp->rekeyid = -1;
  2715. rtp->dtls.timeout_timer = -1;
  2716. #endif
  2717. rtp->f.subclass.format = ao2_bump(ast_format_none);
  2718. rtp->lastrxformat = ao2_bump(ast_format_none);
  2719. rtp->lasttxformat = ao2_bump(ast_format_none);
  2720. return 0;
  2721. }
  2722. /*! \pre instance is locked */
  2723. static int ast_rtp_destroy(struct ast_rtp_instance *instance)
  2724. {
  2725. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2726. #ifdef HAVE_PJPROJECT
  2727. struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
  2728. struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
  2729. #endif
  2730. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  2731. ast_rtp_dtls_stop(instance);
  2732. #endif
  2733. /* Destroy the smoother that was smoothing out audio if present */
  2734. if (rtp->smoother) {
  2735. ast_smoother_free(rtp->smoother);
  2736. }
  2737. /* Close our own socket so we no longer get packets */
  2738. if (rtp->s > -1) {
  2739. close(rtp->s);
  2740. }
  2741. /* Destroy RTCP if it was being used */
  2742. if (rtp->rtcp) {
  2743. /*
  2744. * It is not possible for there to be an active RTCP scheduler
  2745. * entry at this point since it holds a reference to the
  2746. * RTP instance while it's active.
  2747. */
  2748. if (rtp->rtcp->s > -1 && rtp->s != rtp->rtcp->s) {
  2749. close(rtp->rtcp->s);
  2750. }
  2751. ast_free(rtp->rtcp->local_addr_str);
  2752. ast_free(rtp->rtcp);
  2753. }
  2754. /* Destroy RED if it was being used */
  2755. if (rtp->red) {
  2756. ao2_unlock(instance);
  2757. AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
  2758. ao2_lock(instance);
  2759. ast_free(rtp->red);
  2760. rtp->red = NULL;
  2761. }
  2762. #ifdef HAVE_PJPROJECT
  2763. pj_thread_register_check();
  2764. /*
  2765. * The instance lock is already held.
  2766. *
  2767. * Destroy the RTP TURN relay if being used
  2768. */
  2769. if (rtp->turn_rtp) {
  2770. rtp->turn_state = PJ_TURN_STATE_NULL;
  2771. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  2772. ao2_unlock(instance);
  2773. pj_turn_sock_destroy(rtp->turn_rtp);
  2774. ao2_lock(instance);
  2775. while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
  2776. ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
  2777. }
  2778. }
  2779. /* Destroy the RTCP TURN relay if being used */
  2780. if (rtp->turn_rtcp) {
  2781. rtp->turn_state = PJ_TURN_STATE_NULL;
  2782. /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
  2783. ao2_unlock(instance);
  2784. pj_turn_sock_destroy(rtp->turn_rtcp);
  2785. ao2_lock(instance);
  2786. while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
  2787. ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
  2788. }
  2789. }
  2790. /* Destroy any ICE session */
  2791. ast_rtp_ice_stop(instance);
  2792. /* Destroy any candidates */
  2793. if (rtp->ice_local_candidates) {
  2794. ao2_ref(rtp->ice_local_candidates, -1);
  2795. }
  2796. if (rtp->ice_active_remote_candidates) {
  2797. ao2_ref(rtp->ice_active_remote_candidates, -1);
  2798. }
  2799. if (rtp->ioqueue) {
  2800. /*
  2801. * We cannot hold the instance lock because we could wait
  2802. * for the ioqueue thread to die and we might deadlock as
  2803. * a result.
  2804. */
  2805. ao2_unlock(instance);
  2806. rtp_ioqueue_thread_remove(rtp->ioqueue);
  2807. ao2_lock(instance);
  2808. }
  2809. #endif
  2810. ao2_cleanup(rtp->lasttxformat);
  2811. ao2_cleanup(rtp->lastrxformat);
  2812. ao2_cleanup(rtp->f.subclass.format);
  2813. #ifdef HAVE_PJPROJECT
  2814. /* Destroy synchronization items */
  2815. ast_cond_destroy(&rtp->cond);
  2816. #endif
  2817. /* Finally destroy ourselves */
  2818. ast_free(rtp);
  2819. return 0;
  2820. }
  2821. /*! \pre instance is locked */
  2822. static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
  2823. {
  2824. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2825. rtp->dtmfmode = dtmf_mode;
  2826. return 0;
  2827. }
  2828. /*! \pre instance is locked */
  2829. static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
  2830. {
  2831. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2832. return rtp->dtmfmode;
  2833. }
  2834. /*! \pre instance is locked */
  2835. static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
  2836. {
  2837. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2838. struct ast_sockaddr remote_address = { {0,} };
  2839. int hdrlen = 12, res = 0, i = 0, payload = 101;
  2840. char data[256];
  2841. unsigned int *rtpheader = (unsigned int*)data;
  2842. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2843. /* If we have no remote address information bail out now */
  2844. if (ast_sockaddr_isnull(&remote_address)) {
  2845. return -1;
  2846. }
  2847. /* Convert given digit into what we want to transmit */
  2848. if ((digit <= '9') && (digit >= '0')) {
  2849. digit -= '0';
  2850. } else if (digit == '*') {
  2851. digit = 10;
  2852. } else if (digit == '#') {
  2853. digit = 11;
  2854. } else if ((digit >= 'A') && (digit <= 'D')) {
  2855. digit = digit - 'A' + 12;
  2856. } else if ((digit >= 'a') && (digit <= 'd')) {
  2857. digit = digit - 'a' + 12;
  2858. } else {
  2859. ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
  2860. return -1;
  2861. }
  2862. /* Grab the payload that they expect the RFC2833 packet to be received in */
  2863. payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_DTMF);
  2864. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  2865. rtp->send_duration = 160;
  2866. rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
  2867. rtp->lastdigitts = rtp->lastts + rtp->send_duration;
  2868. /* Create the actual packet that we will be sending */
  2869. rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
  2870. rtpheader[1] = htonl(rtp->lastdigitts);
  2871. rtpheader[2] = htonl(rtp->ssrc);
  2872. /* Actually send the packet */
  2873. for (i = 0; i < 2; i++) {
  2874. int ice;
  2875. rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
  2876. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
  2877. if (res < 0) {
  2878. ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
  2879. ast_sockaddr_stringify(&remote_address),
  2880. strerror(errno));
  2881. }
  2882. if (rtp_debug_test_addr(&remote_address)) {
  2883. ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
  2884. ast_sockaddr_stringify(&remote_address),
  2885. ice ? " (via ICE)" : "",
  2886. payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  2887. }
  2888. rtp->seqno++;
  2889. rtp->send_duration += 160;
  2890. rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
  2891. }
  2892. /* Record that we are in the process of sending a digit and information needed to continue doing so */
  2893. rtp->sending_digit = 1;
  2894. rtp->send_digit = digit;
  2895. rtp->send_payload = payload;
  2896. return 0;
  2897. }
  2898. /*! \pre instance is locked */
  2899. static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
  2900. {
  2901. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2902. struct ast_sockaddr remote_address = { {0,} };
  2903. int hdrlen = 12, res = 0;
  2904. char data[256];
  2905. unsigned int *rtpheader = (unsigned int*)data;
  2906. int ice;
  2907. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2908. /* Make sure we know where the other side is so we can send them the packet */
  2909. if (ast_sockaddr_isnull(&remote_address)) {
  2910. return -1;
  2911. }
  2912. /* Actually create the packet we will be sending */
  2913. rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
  2914. rtpheader[1] = htonl(rtp->lastdigitts);
  2915. rtpheader[2] = htonl(rtp->ssrc);
  2916. rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
  2917. /* Boom, send it on out */
  2918. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
  2919. if (res < 0) {
  2920. ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
  2921. ast_sockaddr_stringify(&remote_address),
  2922. strerror(errno));
  2923. }
  2924. if (rtp_debug_test_addr(&remote_address)) {
  2925. ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
  2926. ast_sockaddr_stringify(&remote_address),
  2927. ice ? " (via ICE)" : "",
  2928. rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  2929. }
  2930. /* And now we increment some values for the next time we swing by */
  2931. rtp->seqno++;
  2932. rtp->send_duration += 160;
  2933. rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
  2934. return 0;
  2935. }
  2936. /*! \pre instance is locked */
  2937. static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
  2938. {
  2939. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2940. struct ast_sockaddr remote_address = { {0,} };
  2941. int hdrlen = 12, res = -1, i = 0;
  2942. char data[256];
  2943. unsigned int *rtpheader = (unsigned int*)data;
  2944. unsigned int measured_samples;
  2945. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2946. /* Make sure we know where the remote side is so we can send them the packet we construct */
  2947. if (ast_sockaddr_isnull(&remote_address)) {
  2948. goto cleanup;
  2949. }
  2950. /* Convert the given digit to the one we are going to send */
  2951. if ((digit <= '9') && (digit >= '0')) {
  2952. digit -= '0';
  2953. } else if (digit == '*') {
  2954. digit = 10;
  2955. } else if (digit == '#') {
  2956. digit = 11;
  2957. } else if ((digit >= 'A') && (digit <= 'D')) {
  2958. digit = digit - 'A' + 12;
  2959. } else if ((digit >= 'a') && (digit <= 'd')) {
  2960. digit = digit - 'a' + 12;
  2961. } else {
  2962. ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
  2963. goto cleanup;
  2964. }
  2965. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  2966. if (duration > 0 && (measured_samples = duration * rtp_get_rate(rtp->f.subclass.format) / 1000) > rtp->send_duration) {
  2967. ast_debug(2, "Adjusting final end duration from %d to %u\n", rtp->send_duration, measured_samples);
  2968. rtp->send_duration = measured_samples;
  2969. }
  2970. /* Construct the packet we are going to send */
  2971. rtpheader[1] = htonl(rtp->lastdigitts);
  2972. rtpheader[2] = htonl(rtp->ssrc);
  2973. rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
  2974. rtpheader[3] |= htonl((1 << 23));
  2975. /* Send it 3 times, that's the magical number */
  2976. for (i = 0; i < 3; i++) {
  2977. int ice;
  2978. rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
  2979. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
  2980. if (res < 0) {
  2981. ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
  2982. ast_sockaddr_stringify(&remote_address),
  2983. strerror(errno));
  2984. }
  2985. if (rtp_debug_test_addr(&remote_address)) {
  2986. ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
  2987. ast_sockaddr_stringify(&remote_address),
  2988. ice ? " (via ICE)" : "",
  2989. rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  2990. }
  2991. rtp->seqno++;
  2992. }
  2993. res = 0;
  2994. /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
  2995. rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
  2996. cleanup:
  2997. rtp->sending_digit = 0;
  2998. rtp->send_digit = 0;
  2999. return res;
  3000. }
  3001. /*! \pre instance is locked */
  3002. static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
  3003. {
  3004. return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
  3005. }
  3006. /*! \pre instance is locked */
  3007. static void ast_rtp_update_source(struct ast_rtp_instance *instance)
  3008. {
  3009. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3010. /* We simply set this bit so that the next packet sent will have the marker bit turned on */
  3011. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  3012. ast_debug(3, "Setting the marker bit due to a source update\n");
  3013. return;
  3014. }
  3015. /*! \pre instance is locked */
  3016. static void ast_rtp_change_source(struct ast_rtp_instance *instance)
  3017. {
  3018. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3019. struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance, 0);
  3020. struct ast_srtp *rtcp_srtp = ast_rtp_instance_get_srtp(instance, 1);
  3021. unsigned int ssrc = ast_random();
  3022. if (!rtp->lastts) {
  3023. ast_debug(3, "Not changing SSRC since we haven't sent any RTP yet\n");
  3024. return;
  3025. }
  3026. /* We simply set this bit so that the next packet sent will have the marker bit turned on */
  3027. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  3028. ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
  3029. if (srtp) {
  3030. ast_debug(3, "Changing ssrc for SRTP from %u to %u\n", rtp->ssrc, ssrc);
  3031. res_srtp->change_source(srtp, rtp->ssrc, ssrc);
  3032. if (rtcp_srtp != srtp) {
  3033. res_srtp->change_source(rtcp_srtp, rtp->ssrc, ssrc);
  3034. }
  3035. }
  3036. rtp->ssrc = ssrc;
  3037. return;
  3038. }
  3039. static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
  3040. {
  3041. unsigned int sec, usec, frac;
  3042. sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
  3043. usec = tv.tv_usec;
  3044. /*
  3045. * Convert usec to 0.32 bit fixed point without overflow.
  3046. *
  3047. * = usec * 2^32 / 10^6
  3048. * = usec * 2^32 / (2^6 * 5^6)
  3049. * = usec * 2^26 / 5^6
  3050. *
  3051. * The usec value needs 20 bits to represent 999999 usec. So
  3052. * splitting the 2^26 to get the most precision using 32 bit
  3053. * values gives:
  3054. *
  3055. * = ((usec * 2^12) / 5^6) * 2^14
  3056. *
  3057. * Splitting the division into two stages preserves all the
  3058. * available significant bits of usec over doing the division
  3059. * all at once.
  3060. *
  3061. * = ((((usec * 2^12) / 5^3) * 2^7) / 5^3) * 2^7
  3062. */
  3063. frac = ((((usec << 12) / 125) << 7) / 125) << 7;
  3064. *msw = sec;
  3065. *lsw = frac;
  3066. }
  3067. static void ntp2timeval(unsigned int msw, unsigned int lsw, struct timeval *tv)
  3068. {
  3069. tv->tv_sec = msw - 2208988800u;
  3070. /* Reverse the sequence in timeval2ntp() */
  3071. tv->tv_usec = ((((lsw >> 7) * 125) >> 7) * 125) >> 12;
  3072. }
  3073. static void calculate_lost_packet_statistics(struct ast_rtp *rtp,
  3074. unsigned int *lost_packets,
  3075. int *fraction_lost)
  3076. {
  3077. unsigned int extended_seq_no;
  3078. unsigned int expected_packets;
  3079. unsigned int expected_interval;
  3080. unsigned int received_interval;
  3081. double rxlost_current;
  3082. int lost_interval;
  3083. /* Compute statistics */
  3084. extended_seq_no = rtp->cycles + rtp->lastrxseqno;
  3085. expected_packets = extended_seq_no - rtp->seedrxseqno + 1;
  3086. if (rtp->rxcount > expected_packets) {
  3087. expected_packets += rtp->rxcount - expected_packets;
  3088. }
  3089. *lost_packets = expected_packets - rtp->rxcount;
  3090. expected_interval = expected_packets - rtp->rtcp->expected_prior;
  3091. received_interval = rtp->rxcount - rtp->rtcp->received_prior;
  3092. lost_interval = expected_interval - received_interval;
  3093. if (expected_interval == 0 || lost_interval <= 0) {
  3094. *fraction_lost = 0;
  3095. } else {
  3096. *fraction_lost = (lost_interval << 8) / expected_interval;
  3097. }
  3098. /* Update RTCP statistics */
  3099. rtp->rtcp->received_prior = rtp->rxcount;
  3100. rtp->rtcp->expected_prior = expected_packets;
  3101. if (lost_interval <= 0) {
  3102. rtp->rtcp->rxlost = 0;
  3103. } else {
  3104. rtp->rtcp->rxlost = lost_interval;
  3105. }
  3106. if (rtp->rtcp->rxlost_count == 0) {
  3107. rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
  3108. }
  3109. if (lost_interval < rtp->rtcp->minrxlost) {
  3110. rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
  3111. }
  3112. if (lost_interval > rtp->rtcp->maxrxlost) {
  3113. rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
  3114. }
  3115. rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost,
  3116. rtp->rtcp->rxlost,
  3117. rtp->rtcp->rxlost_count);
  3118. rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost,
  3119. rtp->rtcp->rxlost,
  3120. rtp->rtcp->normdev_rxlost,
  3121. rxlost_current,
  3122. rtp->rtcp->rxlost_count);
  3123. rtp->rtcp->normdev_rxlost = rxlost_current;
  3124. rtp->rtcp->rxlost_count++;
  3125. }
  3126. /*!
  3127. * \brief Send RTCP SR or RR report
  3128. *
  3129. * \pre instance is locked
  3130. */
  3131. static int ast_rtcp_write_report(struct ast_rtp_instance *instance, int sr)
  3132. {
  3133. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3134. RAII_VAR(struct ast_json *, message_blob, NULL, ast_json_unref);
  3135. int res;
  3136. int len = 0;
  3137. struct timeval now;
  3138. unsigned int now_lsw;
  3139. unsigned int now_msw;
  3140. unsigned int *rtcpheader;
  3141. unsigned int lost_packets;
  3142. int fraction_lost;
  3143. struct timeval dlsr = { 0, };
  3144. char bdata[512];
  3145. int rate = rtp_get_rate(rtp->f.subclass.format);
  3146. int ice;
  3147. int header_offset = 0;
  3148. struct ast_sockaddr remote_address = { { 0, } };
  3149. struct ast_rtp_rtcp_report_block *report_block = NULL;
  3150. RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report,
  3151. ast_rtp_rtcp_report_alloc(rtp->themssrc_valid ? 1 : 0),
  3152. ao2_cleanup);
  3153. if (!rtp || !rtp->rtcp) {
  3154. return 0;
  3155. }
  3156. if (ast_sockaddr_isnull(&rtp->rtcp->them)) { /* This'll stop rtcp for this rtp session */
  3157. /* RTCP was stopped. */
  3158. return 0;
  3159. }
  3160. if (!rtcp_report) {
  3161. return 1;
  3162. }
  3163. /* Compute statistics */
  3164. calculate_lost_packet_statistics(rtp, &lost_packets, &fraction_lost);
  3165. gettimeofday(&now, NULL);
  3166. rtcp_report->reception_report_count = rtp->themssrc_valid ? 1 : 0;
  3167. rtcp_report->ssrc = rtp->ssrc;
  3168. rtcp_report->type = sr ? RTCP_PT_SR : RTCP_PT_RR;
  3169. if (sr) {
  3170. rtcp_report->sender_information.ntp_timestamp = now;
  3171. rtcp_report->sender_information.rtp_timestamp = rtp->lastts;
  3172. rtcp_report->sender_information.packet_count = rtp->txcount;
  3173. rtcp_report->sender_information.octet_count = rtp->txoctetcount;
  3174. }
  3175. if (rtp->themssrc_valid) {
  3176. report_block = ast_calloc(1, sizeof(*report_block));
  3177. if (!report_block) {
  3178. return 1;
  3179. }
  3180. rtcp_report->report_block[0] = report_block;
  3181. report_block->source_ssrc = rtp->themssrc;
  3182. report_block->lost_count.fraction = (fraction_lost & 0xff);
  3183. report_block->lost_count.packets = (lost_packets & 0xffffff);
  3184. report_block->highest_seq_no = (rtp->cycles | (rtp->lastrxseqno & 0xffff));
  3185. report_block->ia_jitter = (unsigned int)(rtp->rxjitter * rate);
  3186. report_block->lsr = rtp->rtcp->themrxlsr;
  3187. /* If we haven't received an SR report, DLSR should be 0 */
  3188. if (!ast_tvzero(rtp->rtcp->rxlsr)) {
  3189. timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
  3190. report_block->dlsr = (((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000;
  3191. }
  3192. }
  3193. timeval2ntp(rtcp_report->sender_information.ntp_timestamp, &now_msw, &now_lsw);
  3194. rtcpheader = (unsigned int *)bdata;
  3195. rtcpheader[1] = htonl(rtcp_report->ssrc); /* Our SSRC */
  3196. len += 8;
  3197. if (sr) {
  3198. header_offset = 5;
  3199. rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
  3200. rtcpheader[3] = htonl(now_lsw); /* now, LSW */
  3201. rtcpheader[4] = htonl(rtcp_report->sender_information.rtp_timestamp);
  3202. rtcpheader[5] = htonl(rtcp_report->sender_information.packet_count);
  3203. rtcpheader[6] = htonl(rtcp_report->sender_information.octet_count);
  3204. len += 20;
  3205. }
  3206. if (report_block) {
  3207. rtcpheader[2 + header_offset] = htonl(report_block->source_ssrc); /* Their SSRC */
  3208. rtcpheader[3 + header_offset] = htonl((report_block->lost_count.fraction << 24) | report_block->lost_count.packets);
  3209. rtcpheader[4 + header_offset] = htonl(report_block->highest_seq_no);
  3210. rtcpheader[5 + header_offset] = htonl(report_block->ia_jitter);
  3211. rtcpheader[6 + header_offset] = htonl(report_block->lsr);
  3212. rtcpheader[7 + header_offset] = htonl(report_block->dlsr);
  3213. len += 24;
  3214. }
  3215. rtcpheader[0] = htonl((2 << 30) | (rtcp_report->reception_report_count << 24)
  3216. | ((sr ? RTCP_PT_SR : RTCP_PT_RR) << 16) | ((len/4)-1));
  3217. /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
  3218. /* it can change mid call, and SDES can't) */
  3219. rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
  3220. rtcpheader[(len/4)+1] = htonl(rtcp_report->ssrc);
  3221. rtcpheader[(len/4)+2] = htonl(0x01 << 24);
  3222. len += 12;
  3223. ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
  3224. res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &remote_address, &ice);
  3225. if (res < 0) {
  3226. ast_log(LOG_ERROR, "RTCP %s transmission error to %s, rtcp halted %s\n",
  3227. sr ? "SR" : "RR",
  3228. ast_sockaddr_stringify(&rtp->rtcp->them),
  3229. strerror(errno));
  3230. return 0;
  3231. }
  3232. /* Update RTCP SR/RR statistics */
  3233. if (sr) {
  3234. rtp->rtcp->txlsr = rtcp_report->sender_information.ntp_timestamp;
  3235. rtp->rtcp->sr_count++;
  3236. rtp->rtcp->lastsrtxcount = rtp->txcount;
  3237. } else {
  3238. rtp->rtcp->rr_count++;
  3239. }
  3240. if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
  3241. ast_verbose("* Sent RTCP %s to %s%s\n", sr ? "SR" : "RR",
  3242. ast_sockaddr_stringify(&remote_address), ice ? " (via ICE)" : "");
  3243. ast_verbose(" Our SSRC: %u\n", rtcp_report->ssrc);
  3244. if (sr) {
  3245. ast_verbose(" Sent(NTP): %u.%06u\n",
  3246. (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
  3247. (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec);
  3248. ast_verbose(" Sent(RTP): %u\n", rtcp_report->sender_information.rtp_timestamp);
  3249. ast_verbose(" Sent packets: %u\n", rtcp_report->sender_information.packet_count);
  3250. ast_verbose(" Sent octets: %u\n", rtcp_report->sender_information.octet_count);
  3251. }
  3252. if (report_block) {
  3253. ast_verbose(" Report block:\n");
  3254. ast_verbose(" Their SSRC: %u\n", report_block->source_ssrc);
  3255. ast_verbose(" Fraction lost: %d\n", report_block->lost_count.fraction);
  3256. ast_verbose(" Cumulative loss: %u\n", report_block->lost_count.packets);
  3257. ast_verbose(" Highest seq no: %u\n", report_block->highest_seq_no);
  3258. ast_verbose(" IA jitter: %.4f\n", (double)report_block->ia_jitter / rate);
  3259. ast_verbose(" Their last SR: %u\n", report_block->lsr);
  3260. ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(report_block->dlsr / 65536.0));
  3261. }
  3262. }
  3263. message_blob = ast_json_pack("{s: s, s: s}",
  3264. "to", ast_sockaddr_stringify(&remote_address),
  3265. "from", rtp->rtcp->local_addr_str);
  3266. ast_rtp_publish_rtcp_message(instance, ast_rtp_rtcp_sent_type(),
  3267. rtcp_report,
  3268. message_blob);
  3269. return res;
  3270. }
  3271. /*!
  3272. * \brief Write a RTCP packet to the far end
  3273. *
  3274. * \note Decide if we are going to send an SR (with Reception Block) or RR
  3275. * RR is sent if we have not sent any rtp packets in the previous interval
  3276. *
  3277. * Scheduler callback
  3278. */
  3279. static int ast_rtcp_write(const void *data)
  3280. {
  3281. struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
  3282. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3283. int res;
  3284. if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
  3285. ao2_ref(instance, -1);
  3286. return 0;
  3287. }
  3288. ao2_lock(instance);
  3289. if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
  3290. /* Send an SR */
  3291. res = ast_rtcp_write_report(instance, 1);
  3292. } else {
  3293. /* Send an RR */
  3294. res = ast_rtcp_write_report(instance, 0);
  3295. }
  3296. ao2_unlock(instance);
  3297. if (!res) {
  3298. /*
  3299. * Not being rescheduled.
  3300. */
  3301. rtp->rtcp->schedid = -1;
  3302. ao2_ref(instance, -1);
  3303. }
  3304. return res;
  3305. }
  3306. /*! \pre instance is locked */
  3307. static int rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
  3308. {
  3309. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3310. int pred, mark = 0;
  3311. unsigned int ms = calc_txstamp(rtp, &frame->delivery);
  3312. struct ast_sockaddr remote_address = { {0,} };
  3313. int rate = rtp_get_rate(frame->subclass.format) / 1000;
  3314. if (ast_format_cmp(frame->subclass.format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) {
  3315. frame->samples /= 2;
  3316. }
  3317. if (rtp->sending_digit) {
  3318. return 0;
  3319. }
  3320. if (frame->frametype == AST_FRAME_VOICE) {
  3321. pred = rtp->lastts + frame->samples;
  3322. /* Re-calculate last TS */
  3323. rtp->lastts = rtp->lastts + ms * rate;
  3324. if (ast_tvzero(frame->delivery)) {
  3325. /* If this isn't an absolute delivery time, Check if it is close to our prediction,
  3326. and if so, go with our prediction */
  3327. if (abs((int)rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
  3328. rtp->lastts = pred;
  3329. } else {
  3330. ast_debug(3, "Difference is %d, ms is %u\n", abs((int)rtp->lastts - pred), ms);
  3331. mark = 1;
  3332. }
  3333. }
  3334. } else if (frame->frametype == AST_FRAME_VIDEO) {
  3335. mark = frame->subclass.frame_ending;
  3336. pred = rtp->lastovidtimestamp + frame->samples;
  3337. /* Re-calculate last TS */
  3338. rtp->lastts = rtp->lastts + ms * 90;
  3339. /* If it's close to our prediction, go for it */
  3340. if (ast_tvzero(frame->delivery)) {
  3341. if (abs((int)rtp->lastts - pred) < 7200) {
  3342. rtp->lastts = pred;
  3343. rtp->lastovidtimestamp += frame->samples;
  3344. } else {
  3345. ast_debug(3, "Difference is %d, ms is %u (%u), pred/ts/samples %u/%d/%d\n", abs((int)rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
  3346. rtp->lastovidtimestamp = rtp->lastts;
  3347. }
  3348. }
  3349. } else {
  3350. pred = rtp->lastotexttimestamp + frame->samples;
  3351. /* Re-calculate last TS */
  3352. rtp->lastts = rtp->lastts + ms;
  3353. /* If it's close to our prediction, go for it */
  3354. if (ast_tvzero(frame->delivery)) {
  3355. if (abs((int)rtp->lastts - pred) < 7200) {
  3356. rtp->lastts = pred;
  3357. rtp->lastotexttimestamp += frame->samples;
  3358. } else {
  3359. ast_debug(3, "Difference is %d, ms is %u, pred/ts/samples %u/%d/%d\n", abs((int)rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
  3360. rtp->lastotexttimestamp = rtp->lastts;
  3361. }
  3362. }
  3363. }
  3364. /* If we have been explicitly told to set the marker bit then do so */
  3365. if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
  3366. mark = 1;
  3367. ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
  3368. }
  3369. /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
  3370. if (rtp->lastts > rtp->lastdigitts) {
  3371. rtp->lastdigitts = rtp->lastts;
  3372. }
  3373. if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
  3374. rtp->lastts = frame->ts * rate;
  3375. }
  3376. ast_rtp_instance_get_remote_address(instance, &remote_address);
  3377. /* If we know the remote address construct a packet and send it out */
  3378. if (!ast_sockaddr_isnull(&remote_address)) {
  3379. int hdrlen = 12, res, ice;
  3380. unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
  3381. put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
  3382. put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
  3383. put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
  3384. if ((res = rtp_sendto(instance, (void *)rtpheader, frame->datalen + hdrlen, 0, &remote_address, &ice)) < 0) {
  3385. if (!ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
  3386. ast_debug(1, "RTP Transmission error of packet %d to %s: %s\n",
  3387. rtp->seqno,
  3388. ast_sockaddr_stringify(&remote_address),
  3389. strerror(errno));
  3390. } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
  3391. /* Only give this error message once if we are not RTP debugging */
  3392. if (rtpdebug)
  3393. ast_debug(0, "RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
  3394. ast_sockaddr_stringify(&remote_address));
  3395. ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
  3396. }
  3397. } else {
  3398. if (rtp->rtcp && rtp->rtcp->schedid < 0) {
  3399. ast_debug(1, "Starting RTCP transmission on RTP instance '%p'\n", instance);
  3400. ao2_ref(instance, +1);
  3401. rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
  3402. if (rtp->rtcp->schedid < 0) {
  3403. ao2_ref(instance, -1);
  3404. ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
  3405. }
  3406. }
  3407. }
  3408. if (rtp_debug_test_addr(&remote_address)) {
  3409. ast_verbose("Sent RTP packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
  3410. ast_sockaddr_stringify(&remote_address),
  3411. ice ? " (via ICE)" : "",
  3412. codec, rtp->seqno, rtp->lastts, res - hdrlen);
  3413. }
  3414. }
  3415. rtp->seqno++;
  3416. return 0;
  3417. }
  3418. static struct ast_frame *red_t140_to_red(struct rtp_red *red)
  3419. {
  3420. unsigned char *data = red->t140red.data.ptr;
  3421. int len = 0;
  3422. int i;
  3423. /* replace most aged generation */
  3424. if (red->len[0]) {
  3425. for (i = 1; i < red->num_gen+1; i++)
  3426. len += red->len[i];
  3427. memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
  3428. }
  3429. /* Store length of each generation and primary data length*/
  3430. for (i = 0; i < red->num_gen; i++)
  3431. red->len[i] = red->len[i+1];
  3432. red->len[i] = red->t140.datalen;
  3433. /* write each generation length in red header */
  3434. len = red->hdrlen;
  3435. for (i = 0; i < red->num_gen; i++) {
  3436. len += data[i*4+3] = red->len[i];
  3437. }
  3438. /* add primary data to buffer */
  3439. memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
  3440. red->t140red.datalen = len + red->t140.datalen;
  3441. /* no primary data and no generations to send */
  3442. if (len == red->hdrlen && !red->t140.datalen) {
  3443. return NULL;
  3444. }
  3445. /* reset t.140 buffer */
  3446. red->t140.datalen = 0;
  3447. return &red->t140red;
  3448. }
  3449. /*! \pre instance is locked */
  3450. static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
  3451. {
  3452. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3453. struct ast_sockaddr remote_address = { {0,} };
  3454. struct ast_format *format;
  3455. int codec;
  3456. ast_rtp_instance_get_remote_address(instance, &remote_address);
  3457. /* If we don't actually know the remote address don't even bother doing anything */
  3458. if (ast_sockaddr_isnull(&remote_address)) {
  3459. ast_debug(1, "No remote address on RTP instance '%p' so dropping frame\n", instance);
  3460. return 0;
  3461. }
  3462. /* VP8: is this a request to send a RTCP FIR? */
  3463. if (frame->frametype == AST_FRAME_CONTROL && frame->subclass.integer == AST_CONTROL_VIDUPDATE) {
  3464. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3465. unsigned int *rtcpheader;
  3466. char bdata[1024];
  3467. int len = 20;
  3468. int ice;
  3469. int res;
  3470. if (!rtp || !rtp->rtcp) {
  3471. return 0;
  3472. }
  3473. if (ast_sockaddr_isnull(&rtp->rtcp->them) || rtp->rtcp->schedid < 0) {
  3474. /*
  3475. * RTCP was stopped.
  3476. */
  3477. return 0;
  3478. }
  3479. if (!rtp->themssrc_valid) {
  3480. /* We don't know their SSRC value so we don't know who to update. */
  3481. return 0;
  3482. }
  3483. /* Prepare RTCP FIR (PT=206, FMT=4) */
  3484. rtp->rtcp->firseq++;
  3485. if(rtp->rtcp->firseq == 256) {
  3486. rtp->rtcp->firseq = 0;
  3487. }
  3488. rtcpheader = (unsigned int *)bdata;
  3489. rtcpheader[0] = htonl((2 << 30) | (4 << 24) | (RTCP_PT_PSFB << 16) | ((len/4)-1));
  3490. rtcpheader[1] = htonl(rtp->ssrc);
  3491. rtcpheader[2] = htonl(rtp->themssrc);
  3492. rtcpheader[3] = htonl(rtp->themssrc); /* FCI: SSRC */
  3493. rtcpheader[4] = htonl(rtp->rtcp->firseq << 24); /* FCI: Sequence number */
  3494. res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &rtp->rtcp->them, &ice);
  3495. if (res < 0) {
  3496. ast_log(LOG_ERROR, "RTCP FIR transmission error: %s\n", strerror(errno));
  3497. }
  3498. return 0;
  3499. }
  3500. /* If there is no data length we can't very well send the packet */
  3501. if (!frame->datalen) {
  3502. ast_debug(1, "Received frame with no data for RTP instance '%p' so dropping frame\n", instance);
  3503. return 0;
  3504. }
  3505. /* If the packet is not one our RTP stack supports bail out */
  3506. if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
  3507. ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
  3508. return -1;
  3509. }
  3510. if (rtp->red) {
  3511. /* return 0; */
  3512. /* no primary data or generations to send */
  3513. if ((frame = red_t140_to_red(rtp->red)) == NULL)
  3514. return 0;
  3515. }
  3516. /* Grab the subclass and look up the payload we are going to use */
  3517. codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance),
  3518. 1,
  3519. frame->subclass.format,
  3520. 0);
  3521. if (codec < 0) {
  3522. ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n",
  3523. ast_format_get_name(frame->subclass.format));
  3524. return -1;
  3525. }
  3526. /* Note that we do not increase the ref count here as this pointer
  3527. * will not be held by any thing explicitly. The format variable is
  3528. * merely a convenience reference to frame->subclass.format */
  3529. format = frame->subclass.format;
  3530. if (ast_format_cmp(rtp->lasttxformat, format) == AST_FORMAT_CMP_NOT_EQUAL) {
  3531. /* Oh dear, if the format changed we will have to set up a new smoother */
  3532. ast_debug(1, "Ooh, format changed from %s to %s\n",
  3533. ast_format_get_name(rtp->lasttxformat),
  3534. ast_format_get_name(frame->subclass.format));
  3535. ao2_replace(rtp->lasttxformat, format);
  3536. if (rtp->smoother) {
  3537. ast_smoother_free(rtp->smoother);
  3538. rtp->smoother = NULL;
  3539. }
  3540. }
  3541. /* If no smoother is present see if we have to set one up */
  3542. if (!rtp->smoother && ast_format_can_be_smoothed(format)) {
  3543. unsigned int smoother_flags = ast_format_get_smoother_flags(format);
  3544. unsigned int framing_ms = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(instance));
  3545. if (!framing_ms && (smoother_flags & AST_SMOOTHER_FLAG_FORCED)) {
  3546. framing_ms = ast_format_get_default_ms(format);
  3547. }
  3548. if (framing_ms) {
  3549. rtp->smoother = ast_smoother_new((framing_ms * ast_format_get_minimum_bytes(format)) / ast_format_get_minimum_ms(format));
  3550. if (!rtp->smoother) {
  3551. ast_log(LOG_WARNING, "Unable to create smoother: format %s ms: %u len: %u\n",
  3552. ast_format_get_name(format), framing_ms, ast_format_get_minimum_bytes(format));
  3553. return -1;
  3554. }
  3555. ast_smoother_set_flags(rtp->smoother, smoother_flags);
  3556. }
  3557. }
  3558. /* Feed audio frames into the actual function that will create a frame and send it */
  3559. if (rtp->smoother) {
  3560. struct ast_frame *f;
  3561. if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
  3562. ast_smoother_feed_be(rtp->smoother, frame);
  3563. } else {
  3564. ast_smoother_feed(rtp->smoother, frame);
  3565. }
  3566. while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
  3567. rtp_raw_write(instance, f, codec);
  3568. }
  3569. } else {
  3570. int hdrlen = 12;
  3571. struct ast_frame *f = NULL;
  3572. if (frame->offset < hdrlen) {
  3573. f = ast_frdup(frame);
  3574. } else {
  3575. f = frame;
  3576. }
  3577. if (f->data.ptr) {
  3578. rtp_raw_write(instance, f, codec);
  3579. }
  3580. if (f != frame) {
  3581. ast_frfree(f);
  3582. }
  3583. }
  3584. return 0;
  3585. }
  3586. static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
  3587. {
  3588. struct timeval now;
  3589. struct timeval tmp;
  3590. double transit;
  3591. double current_time;
  3592. double d;
  3593. double dtv;
  3594. double prog;
  3595. int rate = rtp_get_rate(rtp->f.subclass.format);
  3596. double normdev_rxjitter_current;
  3597. if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
  3598. gettimeofday(&rtp->rxcore, NULL);
  3599. rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
  3600. /* map timestamp to a real time */
  3601. rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
  3602. tmp = ast_samp2tv(timestamp, rate);
  3603. rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
  3604. /* Round to 0.1ms for nice, pretty timestamps */
  3605. rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
  3606. }
  3607. gettimeofday(&now,NULL);
  3608. /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
  3609. tmp = ast_samp2tv(timestamp, rate);
  3610. *tv = ast_tvadd(rtp->rxcore, tmp);
  3611. prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
  3612. dtv = (double)rtp->drxcore + (double)(prog);
  3613. current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
  3614. transit = current_time - dtv;
  3615. d = transit - rtp->rxtransit;
  3616. rtp->rxtransit = transit;
  3617. if (d<0) {
  3618. d=-d;
  3619. }
  3620. rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
  3621. if (rtp->rtcp) {
  3622. if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
  3623. rtp->rtcp->maxrxjitter = rtp->rxjitter;
  3624. if (rtp->rtcp->rxjitter_count == 1)
  3625. rtp->rtcp->minrxjitter = rtp->rxjitter;
  3626. if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
  3627. rtp->rtcp->minrxjitter = rtp->rxjitter;
  3628. normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
  3629. rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
  3630. rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
  3631. rtp->rtcp->rxjitter_count++;
  3632. }
  3633. }
  3634. static struct ast_frame *create_dtmf_frame(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
  3635. {
  3636. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3637. struct ast_sockaddr remote_address = { {0,} };
  3638. ast_rtp_instance_get_remote_address(instance, &remote_address);
  3639. if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
  3640. ast_debug(1, "Ignore potential DTMF echo from '%s'\n",
  3641. ast_sockaddr_stringify(&remote_address));
  3642. rtp->resp = 0;
  3643. rtp->dtmfsamples = 0;
  3644. return &ast_null_frame;
  3645. }
  3646. ast_debug(1, "Creating %s DTMF Frame: %d (%c), at %s\n",
  3647. type == AST_FRAME_DTMF_END ? "END" : "BEGIN",
  3648. rtp->resp, rtp->resp,
  3649. ast_sockaddr_stringify(&remote_address));
  3650. if (rtp->resp == 'X') {
  3651. rtp->f.frametype = AST_FRAME_CONTROL;
  3652. rtp->f.subclass.integer = AST_CONTROL_FLASH;
  3653. } else {
  3654. rtp->f.frametype = type;
  3655. rtp->f.subclass.integer = rtp->resp;
  3656. }
  3657. rtp->f.datalen = 0;
  3658. rtp->f.samples = 0;
  3659. rtp->f.mallocd = 0;
  3660. rtp->f.src = "RTP";
  3661. AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
  3662. return &rtp->f;
  3663. }
  3664. static void process_dtmf_rfc2833(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark, struct frame_list *frames)
  3665. {
  3666. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3667. struct ast_sockaddr remote_address = { {0,} };
  3668. unsigned int event, event_end, samples;
  3669. char resp = 0;
  3670. struct ast_frame *f = NULL;
  3671. ast_rtp_instance_get_remote_address(instance, &remote_address);
  3672. /* Figure out event, event end, and samples */
  3673. event = ntohl(*((unsigned int *)(data)));
  3674. event >>= 24;
  3675. event_end = ntohl(*((unsigned int *)(data)));
  3676. event_end <<= 8;
  3677. event_end >>= 24;
  3678. samples = ntohl(*((unsigned int *)(data)));
  3679. samples &= 0xFFFF;
  3680. if (rtp_debug_test_addr(&remote_address)) {
  3681. ast_verbose("Got RTP RFC2833 from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6d, mark %d, event %08x, end %d, duration %-5.5u) \n",
  3682. ast_sockaddr_stringify(&remote_address),
  3683. payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
  3684. }
  3685. /* Print out debug if turned on */
  3686. if (rtpdebug)
  3687. ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
  3688. /* Figure out what digit was pressed */
  3689. if (event < 10) {
  3690. resp = '0' + event;
  3691. } else if (event < 11) {
  3692. resp = '*';
  3693. } else if (event < 12) {
  3694. resp = '#';
  3695. } else if (event < 16) {
  3696. resp = 'A' + (event - 12);
  3697. } else if (event < 17) { /* Event 16: Hook flash */
  3698. resp = 'X';
  3699. } else {
  3700. /* Not a supported event */
  3701. ast_debug(1, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
  3702. return;
  3703. }
  3704. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
  3705. if ((rtp->last_end_timestamp != timestamp) || (rtp->resp && rtp->resp != resp)) {
  3706. rtp->resp = resp;
  3707. rtp->dtmf_timeout = 0;
  3708. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)));
  3709. f->len = 0;
  3710. rtp->last_end_timestamp = timestamp;
  3711. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  3712. }
  3713. } else {
  3714. /* The duration parameter measures the complete
  3715. duration of the event (from the beginning) - RFC2833.
  3716. Account for the fact that duration is only 16 bits long
  3717. (about 8 seconds at 8000 Hz) and can wrap is digit
  3718. is hold for too long. */
  3719. unsigned int new_duration = rtp->dtmf_duration;
  3720. unsigned int last_duration = new_duration & 0xFFFF;
  3721. if (last_duration > 64000 && samples < last_duration) {
  3722. new_duration += 0xFFFF + 1;
  3723. }
  3724. new_duration = (new_duration & ~0xFFFF) | samples;
  3725. if (event_end & 0x80) {
  3726. /* End event */
  3727. if ((rtp->last_seqno != seqno) && (timestamp > rtp->last_end_timestamp)) {
  3728. rtp->last_end_timestamp = timestamp;
  3729. rtp->dtmf_duration = new_duration;
  3730. rtp->resp = resp;
  3731. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
  3732. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.format)), ast_tv(0, 0));
  3733. rtp->resp = 0;
  3734. rtp->dtmf_duration = rtp->dtmf_timeout = 0;
  3735. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  3736. } else if (rtpdebug) {
  3737. ast_debug(1, "Dropping duplicate or out of order DTMF END frame (seqno: %u, ts %u, digit %c)\n",
  3738. seqno, timestamp, resp);
  3739. }
  3740. } else {
  3741. /* Begin/continuation */
  3742. /* The second portion of the seqno check is to not mistakenly
  3743. * stop accepting DTMF if the seqno rolls over beyond
  3744. * 65535.
  3745. */
  3746. if ((rtp->last_seqno > seqno && rtp->last_seqno - seqno < 50)
  3747. || timestamp <= rtp->last_end_timestamp) {
  3748. /* Out of order frame. Processing this can cause us to
  3749. * improperly duplicate incoming DTMF, so just drop
  3750. * this.
  3751. */
  3752. if (rtpdebug) {
  3753. ast_debug(1, "Dropping out of order DTMF frame (seqno %u, ts %u, digit %c)\n",
  3754. seqno, timestamp, resp);
  3755. }
  3756. return;
  3757. }
  3758. if (rtp->resp && rtp->resp != resp) {
  3759. /* Another digit already began. End it */
  3760. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
  3761. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.format)), ast_tv(0, 0));
  3762. rtp->resp = 0;
  3763. rtp->dtmf_duration = rtp->dtmf_timeout = 0;
  3764. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  3765. }
  3766. if (rtp->resp) {
  3767. /* Digit continues */
  3768. rtp->dtmf_duration = new_duration;
  3769. } else {
  3770. /* New digit began */
  3771. rtp->resp = resp;
  3772. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0));
  3773. rtp->dtmf_duration = samples;
  3774. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  3775. }
  3776. rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
  3777. }
  3778. rtp->last_seqno = seqno;
  3779. }
  3780. rtp->dtmfsamples = samples;
  3781. return;
  3782. }
  3783. static struct ast_frame *process_dtmf_cisco(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark)
  3784. {
  3785. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3786. unsigned int event, flags, power;
  3787. char resp = 0;
  3788. unsigned char seq;
  3789. struct ast_frame *f = NULL;
  3790. if (len < 4) {
  3791. return NULL;
  3792. }
  3793. /* The format of Cisco RTP DTMF packet looks like next:
  3794. +0 - sequence number of DTMF RTP packet (begins from 1,
  3795. wrapped to 0)
  3796. +1 - set of flags
  3797. +1 (bit 0) - flaps by different DTMF digits delimited by audio
  3798. or repeated digit without audio???
  3799. +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
  3800. then falls to 0 at its end)
  3801. +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
  3802. Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
  3803. by each new packet and thus provides some redudancy.
  3804. Sample of Cisco RTP DTMF packet is (all data in hex):
  3805. 19 07 00 02 12 02 20 02
  3806. showing end of DTMF digit '2'.
  3807. The packets
  3808. 27 07 00 02 0A 02 20 02
  3809. 28 06 20 02 00 02 0A 02
  3810. shows begin of new digit '2' with very short pause (20 ms) after
  3811. previous digit '2'. Bit +1.0 flips at begin of new digit.
  3812. Cisco RTP DTMF packets comes as replacement of audio RTP packets
  3813. so its uses the same sequencing and timestamping rules as replaced
  3814. audio packets. Repeat interval of DTMF packets is 20 ms and not rely
  3815. on audio framing parameters. Marker bit isn't used within stream of
  3816. DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
  3817. are not sequential at borders between DTMF and audio streams,
  3818. */
  3819. seq = data[0];
  3820. flags = data[1];
  3821. power = data[2];
  3822. event = data[3] & 0x1f;
  3823. if (rtpdebug)
  3824. ast_debug(0, "Cisco DTMF Digit: %02x (len=%d, seq=%d, flags=%02x, power=%u, history count=%d)\n", event, len, seq, flags, power, (len - 4) / 2);
  3825. if (event < 10) {
  3826. resp = '0' + event;
  3827. } else if (event < 11) {
  3828. resp = '*';
  3829. } else if (event < 12) {
  3830. resp = '#';
  3831. } else if (event < 16) {
  3832. resp = 'A' + (event - 12);
  3833. } else if (event < 17) {
  3834. resp = 'X';
  3835. }
  3836. if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
  3837. rtp->resp = resp;
  3838. /* Why we should care on DTMF compensation at reception? */
  3839. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
  3840. f = create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0);
  3841. rtp->dtmfsamples = 0;
  3842. }
  3843. } else if ((rtp->resp == resp) && !power) {
  3844. f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE));
  3845. f->samples = rtp->dtmfsamples * (rtp_get_rate(rtp->lastrxformat) / 1000);
  3846. rtp->resp = 0;
  3847. } else if (rtp->resp == resp) {
  3848. rtp->dtmfsamples += 20 * (rtp_get_rate(rtp->lastrxformat) / 1000);
  3849. }
  3850. rtp->dtmf_timeout = 0;
  3851. return f;
  3852. }
  3853. static struct ast_frame *process_cn_rfc3389(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark)
  3854. {
  3855. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3856. /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
  3857. totally help us out becuase we don't have an engine to keep it going and we are not
  3858. guaranteed to have it every 20ms or anything */
  3859. if (rtpdebug) {
  3860. ast_debug(0, "- RTP 3389 Comfort noise event: Format %s (len = %d)\n",
  3861. ast_format_get_name(rtp->lastrxformat), len);
  3862. }
  3863. if (ast_test_flag(rtp, FLAG_3389_WARNING)) {
  3864. struct ast_sockaddr remote_address = { {0,} };
  3865. ast_rtp_instance_get_remote_address(instance, &remote_address);
  3866. ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client address: %s\n",
  3867. ast_sockaddr_stringify(&remote_address));
  3868. ast_set_flag(rtp, FLAG_3389_WARNING);
  3869. }
  3870. /* Must have at least one byte */
  3871. if (!len) {
  3872. return NULL;
  3873. }
  3874. if (len < 24) {
  3875. rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
  3876. rtp->f.datalen = len - 1;
  3877. rtp->f.offset = AST_FRIENDLY_OFFSET;
  3878. memcpy(rtp->f.data.ptr, data + 1, len - 1);
  3879. } else {
  3880. rtp->f.data.ptr = NULL;
  3881. rtp->f.offset = 0;
  3882. rtp->f.datalen = 0;
  3883. }
  3884. rtp->f.frametype = AST_FRAME_CNG;
  3885. rtp->f.subclass.integer = data[0] & 0x7f;
  3886. rtp->f.samples = 0;
  3887. rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
  3888. return &rtp->f;
  3889. }
  3890. static int update_rtt_stats(struct ast_rtp *rtp, unsigned int lsr, unsigned int dlsr)
  3891. {
  3892. struct timeval now;
  3893. struct timeval rtt_tv;
  3894. unsigned int msw;
  3895. unsigned int lsw;
  3896. unsigned int rtt_msw;
  3897. unsigned int rtt_lsw;
  3898. unsigned int lsr_a;
  3899. unsigned int rtt;
  3900. double normdevrtt_current;
  3901. gettimeofday(&now, NULL);
  3902. timeval2ntp(now, &msw, &lsw);
  3903. lsr_a = ((msw & 0x0000ffff) << 16) | ((lsw & 0xffff0000) >> 16);
  3904. rtt = lsr_a - lsr - dlsr;
  3905. rtt_msw = (rtt & 0xffff0000) >> 16;
  3906. rtt_lsw = (rtt & 0x0000ffff);
  3907. rtt_tv.tv_sec = rtt_msw;
  3908. /*
  3909. * Convert 16.16 fixed point rtt_lsw to usec without
  3910. * overflow.
  3911. *
  3912. * = rtt_lsw * 10^6 / 2^16
  3913. * = rtt_lsw * (2^6 * 5^6) / 2^16
  3914. * = rtt_lsw * 5^6 / 2^10
  3915. *
  3916. * The rtt_lsw value is in 16.16 fixed point format and 5^6
  3917. * requires 14 bits to represent. We have enough space to
  3918. * directly do the conversion because there is no integer
  3919. * component in rtt_lsw.
  3920. */
  3921. rtt_tv.tv_usec = (rtt_lsw * 15625) >> 10;
  3922. rtp->rtcp->rtt = (double)rtt_tv.tv_sec + ((double)rtt_tv.tv_usec / 1000000);
  3923. if (lsr_a - dlsr < lsr) {
  3924. return 1;
  3925. }
  3926. rtp->rtcp->accumulated_transit += rtp->rtcp->rtt;
  3927. if (rtp->rtcp->rtt_count == 0 || rtp->rtcp->minrtt > rtp->rtcp->rtt) {
  3928. rtp->rtcp->minrtt = rtp->rtcp->rtt;
  3929. }
  3930. if (rtp->rtcp->maxrtt < rtp->rtcp->rtt) {
  3931. rtp->rtcp->maxrtt = rtp->rtcp->rtt;
  3932. }
  3933. normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt,
  3934. rtp->rtcp->rtt,
  3935. rtp->rtcp->rtt_count);
  3936. rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt,
  3937. rtp->rtcp->rtt,
  3938. rtp->rtcp->normdevrtt,
  3939. normdevrtt_current,
  3940. rtp->rtcp->rtt_count);
  3941. rtp->rtcp->normdevrtt = normdevrtt_current;
  3942. rtp->rtcp->rtt_count++;
  3943. return 0;
  3944. }
  3945. /*!
  3946. * \internal
  3947. * \brief Update RTCP interarrival jitter stats
  3948. */
  3949. static void update_jitter_stats(struct ast_rtp *rtp, unsigned int ia_jitter)
  3950. {
  3951. double reported_jitter;
  3952. double reported_normdev_jitter_current;
  3953. rtp->rtcp->reported_jitter = ia_jitter;
  3954. reported_jitter = (double) rtp->rtcp->reported_jitter;
  3955. if (rtp->rtcp->reported_jitter_count == 0) {
  3956. rtp->rtcp->reported_minjitter = reported_jitter;
  3957. }
  3958. if (reported_jitter < rtp->rtcp->reported_minjitter) {
  3959. rtp->rtcp->reported_minjitter = reported_jitter;
  3960. }
  3961. if (reported_jitter > rtp->rtcp->reported_maxjitter) {
  3962. rtp->rtcp->reported_maxjitter = reported_jitter;
  3963. }
  3964. reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);
  3965. rtp->rtcp->reported_stdev_jitter = stddev_compute(rtp->rtcp->reported_stdev_jitter, reported_jitter, rtp->rtcp->reported_normdev_jitter, reported_normdev_jitter_current, rtp->rtcp->reported_jitter_count);
  3966. rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;
  3967. }
  3968. /*!
  3969. * \internal
  3970. * \brief Update RTCP lost packet stats
  3971. */
  3972. static void update_lost_stats(struct ast_rtp *rtp, unsigned int lost_packets)
  3973. {
  3974. double reported_lost;
  3975. double reported_normdev_lost_current;
  3976. rtp->rtcp->reported_lost = lost_packets;
  3977. reported_lost = (double)rtp->rtcp->reported_lost;
  3978. if (rtp->rtcp->reported_jitter_count == 0) {
  3979. rtp->rtcp->reported_minlost = reported_lost;
  3980. }
  3981. if (reported_lost < rtp->rtcp->reported_minlost) {
  3982. rtp->rtcp->reported_minlost = reported_lost;
  3983. }
  3984. if (reported_lost > rtp->rtcp->reported_maxlost) {
  3985. rtp->rtcp->reported_maxlost = reported_lost;
  3986. }
  3987. reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);
  3988. rtp->rtcp->reported_stdev_lost = stddev_compute(rtp->rtcp->reported_stdev_lost, reported_lost, rtp->rtcp->reported_normdev_lost, reported_normdev_lost_current, rtp->rtcp->reported_jitter_count);
  3989. rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;
  3990. }
  3991. static const char *rtcp_payload_type2str(unsigned int pt)
  3992. {
  3993. const char *str;
  3994. switch (pt) {
  3995. case RTCP_PT_SR:
  3996. str = "Sender Report";
  3997. break;
  3998. case RTCP_PT_RR:
  3999. str = "Receiver Report";
  4000. break;
  4001. case RTCP_PT_FUR:
  4002. /* Full INTRA-frame Request / Fast Update Request */
  4003. str = "H.261 FUR";
  4004. break;
  4005. case RTCP_PT_PSFB:
  4006. /* Payload Specific Feed Back */
  4007. str = "PSFB";
  4008. break;
  4009. case RTCP_PT_SDES:
  4010. str = "Source Description";
  4011. break;
  4012. case RTCP_PT_BYE:
  4013. str = "BYE";
  4014. break;
  4015. default:
  4016. str = "Unknown";
  4017. break;
  4018. }
  4019. return str;
  4020. }
  4021. /*
  4022. * Unshifted RTCP header bit field masks
  4023. */
  4024. #define RTCP_LENGTH_MASK 0xFFFF
  4025. #define RTCP_PAYLOAD_TYPE_MASK 0xFF
  4026. #define RTCP_REPORT_COUNT_MASK 0x1F
  4027. #define RTCP_PADDING_MASK 0x01
  4028. #define RTCP_VERSION_MASK 0x03
  4029. /*
  4030. * RTCP header bit field shift offsets
  4031. */
  4032. #define RTCP_LENGTH_SHIFT 0
  4033. #define RTCP_PAYLOAD_TYPE_SHIFT 16
  4034. #define RTCP_REPORT_COUNT_SHIFT 24
  4035. #define RTCP_PADDING_SHIFT 29
  4036. #define RTCP_VERSION_SHIFT 30
  4037. #define RTCP_VERSION 2U
  4038. #define RTCP_VERSION_SHIFTED (RTCP_VERSION << RTCP_VERSION_SHIFT)
  4039. #define RTCP_VERSION_MASK_SHIFTED (RTCP_VERSION_MASK << RTCP_VERSION_SHIFT)
  4040. /*
  4041. * RTCP first packet record validity header mask and value.
  4042. *
  4043. * RFC3550 intentionally defines the encoding of RTCP_PT_SR and RTCP_PT_RR
  4044. * such that they differ in the least significant bit. Either of these two
  4045. * payload types MUST be the first RTCP packet record in a compound packet.
  4046. *
  4047. * RFC3550 checks the padding bit in the algorithm they use to check the
  4048. * RTCP packet for validity. However, we aren't masking the padding bit
  4049. * to check since we don't know if it is a compound RTCP packet or not.
  4050. */
  4051. #define RTCP_VALID_MASK (RTCP_VERSION_MASK_SHIFTED | (((RTCP_PAYLOAD_TYPE_MASK & ~0x1)) << RTCP_PAYLOAD_TYPE_SHIFT))
  4052. #define RTCP_VALID_VALUE (RTCP_VERSION_SHIFTED | (RTCP_PT_SR << RTCP_PAYLOAD_TYPE_SHIFT))
  4053. #define RTCP_SR_BLOCK_WORD_LENGTH 5
  4054. #define RTCP_RR_BLOCK_WORD_LENGTH 6
  4055. #define RTCP_HEADER_SSRC_LENGTH 2
  4056. static struct ast_frame *ast_rtcp_interpret(struct ast_rtp_instance *instance, const unsigned char *rtcpdata, size_t size, struct ast_sockaddr *addr)
  4057. {
  4058. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4059. unsigned int *rtcpheader = (unsigned int *)(rtcpdata);
  4060. unsigned int packetwords;
  4061. unsigned int position;
  4062. unsigned int first_word;
  4063. /*! True if we have seen an acceptable SSRC to learn the remote RTCP address */
  4064. unsigned int ssrc_seen;
  4065. struct ast_rtp_rtcp_report_block *report_block;
  4066. struct ast_frame *f = &ast_null_frame;
  4067. packetwords = size / 4;
  4068. ast_debug(1, "Got RTCP report of %zu bytes from %s\n",
  4069. size, ast_sockaddr_stringify(addr));
  4070. /*
  4071. * Validate the RTCP packet according to an adapted and slightly
  4072. * modified RFC3550 validation algorithm.
  4073. */
  4074. if (packetwords < RTCP_HEADER_SSRC_LENGTH) {
  4075. ast_debug(1, "%p -- RTCP from %s: Frame size (%u words) is too short\n",
  4076. rtp, ast_sockaddr_stringify(addr), packetwords);
  4077. return &ast_null_frame;
  4078. }
  4079. position = 0;
  4080. first_word = ntohl(rtcpheader[position]);
  4081. if ((first_word & RTCP_VALID_MASK) != RTCP_VALID_VALUE) {
  4082. ast_debug(1, "%p -- RTCP from %s: Failed first packet validity check\n",
  4083. rtp, ast_sockaddr_stringify(addr));
  4084. return &ast_null_frame;
  4085. }
  4086. do {
  4087. position += ((first_word >> RTCP_LENGTH_SHIFT) & RTCP_LENGTH_MASK) + 1;
  4088. if (packetwords <= position) {
  4089. break;
  4090. }
  4091. first_word = ntohl(rtcpheader[position]);
  4092. } while ((first_word & RTCP_VERSION_MASK_SHIFTED) == RTCP_VERSION_SHIFTED);
  4093. if (position != packetwords) {
  4094. ast_debug(1, "%p -- RTCP from %s: Failed packet version or length check\n",
  4095. rtp, ast_sockaddr_stringify(addr));
  4096. return &ast_null_frame;
  4097. }
  4098. /*
  4099. * Note: RFC3605 points out that true NAT (vs NAPT) can cause RTCP
  4100. * to have a different IP address and port than RTP. Otherwise, when
  4101. * strictrtp is enabled we could reject RTCP packets not coming from
  4102. * the learned RTP IP address if it is available.
  4103. */
  4104. /*
  4105. * strictrtp safety needs SSRC to match before we use the
  4106. * sender's address for symmetrical RTP to send our RTCP
  4107. * reports.
  4108. *
  4109. * If strictrtp is not enabled then claim to have already seen
  4110. * a matching SSRC so we'll accept this packet's address for
  4111. * symmetrical RTP.
  4112. */
  4113. ssrc_seen = rtp->strict_rtp_state == STRICT_RTP_OPEN;
  4114. position = 0;
  4115. while (position < packetwords) {
  4116. unsigned int i;
  4117. unsigned int pt;
  4118. unsigned int rc;
  4119. unsigned int ssrc;
  4120. /*! True if the ssrc value we have is valid and not garbage because it doesn't exist. */
  4121. unsigned int ssrc_valid;
  4122. unsigned int length;
  4123. unsigned int min_length;
  4124. struct ast_json *message_blob;
  4125. RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report, NULL, ao2_cleanup);
  4126. i = position;
  4127. first_word = ntohl(rtcpheader[i]);
  4128. pt = (first_word >> RTCP_PAYLOAD_TYPE_SHIFT) & RTCP_PAYLOAD_TYPE_MASK;
  4129. rc = (first_word >> RTCP_REPORT_COUNT_SHIFT) & RTCP_REPORT_COUNT_MASK;
  4130. /* RFC3550 says 'length' is the number of words in the packet - 1 */
  4131. length = ((first_word >> RTCP_LENGTH_SHIFT) & RTCP_LENGTH_MASK) + 1;
  4132. /* Check expected RTCP packet record length */
  4133. min_length = RTCP_HEADER_SSRC_LENGTH;
  4134. switch (pt) {
  4135. case RTCP_PT_SR:
  4136. min_length += RTCP_SR_BLOCK_WORD_LENGTH;
  4137. /* fall through */
  4138. case RTCP_PT_RR:
  4139. min_length += (rc * RTCP_RR_BLOCK_WORD_LENGTH);
  4140. break;
  4141. case RTCP_PT_FUR:
  4142. case RTCP_PT_PSFB:
  4143. break;
  4144. case RTCP_PT_SDES:
  4145. case RTCP_PT_BYE:
  4146. /*
  4147. * There may not be a SSRC/CSRC present. The packet is
  4148. * useless but still valid if it isn't present.
  4149. *
  4150. * We don't know what min_length should be so disable the check
  4151. */
  4152. min_length = length;
  4153. break;
  4154. default:
  4155. ast_debug(1, "%p -- RTCP from %s: %u(%s) skipping record\n",
  4156. rtp, ast_sockaddr_stringify(addr), pt, rtcp_payload_type2str(pt));
  4157. if (rtcp_debug_test_addr(addr)) {
  4158. ast_verbose("\n");
  4159. ast_verbose("RTCP from %s: %u(%s) skipping record\n",
  4160. ast_sockaddr_stringify(addr), pt, rtcp_payload_type2str(pt));
  4161. }
  4162. position += length;
  4163. continue;
  4164. }
  4165. if (length < min_length) {
  4166. ast_debug(1, "%p -- RTCP from %s: %u(%s) length field less than expected minimum. Min:%u Got:%u\n",
  4167. rtp, ast_sockaddr_stringify(addr), pt, rtcp_payload_type2str(pt),
  4168. min_length - 1, length - 1);
  4169. return &ast_null_frame;
  4170. }
  4171. /* Get the RTCP record SSRC if defined for the record */
  4172. ssrc_valid = 1;
  4173. switch (pt) {
  4174. case RTCP_PT_SR:
  4175. case RTCP_PT_RR:
  4176. rtcp_report = ast_rtp_rtcp_report_alloc(rc);
  4177. if (!rtcp_report) {
  4178. return &ast_null_frame;
  4179. }
  4180. rtcp_report->reception_report_count = rc;
  4181. ssrc = ntohl(rtcpheader[i + 1]);
  4182. rtcp_report->ssrc = ssrc;
  4183. break;
  4184. case RTCP_PT_FUR:
  4185. case RTCP_PT_PSFB:
  4186. ssrc = ntohl(rtcpheader[i + 1]);
  4187. break;
  4188. case RTCP_PT_SDES:
  4189. case RTCP_PT_BYE:
  4190. default:
  4191. ssrc = 0;
  4192. ssrc_valid = 0;
  4193. break;
  4194. }
  4195. if (rtcp_debug_test_addr(addr)) {
  4196. ast_verbose("\n");
  4197. ast_verbose("RTCP from %s\n", ast_sockaddr_stringify(addr));
  4198. ast_verbose("PT: %u(%s)\n", pt, rtcp_payload_type2str(pt));
  4199. ast_verbose("Reception reports: %u\n", rc);
  4200. ast_verbose("SSRC of sender: %u\n", ssrc);
  4201. }
  4202. if (ssrc_valid && rtp->themssrc_valid) {
  4203. if (ssrc != rtp->themssrc) {
  4204. /*
  4205. * Skip over this RTCP record as it does not contain the
  4206. * correct SSRC. We should not act upon RTCP records
  4207. * for a different stream.
  4208. */
  4209. position += length;
  4210. ast_debug(1, "%p -- RTCP from %s: Skipping record, received SSRC '%u' != expected '%u'\n",
  4211. rtp, ast_sockaddr_stringify(addr), ssrc, rtp->themssrc);
  4212. continue;
  4213. }
  4214. ssrc_seen = 1;
  4215. }
  4216. if (ssrc_seen && ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
  4217. /* Send to whoever sent to us */
  4218. if (ast_sockaddr_cmp(&rtp->rtcp->them, addr)) {
  4219. ast_sockaddr_copy(&rtp->rtcp->them, addr);
  4220. if (rtpdebug) {
  4221. ast_debug(0, "RTCP NAT: Got RTCP from other end. Now sending to address %s\n",
  4222. ast_sockaddr_stringify(addr));
  4223. }
  4224. }
  4225. }
  4226. i += RTCP_HEADER_SSRC_LENGTH; /* Advance past header and ssrc */
  4227. switch (pt) {
  4228. case RTCP_PT_SR:
  4229. gettimeofday(&rtp->rtcp->rxlsr, NULL);
  4230. rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16);
  4231. rtp->rtcp->spc = ntohl(rtcpheader[i + 3]);
  4232. rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
  4233. rtcp_report->type = RTCP_PT_SR;
  4234. rtcp_report->sender_information.packet_count = rtp->rtcp->spc;
  4235. rtcp_report->sender_information.octet_count = rtp->rtcp->soc;
  4236. ntp2timeval((unsigned int)ntohl(rtcpheader[i]),
  4237. (unsigned int)ntohl(rtcpheader[i + 1]),
  4238. &rtcp_report->sender_information.ntp_timestamp);
  4239. rtcp_report->sender_information.rtp_timestamp = ntohl(rtcpheader[i + 2]);
  4240. if (rtcp_debug_test_addr(addr)) {
  4241. ast_verbose("NTP timestamp: %u.%06u\n",
  4242. (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
  4243. (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec);
  4244. ast_verbose("RTP timestamp: %u\n", rtcp_report->sender_information.rtp_timestamp);
  4245. ast_verbose("SPC: %u\tSOC: %u\n",
  4246. rtcp_report->sender_information.packet_count,
  4247. rtcp_report->sender_information.octet_count);
  4248. }
  4249. i += RTCP_SR_BLOCK_WORD_LENGTH;
  4250. /* Intentional fall through */
  4251. case RTCP_PT_RR:
  4252. if (rtcp_report->type != RTCP_PT_SR) {
  4253. rtcp_report->type = RTCP_PT_RR;
  4254. }
  4255. if (rc > 0) {
  4256. /* Don't handle multiple reception reports (rc > 1) yet */
  4257. report_block = ast_calloc(1, sizeof(*report_block));
  4258. if (!report_block) {
  4259. return &ast_null_frame;
  4260. }
  4261. rtcp_report->report_block[0] = report_block;
  4262. report_block->source_ssrc = ntohl(rtcpheader[i]);
  4263. report_block->lost_count.packets = ntohl(rtcpheader[i + 1]) & 0x00ffffff;
  4264. report_block->lost_count.fraction = ((ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24);
  4265. report_block->highest_seq_no = ntohl(rtcpheader[i + 2]);
  4266. report_block->ia_jitter = ntohl(rtcpheader[i + 3]);
  4267. report_block->lsr = ntohl(rtcpheader[i + 4]);
  4268. report_block->dlsr = ntohl(rtcpheader[i + 5]);
  4269. if (report_block->lsr
  4270. && update_rtt_stats(rtp, report_block->lsr, report_block->dlsr)
  4271. && rtcp_debug_test_addr(addr)) {
  4272. struct timeval now;
  4273. unsigned int lsr_now, lsw, msw;
  4274. gettimeofday(&now, NULL);
  4275. timeval2ntp(now, &msw, &lsw);
  4276. lsr_now = (((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16));
  4277. ast_verbose("Internal RTCP NTP clock skew detected: "
  4278. "lsr=%u, now=%u, dlsr=%u (%u:%03ums), "
  4279. "diff=%u\n",
  4280. report_block->lsr, lsr_now, report_block->dlsr, report_block->dlsr / 65536,
  4281. (report_block->dlsr % 65536) * 1000 / 65536,
  4282. report_block->dlsr - (lsr_now - report_block->lsr));
  4283. }
  4284. update_jitter_stats(rtp, report_block->ia_jitter);
  4285. update_lost_stats(rtp, report_block->lost_count.packets);
  4286. rtp->rtcp->reported_jitter_count++;
  4287. if (rtcp_debug_test_addr(addr)) {
  4288. ast_verbose(" Fraction lost: %d\n", report_block->lost_count.fraction);
  4289. ast_verbose(" Packets lost so far: %u\n", report_block->lost_count.packets);
  4290. ast_verbose(" Highest sequence number: %u\n", report_block->highest_seq_no & 0x0000ffff);
  4291. ast_verbose(" Sequence number cycles: %u\n", report_block->highest_seq_no >> 16);
  4292. ast_verbose(" Interarrival jitter: %u\n", report_block->ia_jitter);
  4293. ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long)(report_block->lsr) >> 16,((unsigned long)(report_block->lsr) << 16) * 4096);
  4294. ast_verbose(" DLSR: %4.4f (sec)\n",(double)report_block->dlsr / 65536.0);
  4295. ast_verbose(" RTT: %4.4f(sec)\n", rtp->rtcp->rtt);
  4296. }
  4297. }
  4298. /* If and when we handle more than one report block, this should occur outside
  4299. * this loop.
  4300. */
  4301. message_blob = ast_json_pack("{s: s, s: s, s: f}",
  4302. "from", ast_sockaddr_stringify(addr),
  4303. "to", rtp->rtcp->local_addr_str,
  4304. "rtt", rtp->rtcp->rtt);
  4305. ast_rtp_publish_rtcp_message(instance, ast_rtp_rtcp_received_type(),
  4306. rtcp_report,
  4307. message_blob);
  4308. ast_json_unref(message_blob);
  4309. break;
  4310. case RTCP_PT_FUR:
  4311. /* Handle RTCP FIR as FUR */
  4312. case RTCP_PT_PSFB:
  4313. if (rtcp_debug_test_addr(addr)) {
  4314. ast_verbose("Received an RTCP Fast Update Request\n");
  4315. }
  4316. rtp->f.frametype = AST_FRAME_CONTROL;
  4317. rtp->f.subclass.integer = AST_CONTROL_VIDUPDATE;
  4318. rtp->f.datalen = 0;
  4319. rtp->f.samples = 0;
  4320. rtp->f.mallocd = 0;
  4321. rtp->f.src = "RTP";
  4322. f = &rtp->f;
  4323. break;
  4324. case RTCP_PT_SDES:
  4325. if (rtcp_debug_test_addr(addr)) {
  4326. ast_verbose("Received an SDES from %s\n",
  4327. ast_sockaddr_stringify(addr));
  4328. }
  4329. break;
  4330. case RTCP_PT_BYE:
  4331. if (rtcp_debug_test_addr(addr)) {
  4332. ast_verbose("Received a BYE from %s\n",
  4333. ast_sockaddr_stringify(addr));
  4334. }
  4335. break;
  4336. default:
  4337. break;
  4338. }
  4339. position += length;
  4340. }
  4341. rtp->rtcp->rtcp_info = 1;
  4342. return f;
  4343. }
  4344. /*! \pre instance is locked */
  4345. static struct ast_frame *ast_rtcp_read(struct ast_rtp_instance *instance)
  4346. {
  4347. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4348. struct ast_sockaddr addr;
  4349. unsigned char rtcpdata[8192 + AST_FRIENDLY_OFFSET];
  4350. unsigned char *read_area = rtcpdata + AST_FRIENDLY_OFFSET;
  4351. size_t read_area_size = sizeof(rtcpdata) - AST_FRIENDLY_OFFSET;
  4352. int res;
  4353. /* Read in RTCP data from the socket */
  4354. if ((res = rtcp_recvfrom(instance, read_area, read_area_size,
  4355. 0, &addr)) < 0) {
  4356. ast_assert(errno != EBADF);
  4357. if (errno != EAGAIN) {
  4358. ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n",
  4359. (errno) ? strerror(errno) : "Unspecified");
  4360. return NULL;
  4361. }
  4362. return &ast_null_frame;
  4363. }
  4364. /* If this was handled by the ICE session don't do anything further */
  4365. if (!res) {
  4366. return &ast_null_frame;
  4367. }
  4368. if (!*read_area) {
  4369. struct sockaddr_in addr_tmp;
  4370. struct ast_sockaddr addr_v4;
  4371. if (ast_sockaddr_is_ipv4(&addr)) {
  4372. ast_sockaddr_to_sin(&addr, &addr_tmp);
  4373. } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
  4374. ast_debug(1, "Using IPv6 mapped address %s for STUN\n",
  4375. ast_sockaddr_stringify(&addr));
  4376. ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
  4377. } else {
  4378. ast_debug(1, "Cannot do STUN for non IPv4 address %s\n",
  4379. ast_sockaddr_stringify(&addr));
  4380. return &ast_null_frame;
  4381. }
  4382. if ((ast_stun_handle_packet(rtp->rtcp->s, &addr_tmp, read_area, res, NULL, NULL) == AST_STUN_ACCEPT)) {
  4383. ast_sockaddr_from_sin(&addr, &addr_tmp);
  4384. ast_sockaddr_copy(&rtp->rtcp->them, &addr);
  4385. }
  4386. return &ast_null_frame;
  4387. }
  4388. return ast_rtcp_interpret(instance, read_area, res, &addr);
  4389. }
  4390. /*! \pre instance is locked */
  4391. static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance,
  4392. struct ast_rtp_instance *instance1, unsigned int *rtpheader, int len, int hdrlen)
  4393. {
  4394. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4395. struct ast_rtp *bridged;
  4396. int res = 0, payload = 0, bridged_payload = 0, mark;
  4397. RAII_VAR(struct ast_rtp_payload_type *, payload_type, NULL, ao2_cleanup);
  4398. int reconstruct = ntohl(rtpheader[0]);
  4399. struct ast_sockaddr remote_address = { {0,} };
  4400. int ice;
  4401. unsigned int timestamp = ntohl(rtpheader[1]);
  4402. /* Get fields from packet */
  4403. payload = (reconstruct & 0x7f0000) >> 16;
  4404. mark = (reconstruct & 0x800000) >> 23;
  4405. /* Check what the payload value should be */
  4406. payload_type = ast_rtp_codecs_get_payload(ast_rtp_instance_get_codecs(instance), payload);
  4407. if (!payload_type) {
  4408. return -1;
  4409. }
  4410. /* Otherwise adjust bridged payload to match */
  4411. bridged_payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance1), payload_type->asterisk_format, payload_type->format, payload_type->rtp_code);
  4412. /* If no codec could be matched between instance and instance1, then somehow things were made incompatible while we were still bridged. Bail. */
  4413. if (bridged_payload < 0) {
  4414. return -1;
  4415. }
  4416. /* If the payload coming in is not one of the negotiated ones then send it to the core, this will cause formats to change and the bridge to break */
  4417. if (ast_rtp_codecs_find_payload_code(ast_rtp_instance_get_codecs(instance1), bridged_payload) == -1) {
  4418. ast_debug(1, "Unsupported payload type received \n");
  4419. return -1;
  4420. }
  4421. /*
  4422. * Even if we are no longer in dtmf, we could still be receiving
  4423. * re-transmissions of the last dtmf end still. Feed those to the
  4424. * core so they can be filtered accordingly.
  4425. */
  4426. if (rtp->last_end_timestamp == timestamp) {
  4427. ast_debug(1, "Feeding packet with duplicate timestamp to core\n");
  4428. return -1;
  4429. }
  4430. if (payload_type->asterisk_format) {
  4431. ao2_replace(rtp->lastrxformat, payload_type->format);
  4432. }
  4433. /*
  4434. * We have now determined that we need to send the RTP packet
  4435. * out the bridged instance to do local bridging so we must unlock
  4436. * the receiving instance to prevent deadlock with the bridged
  4437. * instance.
  4438. *
  4439. * Technically we should grab a ref to instance1 so it won't go
  4440. * away on us. However, we should be safe because the bridged
  4441. * instance won't change without both channels involved being
  4442. * locked and we currently have the channel lock for the receiving
  4443. * instance.
  4444. */
  4445. ao2_unlock(instance);
  4446. ao2_lock(instance1);
  4447. /*
  4448. * Get the peer rtp pointer now to emphasize that using it
  4449. * must happen while instance1 is locked.
  4450. */
  4451. bridged = ast_rtp_instance_get_data(instance1);
  4452. /* If bridged peer is in dtmf, feed all packets to core until it finishes to avoid infinite dtmf */
  4453. if (bridged->sending_digit) {
  4454. ast_debug(1, "Feeding packet to core until DTMF finishes\n");
  4455. ao2_unlock(instance1);
  4456. ao2_lock(instance);
  4457. return -1;
  4458. }
  4459. if (payload_type->asterisk_format) {
  4460. /*
  4461. * If bridged peer has already received rtp, perform the asymmetric codec check
  4462. * if that feature has been activated
  4463. */
  4464. if (!bridged->asymmetric_codec
  4465. && bridged->lastrxformat != ast_format_none
  4466. && ast_format_cmp(payload_type->format, bridged->lastrxformat) == AST_FORMAT_CMP_NOT_EQUAL) {
  4467. ast_debug(1, "Asymmetric RTP codecs detected (TX: %s, RX: %s) sending frame to core\n",
  4468. ast_format_get_name(payload_type->format),
  4469. ast_format_get_name(bridged->lastrxformat));
  4470. ao2_unlock(instance1);
  4471. ao2_lock(instance);
  4472. return -1;
  4473. }
  4474. ao2_replace(bridged->lasttxformat, payload_type->format);
  4475. }
  4476. ast_rtp_instance_get_remote_address(instance1, &remote_address);
  4477. if (ast_sockaddr_isnull(&remote_address)) {
  4478. ast_debug(5, "Remote address is null, most likely RTP has been stopped\n");
  4479. ao2_unlock(instance1);
  4480. ao2_lock(instance);
  4481. return 0;
  4482. }
  4483. /* If the marker bit has been explicitly set turn it on */
  4484. if (ast_test_flag(bridged, FLAG_NEED_MARKER_BIT)) {
  4485. mark = 1;
  4486. ast_clear_flag(bridged, FLAG_NEED_MARKER_BIT);
  4487. }
  4488. /* Set the marker bit for the first local bridged packet which has the first bridged peer's SSRC. */
  4489. if (ast_test_flag(bridged, FLAG_REQ_LOCAL_BRIDGE_BIT)) {
  4490. mark = 1;
  4491. ast_clear_flag(bridged, FLAG_REQ_LOCAL_BRIDGE_BIT);
  4492. }
  4493. /* Reconstruct part of the packet */
  4494. reconstruct &= 0xFF80FFFF;
  4495. reconstruct |= (bridged_payload << 16);
  4496. reconstruct |= (mark << 23);
  4497. rtpheader[0] = htonl(reconstruct);
  4498. /* Send the packet back out */
  4499. res = rtp_sendto(instance1, (void *)rtpheader, len, 0, &remote_address, &ice);
  4500. if (res < 0) {
  4501. if (!ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_NAT) && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
  4502. ast_log(LOG_WARNING,
  4503. "RTP Transmission error of packet to %s: %s\n",
  4504. ast_sockaddr_stringify(&remote_address),
  4505. strerror(errno));
  4506. } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
  4507. if (rtpdebug || DEBUG_ATLEAST(1)) {
  4508. ast_log(LOG_WARNING,
  4509. "RTP NAT: Can't write RTP to private "
  4510. "address %s, waiting for other end to "
  4511. "send audio...\n",
  4512. ast_sockaddr_stringify(&remote_address));
  4513. }
  4514. ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
  4515. }
  4516. ao2_unlock(instance1);
  4517. ao2_lock(instance);
  4518. return 0;
  4519. }
  4520. if (rtp_debug_test_addr(&remote_address)) {
  4521. ast_verbose("Sent RTP P2P packet to %s%s (type %-2.2d, len %-6.6d)\n",
  4522. ast_sockaddr_stringify(&remote_address),
  4523. ice ? " (via ICE)" : "",
  4524. bridged_payload, len - hdrlen);
  4525. }
  4526. ao2_unlock(instance1);
  4527. ao2_lock(instance);
  4528. return 0;
  4529. }
  4530. /*! \pre instance is locked */
  4531. static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
  4532. {
  4533. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4534. struct ast_rtp_instance *instance1;
  4535. struct ast_sockaddr addr;
  4536. int res, hdrlen = 12, version, payloadtype, padding, mark, ext, cc, prev_seqno;
  4537. unsigned char *read_area = rtp->rawdata + AST_FRIENDLY_OFFSET;
  4538. size_t read_area_size = sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET;
  4539. unsigned int *rtpheader = (unsigned int*)(read_area), seqno, ssrc, timestamp;
  4540. RAII_VAR(struct ast_rtp_payload_type *, payload, NULL, ao2_cleanup);
  4541. struct ast_sockaddr remote_address = { {0,} };
  4542. struct frame_list frames;
  4543. /* If this is actually RTCP let's hop on over and handle it */
  4544. if (rtcp) {
  4545. if (rtp->rtcp && rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
  4546. return ast_rtcp_read(instance);
  4547. }
  4548. return &ast_null_frame;
  4549. }
  4550. /* If we are currently sending DTMF to the remote party send a continuation packet */
  4551. if (rtp->sending_digit) {
  4552. ast_rtp_dtmf_continuation(instance);
  4553. }
  4554. /* Actually read in the data from the socket */
  4555. if ((res = rtp_recvfrom(instance, read_area, read_area_size, 0,
  4556. &addr)) < 0) {
  4557. ast_assert(errno != EBADF);
  4558. if (errno != EAGAIN) {
  4559. ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n",
  4560. (errno) ? strerror(errno) : "Unspecified");
  4561. return NULL;
  4562. }
  4563. return &ast_null_frame;
  4564. }
  4565. /* If this was handled by the ICE session don't do anything */
  4566. if (!res) {
  4567. return &ast_null_frame;
  4568. }
  4569. /* This could be a multiplexed RTCP packet. If so, be sure to interpret it correctly */
  4570. if (rtcp_mux(rtp, read_area)) {
  4571. return ast_rtcp_interpret(instance, read_area, res, &addr);
  4572. }
  4573. /* Make sure the data that was read in is actually enough to make up an RTP packet */
  4574. if (res < hdrlen) {
  4575. /* If this is a keepalive containing only nulls, don't bother with a warning */
  4576. int i;
  4577. for (i = 0; i < res; ++i) {
  4578. if (read_area[i] != '\0') {
  4579. ast_log(LOG_WARNING, "RTP Read too short\n");
  4580. return &ast_null_frame;
  4581. }
  4582. }
  4583. return &ast_null_frame;
  4584. }
  4585. /* Get fields and verify this is an RTP packet */
  4586. seqno = ntohl(rtpheader[0]);
  4587. ast_rtp_instance_get_remote_address(instance, &remote_address);
  4588. if (!(version = (seqno & 0xC0000000) >> 30)) {
  4589. struct sockaddr_in addr_tmp;
  4590. struct ast_sockaddr addr_v4;
  4591. if (ast_sockaddr_is_ipv4(&addr)) {
  4592. ast_sockaddr_to_sin(&addr, &addr_tmp);
  4593. } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
  4594. ast_debug(1, "Using IPv6 mapped address %s for STUN\n",
  4595. ast_sockaddr_stringify(&addr));
  4596. ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
  4597. } else {
  4598. ast_debug(1, "Cannot do STUN for non IPv4 address %s\n",
  4599. ast_sockaddr_stringify(&addr));
  4600. return &ast_null_frame;
  4601. }
  4602. if ((ast_stun_handle_packet(rtp->s, &addr_tmp, read_area, res, NULL, NULL) == AST_STUN_ACCEPT) &&
  4603. ast_sockaddr_isnull(&remote_address)) {
  4604. ast_sockaddr_from_sin(&addr, &addr_tmp);
  4605. ast_rtp_instance_set_remote_address(instance, &addr);
  4606. }
  4607. return &ast_null_frame;
  4608. }
  4609. /* If the version is not what we expected by this point then just drop the packet */
  4610. if (version != 2) {
  4611. return &ast_null_frame;
  4612. }
  4613. /* If strict RTP protection is enabled see if we need to learn the remote address or if we need to drop the packet */
  4614. switch (rtp->strict_rtp_state) {
  4615. case STRICT_RTP_LEARN:
  4616. /*
  4617. * Scenario setup:
  4618. * PartyA -- Ast1 -- Ast2 -- PartyB
  4619. *
  4620. * The learning timeout is necessary for Ast1 to handle the above
  4621. * setup where PartyA calls PartyB and Ast2 initiates direct media
  4622. * between Ast1 and PartyB. Ast1 may lock onto the Ast2 stream and
  4623. * never learn the PartyB stream when it starts. The timeout makes
  4624. * Ast1 stay in the learning state long enough to see and learn the
  4625. * RTP stream from PartyB.
  4626. *
  4627. * To mitigate against attack, the learning state cannot switch
  4628. * streams while there are competing streams. The competing streams
  4629. * interfere with each other's qualification. Once we accept a
  4630. * stream and reach the timeout, an attacker cannot interfere
  4631. * anymore.
  4632. *
  4633. * Here are a few scenarios and each one assumes that the streams
  4634. * are continuous:
  4635. *
  4636. * 1) We already have a known stream source address and the known
  4637. * stream wants to change to a new source address. An attacking
  4638. * stream will block learning the new stream source. After the
  4639. * timeout we re-lock onto the original stream source address which
  4640. * likely went away. The result is one way audio.
  4641. *
  4642. * 2) We already have a known stream source address and the known
  4643. * stream doesn't want to change source addresses. An attacking
  4644. * stream will not be able to replace the known stream. After the
  4645. * timeout we re-lock onto the known stream. The call is not
  4646. * affected.
  4647. *
  4648. * 3) We don't have a known stream source address. This presumably
  4649. * is the start of a call. Competing streams will result in staying
  4650. * in learning mode until a stream becomes the victor and we reach
  4651. * the timeout. We cannot exit learning if we have no known stream
  4652. * to lock onto. The result is one way audio until there is a victor.
  4653. *
  4654. * If we learn a stream source address before the timeout we will be
  4655. * in scenario 1) or 2) when a competing stream starts.
  4656. */
  4657. if (!ast_sockaddr_isnull(&rtp->strict_rtp_address)
  4658. && STRICT_RTP_LEARN_TIMEOUT < ast_tvdiff_ms(ast_tvnow(), rtp->rtp_source_learn.start)) {
  4659. ast_verb(4, "%p -- Strict RTP learning complete - Locking on source address %s\n",
  4660. rtp, ast_sockaddr_stringify(&rtp->strict_rtp_address));
  4661. ast_test_suite_event_notify("STRICT_RTP_LEARN", "Source: %s",
  4662. ast_sockaddr_stringify(&rtp->strict_rtp_address));
  4663. rtp->strict_rtp_state = STRICT_RTP_CLOSED;
  4664. } else {
  4665. struct ast_sockaddr target_address;
  4666. if (!ast_sockaddr_cmp(&rtp->strict_rtp_address, &addr)) {
  4667. /*
  4668. * We are open to learning a new address but have received
  4669. * traffic from the current address, accept it and reset
  4670. * the learning counts for a new source. When no more
  4671. * current source packets arrive a new source can take over
  4672. * once sufficient traffic is received.
  4673. */
  4674. rtp_learning_seq_init(&rtp->rtp_source_learn, seqno);
  4675. break;
  4676. }
  4677. /*
  4678. * We give preferential treatment to the requested target address
  4679. * (negotiated SDP address) where we are to send our RTP. However,
  4680. * the other end has no obligation to send from that address even
  4681. * though it is practically a requirement when NAT is involved.
  4682. */
  4683. ast_rtp_instance_get_requested_target_address(instance, &target_address);
  4684. if (!ast_sockaddr_cmp(&target_address, &addr)) {
  4685. /* Accept the negotiated target RTP stream as the source */
  4686. ast_verb(4, "%p -- Strict RTP switching to RTP target address %s as source\n",
  4687. rtp, ast_sockaddr_stringify(&addr));
  4688. ast_sockaddr_copy(&rtp->strict_rtp_address, &addr);
  4689. rtp_learning_seq_init(&rtp->rtp_source_learn, seqno);
  4690. break;
  4691. }
  4692. /*
  4693. * Trying to learn a new address. If we pass a probationary period
  4694. * with it, that means we've stopped getting RTP from the original
  4695. * source and we should switch to it.
  4696. */
  4697. if (!ast_sockaddr_cmp(&rtp->rtp_source_learn.proposed_address, &addr)) {
  4698. if (rtp->rtp_source_learn.stream_type == AST_MEDIA_TYPE_UNKNOWN) {
  4699. struct ast_rtp_codecs *codecs;
  4700. codecs = ast_rtp_instance_get_codecs(instance);
  4701. rtp->rtp_source_learn.stream_type =
  4702. ast_rtp_codecs_get_stream_type(codecs);
  4703. ast_verb(4, "%p -- Strict RTP qualifying stream type: %s\n",
  4704. rtp, ast_codec_media_type2str(rtp->rtp_source_learn.stream_type));
  4705. }
  4706. if (!rtp_learning_rtp_seq_update(&rtp->rtp_source_learn, seqno)) {
  4707. /* Accept the new RTP stream */
  4708. ast_verb(4, "%p -- Strict RTP switching source address to %s\n",
  4709. rtp, ast_sockaddr_stringify(&addr));
  4710. ast_sockaddr_copy(&rtp->strict_rtp_address, &addr);
  4711. rtp_learning_seq_init(&rtp->rtp_source_learn, seqno);
  4712. break;
  4713. }
  4714. /* Not ready to accept the RTP stream candidate */
  4715. ast_debug(1, "%p -- Received RTP packet from %s, dropping due to strict RTP protection. Will switch to it in %d packets.\n",
  4716. rtp, ast_sockaddr_stringify(&addr), rtp->rtp_source_learn.packets);
  4717. } else {
  4718. /*
  4719. * This is either an attacking stream or
  4720. * the start of the expected new stream.
  4721. */
  4722. ast_sockaddr_copy(&rtp->rtp_source_learn.proposed_address, &addr);
  4723. rtp_learning_seq_init(&rtp->rtp_source_learn, seqno);
  4724. ast_debug(1, "%p -- Received RTP packet from %s, dropping due to strict RTP protection. Qualifying new stream.\n",
  4725. rtp, ast_sockaddr_stringify(&addr));
  4726. }
  4727. return &ast_null_frame;
  4728. }
  4729. /* Fall through */
  4730. case STRICT_RTP_CLOSED:
  4731. /*
  4732. * We should not allow a stream address change if the SSRC matches
  4733. * once strictrtp learning is closed. Any kind of address change
  4734. * like this should have happened while we were in the learning
  4735. * state. We do not want to allow the possibility of an attacker
  4736. * interfering with the RTP stream after the learning period.
  4737. * An attacker could manage to get an RTCP packet redirected to
  4738. * them which can contain the SSRC value.
  4739. */
  4740. if (!ast_sockaddr_cmp(&rtp->strict_rtp_address, &addr)) {
  4741. break;
  4742. }
  4743. ast_debug(1, "%p -- Received RTP packet from %s, dropping due to strict RTP protection.\n",
  4744. rtp, ast_sockaddr_stringify(&addr));
  4745. #ifdef TEST_FRAMEWORK
  4746. {
  4747. static int strict_rtp_test_event = 1;
  4748. if (strict_rtp_test_event) {
  4749. ast_test_suite_event_notify("STRICT_RTP_CLOSED", "Source: %s",
  4750. ast_sockaddr_stringify(&addr));
  4751. strict_rtp_test_event = 0; /* Only run this event once to prevent possible spam */
  4752. }
  4753. }
  4754. #endif
  4755. return &ast_null_frame;
  4756. case STRICT_RTP_OPEN:
  4757. break;
  4758. }
  4759. /* If symmetric RTP is enabled see if the remote side is not what we expected and change where we are sending audio */
  4760. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
  4761. if (ast_sockaddr_cmp(&remote_address, &addr)) {
  4762. /* do not update the originally given address, but only the remote */
  4763. ast_rtp_instance_set_incoming_source_address(instance, &addr);
  4764. ast_sockaddr_copy(&remote_address, &addr);
  4765. if (rtp->rtcp && rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
  4766. ast_sockaddr_copy(&rtp->rtcp->them, &addr);
  4767. ast_sockaddr_set_port(&rtp->rtcp->them, ast_sockaddr_port(&addr) + 1);
  4768. }
  4769. ast_set_flag(rtp, FLAG_NAT_ACTIVE);
  4770. if (rtpdebug)
  4771. ast_debug(0, "RTP NAT: Got audio from other end. Now sending to address %s\n",
  4772. ast_sockaddr_stringify(&remote_address));
  4773. }
  4774. }
  4775. /* Pull out the various other fields we will need */
  4776. payloadtype = (seqno & 0x7f0000) >> 16;
  4777. padding = seqno & (1 << 29);
  4778. mark = seqno & (1 << 23);
  4779. ext = seqno & (1 << 28);
  4780. cc = (seqno & 0xF000000) >> 24;
  4781. seqno &= 0xffff;
  4782. timestamp = ntohl(rtpheader[1]);
  4783. ssrc = ntohl(rtpheader[2]);
  4784. AST_LIST_HEAD_INIT_NOLOCK(&frames);
  4785. /* Force a marker bit and change SSRC if the SSRC changes */
  4786. if (rtp->themssrc_valid && rtp->themssrc != ssrc) {
  4787. struct ast_frame *f, srcupdate = {
  4788. AST_FRAME_CONTROL,
  4789. .subclass.integer = AST_CONTROL_SRCCHANGE,
  4790. };
  4791. if (!mark) {
  4792. if (rtpdebug) {
  4793. ast_debug(1, "Forcing Marker bit, because SSRC has changed\n");
  4794. }
  4795. mark = 1;
  4796. }
  4797. f = ast_frisolate(&srcupdate);
  4798. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  4799. rtp->seedrxseqno = 0;
  4800. rtp->rxcount = 0;
  4801. rtp->rxoctetcount = 0;
  4802. rtp->cycles = 0;
  4803. rtp->lastrxseqno = 0;
  4804. rtp->last_seqno = 0;
  4805. rtp->last_end_timestamp = 0;
  4806. if (rtp->rtcp) {
  4807. rtp->rtcp->expected_prior = 0;
  4808. rtp->rtcp->received_prior = 0;
  4809. }
  4810. }
  4811. rtp->themssrc = ssrc; /* Record their SSRC to put in future RR */
  4812. rtp->themssrc_valid = 1;
  4813. /* Remove any padding bytes that may be present */
  4814. if (padding) {
  4815. res -= read_area[res - 1];
  4816. }
  4817. /* Skip over any CSRC fields */
  4818. if (cc) {
  4819. hdrlen += cc * 4;
  4820. }
  4821. /* Look for any RTP extensions, currently we do not support any */
  4822. if (ext) {
  4823. hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
  4824. hdrlen += 4;
  4825. if (DEBUG_ATLEAST(1)) {
  4826. unsigned int profile;
  4827. profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
  4828. if (profile == 0x505a) {
  4829. ast_log(LOG_DEBUG, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
  4830. } else {
  4831. ast_log(LOG_DEBUG, "Found unknown RTP Extensions %x\n", profile);
  4832. }
  4833. }
  4834. }
  4835. /* Make sure after we potentially mucked with the header length that it is once again valid */
  4836. if (res < hdrlen) {
  4837. ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d\n", res, hdrlen);
  4838. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  4839. }
  4840. rtp->rxcount++;
  4841. rtp->rxoctetcount += (res - hdrlen);
  4842. if (rtp->rxcount == 1) {
  4843. rtp->seedrxseqno = seqno;
  4844. }
  4845. /* Do not schedule RR if RTCP isn't run */
  4846. if (rtp->rtcp && !ast_sockaddr_isnull(&rtp->rtcp->them) && rtp->rtcp->schedid < 0) {
  4847. /* Schedule transmission of Receiver Report */
  4848. ao2_ref(instance, +1);
  4849. rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
  4850. if (rtp->rtcp->schedid < 0) {
  4851. ao2_ref(instance, -1);
  4852. ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
  4853. }
  4854. }
  4855. if ((int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
  4856. rtp->cycles += RTP_SEQ_MOD;
  4857. prev_seqno = rtp->lastrxseqno;
  4858. rtp->lastrxseqno = seqno;
  4859. /* If we are directly bridged to another instance send the audio directly out,
  4860. * but only after updating core information about the received traffic so that
  4861. * outgoing RTCP reflects it.
  4862. */
  4863. instance1 = ast_rtp_instance_get_bridged(instance);
  4864. if (instance1
  4865. && !bridge_p2p_rtp_write(instance, instance1, rtpheader, res, hdrlen)) {
  4866. struct timeval rxtime;
  4867. struct ast_frame *f;
  4868. /* Update statistics for jitter so they are correct in RTCP */
  4869. calc_rxstamp(&rxtime, rtp, timestamp, mark);
  4870. /* When doing P2P we don't need to raise any frames about SSRC change to the core */
  4871. while ((f = AST_LIST_REMOVE_HEAD(&frames, frame_list)) != NULL) {
  4872. ast_frfree(f);
  4873. }
  4874. return &ast_null_frame;
  4875. }
  4876. if (rtp_debug_test_addr(&addr)) {
  4877. ast_verbose("Got RTP packet from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6d)\n",
  4878. ast_sockaddr_stringify(&addr),
  4879. payloadtype, seqno, timestamp,res - hdrlen);
  4880. }
  4881. payload = ast_rtp_codecs_get_payload(ast_rtp_instance_get_codecs(instance), payloadtype);
  4882. if (!payload) {
  4883. /* Unknown payload type. */
  4884. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  4885. }
  4886. /* If the payload is not actually an Asterisk one but a special one pass it off to the respective handler */
  4887. if (!payload->asterisk_format) {
  4888. struct ast_frame *f = NULL;
  4889. if (payload->rtp_code == AST_RTP_DTMF) {
  4890. /* process_dtmf_rfc2833 may need to return multiple frames. We do this
  4891. * by passing the pointer to the frame list to it so that the method
  4892. * can append frames to the list as needed.
  4893. */
  4894. process_dtmf_rfc2833(instance, read_area + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark, &frames);
  4895. } else if (payload->rtp_code == AST_RTP_CISCO_DTMF) {
  4896. f = process_dtmf_cisco(instance, read_area + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
  4897. } else if (payload->rtp_code == AST_RTP_CN) {
  4898. f = process_cn_rfc3389(instance, read_area + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
  4899. } else {
  4900. ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n",
  4901. payloadtype,
  4902. ast_sockaddr_stringify(&remote_address));
  4903. }
  4904. if (f) {
  4905. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  4906. }
  4907. /* Even if no frame was returned by one of the above methods,
  4908. * we may have a frame to return in our frame list
  4909. */
  4910. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  4911. }
  4912. ao2_replace(rtp->lastrxformat, payload->format);
  4913. ao2_replace(rtp->f.subclass.format, payload->format);
  4914. switch (ast_format_get_type(rtp->f.subclass.format)) {
  4915. case AST_MEDIA_TYPE_AUDIO:
  4916. rtp->f.frametype = AST_FRAME_VOICE;
  4917. break;
  4918. case AST_MEDIA_TYPE_VIDEO:
  4919. rtp->f.frametype = AST_FRAME_VIDEO;
  4920. break;
  4921. case AST_MEDIA_TYPE_TEXT:
  4922. rtp->f.frametype = AST_FRAME_TEXT;
  4923. break;
  4924. case AST_MEDIA_TYPE_IMAGE:
  4925. /* Fall through */
  4926. default:
  4927. ast_log(LOG_WARNING, "Unknown or unsupported media type: %s\n",
  4928. ast_codec_media_type2str(ast_format_get_type(rtp->f.subclass.format)));
  4929. return &ast_null_frame;
  4930. }
  4931. if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
  4932. rtp->dtmf_timeout = 0;
  4933. if (rtp->resp) {
  4934. struct ast_frame *f;
  4935. f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0);
  4936. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.format)), ast_tv(0, 0));
  4937. rtp->resp = 0;
  4938. rtp->dtmf_timeout = rtp->dtmf_duration = 0;
  4939. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  4940. return AST_LIST_FIRST(&frames);
  4941. }
  4942. }
  4943. rtp->f.src = "RTP";
  4944. rtp->f.mallocd = 0;
  4945. rtp->f.datalen = res - hdrlen;
  4946. rtp->f.data.ptr = read_area + hdrlen;
  4947. rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
  4948. rtp->f.seqno = seqno;
  4949. if ((ast_format_cmp(rtp->f.subclass.format, ast_format_t140) == AST_FORMAT_CMP_EQUAL)
  4950. && ((int)seqno - (prev_seqno + 1) > 0)
  4951. && ((int)seqno - (prev_seqno + 1) < 10)) {
  4952. unsigned char *data = rtp->f.data.ptr;
  4953. memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
  4954. rtp->f.datalen +=3;
  4955. *data++ = 0xEF;
  4956. *data++ = 0xBF;
  4957. *data = 0xBD;
  4958. }
  4959. if (ast_format_cmp(rtp->f.subclass.format, ast_format_t140_red) == AST_FORMAT_CMP_EQUAL) {
  4960. unsigned char *data = rtp->f.data.ptr;
  4961. unsigned char *header_end;
  4962. int num_generations;
  4963. int header_length;
  4964. int len;
  4965. int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
  4966. int x;
  4967. ao2_replace(rtp->f.subclass.format, ast_format_t140);
  4968. header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
  4969. if (header_end == NULL) {
  4970. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  4971. }
  4972. header_end++;
  4973. header_length = header_end - data;
  4974. num_generations = header_length / 4;
  4975. len = header_length;
  4976. if (!diff) {
  4977. for (x = 0; x < num_generations; x++)
  4978. len += data[x * 4 + 3];
  4979. if (!(rtp->f.datalen - len))
  4980. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  4981. rtp->f.data.ptr += len;
  4982. rtp->f.datalen -= len;
  4983. } else if (diff > num_generations && diff < 10) {
  4984. len -= 3;
  4985. rtp->f.data.ptr += len;
  4986. rtp->f.datalen -= len;
  4987. data = rtp->f.data.ptr;
  4988. *data++ = 0xEF;
  4989. *data++ = 0xBF;
  4990. *data = 0xBD;
  4991. } else {
  4992. for ( x = 0; x < num_generations - diff; x++)
  4993. len += data[x * 4 + 3];
  4994. rtp->f.data.ptr += len;
  4995. rtp->f.datalen -= len;
  4996. }
  4997. }
  4998. if (ast_format_get_type(rtp->f.subclass.format) == AST_MEDIA_TYPE_AUDIO) {
  4999. rtp->f.samples = ast_codec_samples_count(&rtp->f);
  5000. if (ast_format_cache_is_slinear(rtp->f.subclass.format)) {
  5001. ast_frame_byteswap_be(&rtp->f);
  5002. }
  5003. calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
  5004. /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
  5005. ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
  5006. rtp->f.ts = timestamp / (rtp_get_rate(rtp->f.subclass.format) / 1000);
  5007. rtp->f.len = rtp->f.samples / ((ast_format_get_sample_rate(rtp->f.subclass.format) / 1000));
  5008. } else if (ast_format_get_type(rtp->f.subclass.format) == AST_MEDIA_TYPE_VIDEO) {
  5009. /* Video -- samples is # of samples vs. 90000 */
  5010. if (!rtp->lastividtimestamp)
  5011. rtp->lastividtimestamp = timestamp;
  5012. ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
  5013. rtp->f.ts = timestamp / (rtp_get_rate(rtp->f.subclass.format) / 1000);
  5014. rtp->f.samples = timestamp - rtp->lastividtimestamp;
  5015. rtp->lastividtimestamp = timestamp;
  5016. rtp->f.delivery.tv_sec = 0;
  5017. rtp->f.delivery.tv_usec = 0;
  5018. /* Pass the RTP marker bit as bit */
  5019. rtp->f.subclass.frame_ending = mark ? 1 : 0;
  5020. } else if (ast_format_get_type(rtp->f.subclass.format) == AST_MEDIA_TYPE_TEXT) {
  5021. /* TEXT -- samples is # of samples vs. 1000 */
  5022. if (!rtp->lastitexttimestamp)
  5023. rtp->lastitexttimestamp = timestamp;
  5024. rtp->f.samples = timestamp - rtp->lastitexttimestamp;
  5025. rtp->lastitexttimestamp = timestamp;
  5026. rtp->f.delivery.tv_sec = 0;
  5027. rtp->f.delivery.tv_usec = 0;
  5028. } else {
  5029. ast_log(LOG_WARNING, "Unknown or unsupported media type: %s\n",
  5030. ast_codec_media_type2str(ast_format_get_type(rtp->f.subclass.format)));
  5031. return &ast_null_frame;;
  5032. }
  5033. AST_LIST_INSERT_TAIL(&frames, &rtp->f, frame_list);
  5034. return AST_LIST_FIRST(&frames);
  5035. }
  5036. /*! \pre instance is locked */
  5037. static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
  5038. {
  5039. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5040. if (property == AST_RTP_PROPERTY_RTCP) {
  5041. if (value) {
  5042. struct ast_sockaddr local_addr;
  5043. if (rtp->rtcp && rtp->rtcp->type == value) {
  5044. ast_debug(1, "Ignoring duplicate RTCP property on RTP instance '%p'\n", instance);
  5045. return;
  5046. }
  5047. if (!rtp->rtcp) {
  5048. rtp->rtcp = ast_calloc(1, sizeof(*rtp->rtcp));
  5049. if (!rtp->rtcp) {
  5050. return;
  5051. }
  5052. rtp->rtcp->s = -1;
  5053. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  5054. rtp->rtcp->dtls.timeout_timer = -1;
  5055. #endif
  5056. rtp->rtcp->schedid = -1;
  5057. }
  5058. rtp->rtcp->type = value;
  5059. /* Grab the IP address and port we are going to use */
  5060. ast_rtp_instance_get_local_address(instance, &rtp->rtcp->us);
  5061. if (value == AST_RTP_INSTANCE_RTCP_STANDARD) {
  5062. ast_sockaddr_set_port(&rtp->rtcp->us,
  5063. ast_sockaddr_port(&rtp->rtcp->us) + 1);
  5064. }
  5065. ast_sockaddr_copy(&local_addr, &rtp->rtcp->us);
  5066. if (!ast_find_ourip(&local_addr, &rtp->rtcp->us, 0)) {
  5067. ast_sockaddr_set_port(&local_addr, ast_sockaddr_port(&rtp->rtcp->us));
  5068. } else {
  5069. /* Failed to get local address reset to use default. */
  5070. ast_sockaddr_copy(&local_addr, &rtp->rtcp->us);
  5071. }
  5072. ast_free(rtp->rtcp->local_addr_str);
  5073. rtp->rtcp->local_addr_str = ast_strdup(ast_sockaddr_stringify(&local_addr));
  5074. if (!rtp->rtcp->local_addr_str) {
  5075. ast_free(rtp->rtcp);
  5076. rtp->rtcp = NULL;
  5077. return;
  5078. }
  5079. if (value == AST_RTP_INSTANCE_RTCP_STANDARD) {
  5080. /* We're either setting up RTCP from scratch or
  5081. * switching from MUX. Either way, we won't have
  5082. * a socket set up, and we need to set it up
  5083. */
  5084. if ((rtp->rtcp->s =
  5085. create_new_socket("RTCP",
  5086. ast_sockaddr_is_ipv4(&rtp->rtcp->us) ?
  5087. AF_INET :
  5088. ast_sockaddr_is_ipv6(&rtp->rtcp->us) ?
  5089. AF_INET6 : -1)) < 0) {
  5090. ast_debug(1, "Failed to create a new socket for RTCP on instance '%p'\n", instance);
  5091. ast_free(rtp->rtcp->local_addr_str);
  5092. ast_free(rtp->rtcp);
  5093. rtp->rtcp = NULL;
  5094. return;
  5095. }
  5096. /* Try to actually bind to the IP address and port we are going to use for RTCP, if this fails we have to bail out */
  5097. if (ast_bind(rtp->rtcp->s, &rtp->rtcp->us)) {
  5098. ast_debug(1, "Failed to setup RTCP on RTP instance '%p'\n", instance);
  5099. close(rtp->rtcp->s);
  5100. ast_free(rtp->rtcp->local_addr_str);
  5101. ast_free(rtp->rtcp);
  5102. rtp->rtcp = NULL;
  5103. return;
  5104. }
  5105. #ifdef HAVE_PJPROJECT
  5106. if (rtp->ice) {
  5107. rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us, ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP, TRANSPORT_SOCKET_RTCP);
  5108. }
  5109. #endif
  5110. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  5111. dtls_setup_rtcp(instance);
  5112. #endif
  5113. } else {
  5114. struct ast_sockaddr addr;
  5115. /* RTCPMUX uses the same socket as RTP. If we were previously using standard RTCP
  5116. * then close the socket we previously created.
  5117. *
  5118. * It may seem as though there is a possible race condition here where we might try
  5119. * to close the RTCP socket while it is being used to send data. However, this is not
  5120. * a problem in practice since setting and adjusting of RTCP properties happens prior
  5121. * to activating RTP. It is not until RTP is activated that timers start for RTCP
  5122. * transmission
  5123. */
  5124. if (rtp->rtcp->s > -1 && rtp->rtcp->s != rtp->s) {
  5125. close(rtp->rtcp->s);
  5126. }
  5127. rtp->rtcp->s = rtp->s;
  5128. ast_rtp_instance_get_remote_address(instance, &addr);
  5129. ast_sockaddr_copy(&rtp->rtcp->them, &addr);
  5130. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  5131. if (rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
  5132. SSL_free(rtp->rtcp->dtls.ssl);
  5133. }
  5134. rtp->rtcp->dtls.ssl = rtp->dtls.ssl;
  5135. #endif
  5136. }
  5137. ast_debug(1, "Setup RTCP on RTP instance '%p'\n", instance);
  5138. } else {
  5139. if (rtp->rtcp) {
  5140. if (rtp->rtcp->schedid > -1) {
  5141. ao2_unlock(instance);
  5142. if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
  5143. /* Successfully cancelled scheduler entry. */
  5144. ao2_ref(instance, -1);
  5145. } else {
  5146. /* Unable to cancel scheduler entry */
  5147. ast_debug(1, "Failed to tear down RTCP on RTP instance '%p'\n", instance);
  5148. ao2_lock(instance);
  5149. return;
  5150. }
  5151. ao2_lock(instance);
  5152. rtp->rtcp->schedid = -1;
  5153. }
  5154. if (rtp->rtcp->s > -1 && rtp->rtcp->s != rtp->s) {
  5155. close(rtp->rtcp->s);
  5156. }
  5157. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  5158. ao2_unlock(instance);
  5159. dtls_srtp_stop_timeout_timer(instance, rtp, 1);
  5160. ao2_lock(instance);
  5161. if (rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
  5162. SSL_free(rtp->rtcp->dtls.ssl);
  5163. }
  5164. #endif
  5165. ast_free(rtp->rtcp->local_addr_str);
  5166. ast_free(rtp->rtcp);
  5167. rtp->rtcp = NULL;
  5168. }
  5169. }
  5170. } else if (property == AST_RTP_PROPERTY_ASYMMETRIC_CODEC) {
  5171. rtp->asymmetric_codec = value;
  5172. }
  5173. }
  5174. /*! \pre instance is locked */
  5175. static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp)
  5176. {
  5177. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5178. return rtcp ? (rtp->rtcp ? rtp->rtcp->s : -1) : rtp->s;
  5179. }
  5180. /*! \pre instance is locked */
  5181. static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
  5182. {
  5183. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5184. struct ast_sockaddr local;
  5185. ast_rtp_instance_get_local_address(instance, &local);
  5186. if (!ast_sockaddr_isnull(addr)) {
  5187. /* Update the local RTP address with what is being used */
  5188. if (ast_ouraddrfor(addr, &local)) {
  5189. /* Failed to update our address so reuse old local address */
  5190. ast_rtp_instance_get_local_address(instance, &local);
  5191. } else {
  5192. ast_rtp_instance_set_local_address(instance, &local);
  5193. }
  5194. }
  5195. if (rtp->rtcp && !ast_sockaddr_isnull(addr)) {
  5196. ast_debug(1, "Setting RTCP address on RTP instance '%p'\n", instance);
  5197. ast_sockaddr_copy(&rtp->rtcp->them, addr);
  5198. if (rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
  5199. ast_sockaddr_set_port(&rtp->rtcp->them, ast_sockaddr_port(addr) + 1);
  5200. /* Update the local RTCP address with what is being used */
  5201. ast_sockaddr_set_port(&local, ast_sockaddr_port(&local) + 1);
  5202. }
  5203. ast_sockaddr_copy(&rtp->rtcp->us, &local);
  5204. ast_free(rtp->rtcp->local_addr_str);
  5205. rtp->rtcp->local_addr_str = ast_strdup(ast_sockaddr_stringify(&local));
  5206. }
  5207. /* Need to reset the DTMF last sequence number and the timestamp of the last END packet */
  5208. rtp->last_seqno = 0;
  5209. rtp->last_end_timestamp = 0;
  5210. if (strictrtp && rtp->strict_rtp_state != STRICT_RTP_OPEN
  5211. && !ast_sockaddr_isnull(addr) && ast_sockaddr_cmp(addr, &rtp->strict_rtp_address)) {
  5212. /* We only need to learn a new strict source address if we've been told the source is
  5213. * changing to something different.
  5214. */
  5215. ast_verb(4, "%p -- Strict RTP learning after remote address set to: %s\n",
  5216. rtp, ast_sockaddr_stringify(addr));
  5217. rtp_learning_start(rtp);
  5218. }
  5219. }
  5220. /*!
  5221. * \brief Write t140 redundacy frame
  5222. *
  5223. * \param data primary data to be buffered
  5224. *
  5225. * Scheduler callback
  5226. */
  5227. static int red_write(const void *data)
  5228. {
  5229. struct ast_rtp_instance *instance = (struct ast_rtp_instance*) data;
  5230. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5231. ao2_lock(instance);
  5232. if (rtp->red->t140.datalen > 0) {
  5233. ast_rtp_write(instance, &rtp->red->t140);
  5234. }
  5235. ao2_unlock(instance);
  5236. return 1;
  5237. }
  5238. /*! \pre instance is locked */
  5239. static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
  5240. {
  5241. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5242. int x;
  5243. rtp->red = ast_calloc(1, sizeof(*rtp->red));
  5244. if (!rtp->red) {
  5245. return -1;
  5246. }
  5247. rtp->red->t140.frametype = AST_FRAME_TEXT;
  5248. rtp->red->t140.subclass.format = ast_format_t140_red;
  5249. rtp->red->t140.data.ptr = &rtp->red->buf_data;
  5250. rtp->red->t140red = rtp->red->t140;
  5251. rtp->red->t140red.data.ptr = &rtp->red->t140red_data;
  5252. rtp->red->ti = buffer_time;
  5253. rtp->red->num_gen = generations;
  5254. rtp->red->hdrlen = generations * 4 + 1;
  5255. for (x = 0; x < generations; x++) {
  5256. rtp->red->pt[x] = payloads[x];
  5257. rtp->red->pt[x] |= 1 << 7; /* mark redundant generations pt */
  5258. rtp->red->t140red_data[x*4] = rtp->red->pt[x];
  5259. }
  5260. rtp->red->t140red_data[x*4] = rtp->red->pt[x] = payloads[x]; /* primary pt */
  5261. rtp->red->schedid = ast_sched_add(rtp->sched, generations, red_write, instance);
  5262. return 0;
  5263. }
  5264. /*! \pre instance is locked */
  5265. static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
  5266. {
  5267. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5268. struct rtp_red *red = rtp->red;
  5269. if (!red) {
  5270. return 0;
  5271. }
  5272. if (frame->datalen > 0) {
  5273. if (red->t140.datalen > 0) {
  5274. const unsigned char *primary = red->buf_data;
  5275. /* There is something already in the T.140 buffer */
  5276. if (primary[0] == 0x08 || primary[0] == 0x0a || primary[0] == 0x0d) {
  5277. /* Flush the previous T.140 packet if it is a command */
  5278. ast_rtp_write(instance, &rtp->red->t140);
  5279. } else {
  5280. primary = frame->data.ptr;
  5281. if (primary[0] == 0x08 || primary[0] == 0x0a || primary[0] == 0x0d) {
  5282. /* Flush the previous T.140 packet if we are buffering a command now */
  5283. ast_rtp_write(instance, &rtp->red->t140);
  5284. }
  5285. }
  5286. }
  5287. memcpy(&red->buf_data[red->t140.datalen], frame->data.ptr, frame->datalen);
  5288. red->t140.datalen += frame->datalen;
  5289. red->t140.ts = frame->ts;
  5290. }
  5291. return 0;
  5292. }
  5293. /*! \pre Neither instance0 nor instance1 are locked */
  5294. static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1)
  5295. {
  5296. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance0);
  5297. ao2_lock(instance0);
  5298. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT | FLAG_REQ_LOCAL_BRIDGE_BIT);
  5299. ao2_unlock(instance0);
  5300. return 0;
  5301. }
  5302. /*! \pre instance is locked */
  5303. static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
  5304. {
  5305. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5306. if (!rtp->rtcp) {
  5307. return -1;
  5308. }
  5309. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXCOUNT, -1, stats->txcount, rtp->txcount);
  5310. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXCOUNT, -1, stats->rxcount, rtp->rxcount);
  5311. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXOCTETCOUNT, -1, stats->txoctetcount, rtp->txoctetcount);
  5312. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXOCTETCOUNT, -1, stats->rxoctetcount, rtp->rxoctetcount);
  5313. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->txploss, rtp->rtcp->reported_lost);
  5314. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->rxploss, rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
  5315. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_maxrxploss, rtp->rtcp->reported_maxlost);
  5316. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_minrxploss, rtp->rtcp->reported_minlost);
  5317. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_normdevrxploss, rtp->rtcp->reported_normdev_lost);
  5318. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_stdevrxploss, rtp->rtcp->reported_stdev_lost);
  5319. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_maxrxploss, rtp->rtcp->maxrxlost);
  5320. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_minrxploss, rtp->rtcp->minrxlost);
  5321. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_normdevrxploss, rtp->rtcp->normdev_rxlost);
  5322. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_stdevrxploss, rtp->rtcp->stdev_rxlost);
  5323. AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_LOSS);
  5324. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->txjitter, rtp->rxjitter);
  5325. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->rxjitter, rtp->rtcp->reported_jitter / (unsigned int) 65536.0);
  5326. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_maxjitter, rtp->rtcp->reported_maxjitter);
  5327. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_minjitter, rtp->rtcp->reported_minjitter);
  5328. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_normdevjitter, rtp->rtcp->reported_normdev_jitter);
  5329. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_stdevjitter, rtp->rtcp->reported_stdev_jitter);
  5330. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_maxjitter, rtp->rtcp->maxrxjitter);
  5331. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_minjitter, rtp->rtcp->minrxjitter);
  5332. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_normdevjitter, rtp->rtcp->normdev_rxjitter);
  5333. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_stdevjitter, rtp->rtcp->stdev_rxjitter);
  5334. AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_JITTER);
  5335. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->rtt, rtp->rtcp->rtt);
  5336. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MAX_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->maxrtt, rtp->rtcp->maxrtt);
  5337. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MIN_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->minrtt, rtp->rtcp->minrtt);
  5338. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_NORMDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->normdevrtt, rtp->rtcp->normdevrtt);
  5339. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_STDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->stdevrtt, rtp->rtcp->stdevrtt);
  5340. AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_RTT);
  5341. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_SSRC, -1, stats->local_ssrc, rtp->ssrc);
  5342. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_SSRC, -1, stats->remote_ssrc, rtp->themssrc);
  5343. AST_RTP_STAT_STRCPY(AST_RTP_INSTANCE_STAT_CHANNEL_UNIQUEID, -1, stats->channel_uniqueid, ast_rtp_instance_get_channel_id(instance));
  5344. return 0;
  5345. }
  5346. /*! \pre Neither instance0 nor instance1 are locked */
  5347. static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1)
  5348. {
  5349. /* If both sides are not using the same method of DTMF transmission
  5350. * (ie: one is RFC2833, other is INFO... then we can not do direct media.
  5351. * --------------------------------------------------
  5352. * | DTMF Mode | HAS_DTMF | Accepts Begin Frames |
  5353. * |-----------|------------|-----------------------|
  5354. * | Inband | False | True |
  5355. * | RFC2833 | True | True |
  5356. * | SIP INFO | False | False |
  5357. * --------------------------------------------------
  5358. */
  5359. return (((ast_rtp_instance_get_prop(instance0, AST_RTP_PROPERTY_DTMF) != ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_DTMF)) ||
  5360. (!ast_channel_tech(chan0)->send_digit_begin != !ast_channel_tech(chan1)->send_digit_begin)) ? 0 : 1);
  5361. }
  5362. /*! \pre instance is NOT locked */
  5363. static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username)
  5364. {
  5365. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5366. struct sockaddr_in suggestion_tmp;
  5367. /*
  5368. * The instance should not be locked because we can block
  5369. * waiting for a STUN respone.
  5370. */
  5371. ast_sockaddr_to_sin(suggestion, &suggestion_tmp);
  5372. ast_stun_request(rtp->s, &suggestion_tmp, username, NULL);
  5373. ast_sockaddr_from_sin(suggestion, &suggestion_tmp);
  5374. }
  5375. /*! \pre instance is locked */
  5376. static void ast_rtp_stop(struct ast_rtp_instance *instance)
  5377. {
  5378. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5379. struct ast_sockaddr addr = { {0,} };
  5380. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  5381. ao2_unlock(instance);
  5382. AST_SCHED_DEL_UNREF(rtp->sched, rtp->rekeyid, ao2_ref(instance, -1));
  5383. dtls_srtp_stop_timeout_timer(instance, rtp, 0);
  5384. if (rtp->rtcp) {
  5385. dtls_srtp_stop_timeout_timer(instance, rtp, 1);
  5386. }
  5387. ao2_lock(instance);
  5388. #endif
  5389. if (rtp->rtcp && rtp->rtcp->schedid > -1) {
  5390. ao2_unlock(instance);
  5391. if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
  5392. /* successfully cancelled scheduler entry. */
  5393. ao2_ref(instance, -1);
  5394. }
  5395. ao2_lock(instance);
  5396. rtp->rtcp->schedid = -1;
  5397. }
  5398. if (rtp->red) {
  5399. ao2_unlock(instance);
  5400. AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
  5401. ao2_lock(instance);
  5402. ast_free(rtp->red);
  5403. rtp->red = NULL;
  5404. }
  5405. ast_rtp_instance_set_remote_address(instance, &addr);
  5406. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  5407. }
  5408. /*! \pre instance is locked */
  5409. static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
  5410. {
  5411. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5412. return ast_set_qos(rtp->s, tos, cos, desc);
  5413. }
  5414. /*!
  5415. * \brief generate comfort noice (CNG)
  5416. *
  5417. * \pre instance is locked
  5418. */
  5419. static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level)
  5420. {
  5421. unsigned int *rtpheader;
  5422. int hdrlen = 12;
  5423. int res, payload = 0;
  5424. char data[256];
  5425. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5426. struct ast_sockaddr remote_address = { {0,} };
  5427. int ice;
  5428. ast_rtp_instance_get_remote_address(instance, &remote_address);
  5429. if (ast_sockaddr_isnull(&remote_address)) {
  5430. return -1;
  5431. }
  5432. payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_CN);
  5433. level = 127 - (level & 0x7f);
  5434. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  5435. /* Get a pointer to the header */
  5436. rtpheader = (unsigned int *)data;
  5437. rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
  5438. rtpheader[1] = htonl(rtp->lastts);
  5439. rtpheader[2] = htonl(rtp->ssrc);
  5440. data[12] = level;
  5441. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 1, 0, &remote_address, &ice);
  5442. if (res < 0) {
  5443. ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s: %s\n", ast_sockaddr_stringify(&remote_address), strerror(errno));
  5444. return res;
  5445. }
  5446. if (rtp_debug_test_addr(&remote_address)) {
  5447. ast_verbose("Sent Comfort Noise RTP packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
  5448. ast_sockaddr_stringify(&remote_address),
  5449. ice ? " (via ICE)" : "",
  5450. AST_RTP_CN, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  5451. }
  5452. rtp->seqno++;
  5453. return res;
  5454. }
  5455. #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
  5456. static void dtls_perform_setup(struct dtls_details *dtls)
  5457. {
  5458. if (!dtls->ssl || !SSL_is_init_finished(dtls->ssl)) {
  5459. return;
  5460. }
  5461. SSL_clear(dtls->ssl);
  5462. if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
  5463. SSL_set_accept_state(dtls->ssl);
  5464. } else {
  5465. SSL_set_connect_state(dtls->ssl);
  5466. }
  5467. dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
  5468. }
  5469. /*! \pre instance is locked */
  5470. static int ast_rtp_activate(struct ast_rtp_instance *instance)
  5471. {
  5472. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  5473. dtls_perform_setup(&rtp->dtls);
  5474. if (rtp->rtcp) {
  5475. dtls_perform_setup(&rtp->rtcp->dtls);
  5476. }
  5477. /* If ICE negotiation is enabled the DTLS Handshake will be performed upon completion of it */
  5478. #ifdef HAVE_PJPROJECT
  5479. if (rtp->ice) {
  5480. return 0;
  5481. }
  5482. #endif
  5483. dtls_perform_handshake(instance, &rtp->dtls, 0);
  5484. if (rtp->rtcp && rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
  5485. dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
  5486. }
  5487. return 0;
  5488. }
  5489. #endif
  5490. static char *rtp_do_debug_ip(struct ast_cli_args *a)
  5491. {
  5492. char *arg = ast_strdupa(a->argv[4]);
  5493. char *debughost = NULL;
  5494. char *debugport = NULL;
  5495. if (!ast_sockaddr_parse(&rtpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
  5496. ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
  5497. return CLI_FAILURE;
  5498. }
  5499. rtpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
  5500. ast_cli(a->fd, "RTP Debugging Enabled for address: %s\n",
  5501. ast_sockaddr_stringify(&rtpdebugaddr));
  5502. rtpdebug = 1;
  5503. return CLI_SUCCESS;
  5504. }
  5505. static char *rtcp_do_debug_ip(struct ast_cli_args *a)
  5506. {
  5507. char *arg = ast_strdupa(a->argv[4]);
  5508. char *debughost = NULL;
  5509. char *debugport = NULL;
  5510. if (!ast_sockaddr_parse(&rtcpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
  5511. ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
  5512. return CLI_FAILURE;
  5513. }
  5514. rtcpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
  5515. ast_cli(a->fd, "RTCP Debugging Enabled for address: %s\n",
  5516. ast_sockaddr_stringify(&rtcpdebugaddr));
  5517. rtcpdebug = 1;
  5518. return CLI_SUCCESS;
  5519. }
  5520. static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5521. {
  5522. switch (cmd) {
  5523. case CLI_INIT:
  5524. e->command = "rtp set debug {on|off|ip}";
  5525. e->usage =
  5526. "Usage: rtp set debug {on|off|ip host[:port]}\n"
  5527. " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
  5528. " specified, limit the dumped packets to those to and from\n"
  5529. " the specified 'host' with optional port.\n";
  5530. return NULL;
  5531. case CLI_GENERATE:
  5532. return NULL;
  5533. }
  5534. if (a->argc == e->args) { /* set on or off */
  5535. if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
  5536. rtpdebug = 1;
  5537. memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
  5538. ast_cli(a->fd, "RTP Debugging Enabled\n");
  5539. return CLI_SUCCESS;
  5540. } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
  5541. rtpdebug = 0;
  5542. ast_cli(a->fd, "RTP Debugging Disabled\n");
  5543. return CLI_SUCCESS;
  5544. }
  5545. } else if (a->argc == e->args +1) { /* ip */
  5546. return rtp_do_debug_ip(a);
  5547. }
  5548. return CLI_SHOWUSAGE; /* default, failure */
  5549. }
  5550. static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5551. {
  5552. switch (cmd) {
  5553. case CLI_INIT:
  5554. e->command = "rtcp set debug {on|off|ip}";
  5555. e->usage =
  5556. "Usage: rtcp set debug {on|off|ip host[:port]}\n"
  5557. " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
  5558. " specified, limit the dumped packets to those to and from\n"
  5559. " the specified 'host' with optional port.\n";
  5560. return NULL;
  5561. case CLI_GENERATE:
  5562. return NULL;
  5563. }
  5564. if (a->argc == e->args) { /* set on or off */
  5565. if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
  5566. rtcpdebug = 1;
  5567. memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
  5568. ast_cli(a->fd, "RTCP Debugging Enabled\n");
  5569. return CLI_SUCCESS;
  5570. } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
  5571. rtcpdebug = 0;
  5572. ast_cli(a->fd, "RTCP Debugging Disabled\n");
  5573. return CLI_SUCCESS;
  5574. }
  5575. } else if (a->argc == e->args +1) { /* ip */
  5576. return rtcp_do_debug_ip(a);
  5577. }
  5578. return CLI_SHOWUSAGE; /* default, failure */
  5579. }
  5580. static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  5581. {
  5582. switch (cmd) {
  5583. case CLI_INIT:
  5584. e->command = "rtcp set stats {on|off}";
  5585. e->usage =
  5586. "Usage: rtcp set stats {on|off}\n"
  5587. " Enable/Disable dumping of RTCP stats.\n";
  5588. return NULL;
  5589. case CLI_GENERATE:
  5590. return NULL;
  5591. }
  5592. if (a->argc != e->args)
  5593. return CLI_SHOWUSAGE;
  5594. if (!strncasecmp(a->argv[e->args-1], "on", 2))
  5595. rtcpstats = 1;
  5596. else if (!strncasecmp(a->argv[e->args-1], "off", 3))
  5597. rtcpstats = 0;
  5598. else
  5599. return CLI_SHOWUSAGE;
  5600. ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
  5601. return CLI_SUCCESS;
  5602. }
  5603. static struct ast_cli_entry cli_rtp[] = {
  5604. AST_CLI_DEFINE(handle_cli_rtp_set_debug, "Enable/Disable RTP debugging"),
  5605. AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging"),
  5606. AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats"),
  5607. };
  5608. #ifdef HAVE_PJPROJECT
  5609. /*!
  5610. * \internal
  5611. * \brief Clear the configured blacklist.
  5612. * \since 13.16.0
  5613. *
  5614. * \param lock R/W lock protecting the blacklist
  5615. * \param blacklist List to clear
  5616. *
  5617. * \return Nothing
  5618. */
  5619. static void blacklist_clear(ast_rwlock_t *lock, struct ast_ha **blacklist)
  5620. {
  5621. ast_rwlock_wrlock(lock);
  5622. ast_free_ha(*blacklist);
  5623. *blacklist = NULL;
  5624. ast_rwlock_unlock(lock);
  5625. }
  5626. /*!
  5627. * \internal
  5628. * \brief Load the blacklist configuration.
  5629. * \since 13.16.0
  5630. *
  5631. * \param cfg Raw config file options.
  5632. * \param option_name Blacklist option name
  5633. * \param lock R/W lock protecting the blacklist
  5634. * \param blacklist List to load
  5635. *
  5636. * \return Nothing
  5637. */
  5638. static void blacklist_config_load(struct ast_config *cfg, const char *option_name,
  5639. ast_rwlock_t *lock, struct ast_ha **blacklist)
  5640. {
  5641. struct ast_variable *var;
  5642. ast_rwlock_wrlock(lock);
  5643. for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
  5644. if (!strcasecmp(var->name, option_name)) {
  5645. struct ast_ha *na;
  5646. int ha_error = 0;
  5647. na = ast_append_ha("d", var->value, *blacklist, &ha_error);
  5648. if (!na) {
  5649. ast_log(LOG_WARNING, "Invalid %s value: %s\n",
  5650. option_name, var->value);
  5651. } else {
  5652. *blacklist = na;
  5653. }
  5654. if (ha_error) {
  5655. ast_log(LOG_ERROR,
  5656. "Bad %s configuration value line %d: %s\n",
  5657. option_name, var->lineno, var->value);
  5658. }
  5659. }
  5660. }
  5661. ast_rwlock_unlock(lock);
  5662. }
  5663. #endif
  5664. static int rtp_reload(int reload)
  5665. {
  5666. struct ast_config *cfg;
  5667. const char *s;
  5668. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  5669. #ifdef HAVE_PJPROJECT
  5670. struct ast_variable *var;
  5671. struct ast_ice_host_candidate *candidate;
  5672. #endif
  5673. cfg = ast_config_load2("rtp.conf", "rtp", config_flags);
  5674. if (!cfg || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
  5675. return 0;
  5676. }
  5677. #ifdef SO_NO_CHECK
  5678. nochecksums = 0;
  5679. #endif
  5680. rtpstart = DEFAULT_RTP_START;
  5681. rtpend = DEFAULT_RTP_END;
  5682. rtcpinterval = RTCP_DEFAULT_INTERVALMS;
  5683. dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  5684. strictrtp = DEFAULT_STRICT_RTP;
  5685. learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL;
  5686. learning_min_duration = DEFAULT_LEARNING_MIN_DURATION;
  5687. /** This resource is not "reloaded" so much as unloaded and loaded again.
  5688. * In the case of the TURN related variables, the memory referenced by a
  5689. * previously loaded instance *should* have been released when the
  5690. * corresponding pool was destroyed. If at some point in the future this
  5691. * resource were to support ACTUAL live reconfiguration and did NOT release
  5692. * the pool this will cause a small memory leak.
  5693. */
  5694. #ifdef HAVE_PJPROJECT
  5695. icesupport = DEFAULT_ICESUPPORT;
  5696. turnport = DEFAULT_TURN_PORT;
  5697. memset(&stunaddr, 0, sizeof(stunaddr));
  5698. turnaddr = pj_str(NULL);
  5699. turnusername = pj_str(NULL);
  5700. turnpassword = pj_str(NULL);
  5701. host_candidate_overrides_clear();
  5702. blacklist_clear(&ice_blacklist_lock, &ice_blacklist);
  5703. blacklist_clear(&stun_blacklist_lock, &stun_blacklist);
  5704. #endif
  5705. if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
  5706. rtpstart = atoi(s);
  5707. if (rtpstart < MINIMUM_RTP_PORT)
  5708. rtpstart = MINIMUM_RTP_PORT;
  5709. if (rtpstart > MAXIMUM_RTP_PORT)
  5710. rtpstart = MAXIMUM_RTP_PORT;
  5711. }
  5712. if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
  5713. rtpend = atoi(s);
  5714. if (rtpend < MINIMUM_RTP_PORT)
  5715. rtpend = MINIMUM_RTP_PORT;
  5716. if (rtpend > MAXIMUM_RTP_PORT)
  5717. rtpend = MAXIMUM_RTP_PORT;
  5718. }
  5719. if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
  5720. rtcpinterval = atoi(s);
  5721. if (rtcpinterval == 0)
  5722. rtcpinterval = 0; /* Just so we're clear... it's zero */
  5723. if (rtcpinterval < RTCP_MIN_INTERVALMS)
  5724. rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
  5725. if (rtcpinterval > RTCP_MAX_INTERVALMS)
  5726. rtcpinterval = RTCP_MAX_INTERVALMS;
  5727. }
  5728. if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
  5729. #ifdef SO_NO_CHECK
  5730. nochecksums = ast_false(s) ? 1 : 0;
  5731. #else
  5732. if (ast_false(s))
  5733. ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
  5734. #endif
  5735. }
  5736. if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
  5737. dtmftimeout = atoi(s);
  5738. if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
  5739. ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
  5740. dtmftimeout, DEFAULT_DTMF_TIMEOUT);
  5741. dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  5742. };
  5743. }
  5744. if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
  5745. if (ast_true(s)) {
  5746. strictrtp = STRICT_RTP_YES;
  5747. } else if (!strcasecmp(s, "seqno")) {
  5748. strictrtp = STRICT_RTP_SEQNO;
  5749. } else {
  5750. strictrtp = STRICT_RTP_NO;
  5751. }
  5752. }
  5753. if ((s = ast_variable_retrieve(cfg, "general", "probation"))) {
  5754. if ((sscanf(s, "%d", &learning_min_sequential) != 1) || learning_min_sequential <= 1) {
  5755. ast_log(LOG_WARNING, "Value for 'probation' could not be read, using default of '%d' instead\n",
  5756. DEFAULT_LEARNING_MIN_SEQUENTIAL);
  5757. learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL;
  5758. }
  5759. learning_min_duration = CALC_LEARNING_MIN_DURATION(learning_min_sequential);
  5760. }
  5761. #ifdef HAVE_PJPROJECT
  5762. if ((s = ast_variable_retrieve(cfg, "general", "icesupport"))) {
  5763. icesupport = ast_true(s);
  5764. }
  5765. if ((s = ast_variable_retrieve(cfg, "general", "stunaddr"))) {
  5766. stunaddr.sin_port = htons(STANDARD_STUN_PORT);
  5767. if (ast_parse_arg(s, PARSE_INADDR, &stunaddr)) {
  5768. ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", s);
  5769. }
  5770. }
  5771. if ((s = ast_variable_retrieve(cfg, "general", "turnaddr"))) {
  5772. struct sockaddr_in addr;
  5773. addr.sin_port = htons(DEFAULT_TURN_PORT);
  5774. if (ast_parse_arg(s, PARSE_INADDR, &addr)) {
  5775. ast_log(LOG_WARNING, "Invalid TURN server address: %s\n", s);
  5776. } else {
  5777. pj_strdup2_with_null(pool, &turnaddr, ast_inet_ntoa(addr.sin_addr));
  5778. /* ntohs() is not a bug here. The port number is used in host byte order with
  5779. * a pjnat API. */
  5780. turnport = ntohs(addr.sin_port);
  5781. }
  5782. }
  5783. if ((s = ast_variable_retrieve(cfg, "general", "turnusername"))) {
  5784. pj_strdup2_with_null(pool, &turnusername, s);
  5785. }
  5786. if ((s = ast_variable_retrieve(cfg, "general", "turnpassword"))) {
  5787. pj_strdup2_with_null(pool, &turnpassword, s);
  5788. }
  5789. AST_RWLIST_WRLOCK(&host_candidates);
  5790. for (var = ast_variable_browse(cfg, "ice_host_candidates"); var; var = var->next) {
  5791. struct ast_sockaddr local_addr, advertised_addr;
  5792. pj_str_t address;
  5793. ast_sockaddr_setnull(&local_addr);
  5794. ast_sockaddr_setnull(&advertised_addr);
  5795. if (ast_parse_arg(var->name, PARSE_ADDR | PARSE_PORT_IGNORE, &local_addr)) {
  5796. ast_log(LOG_WARNING, "Invalid local ICE host address: %s\n", var->name);
  5797. continue;
  5798. }
  5799. if (ast_parse_arg(var->value, PARSE_ADDR | PARSE_PORT_IGNORE, &advertised_addr)) {
  5800. ast_log(LOG_WARNING, "Invalid advertised ICE host address: %s\n", var->value);
  5801. continue;
  5802. }
  5803. if (!(candidate = ast_calloc(1, sizeof(*candidate)))) {
  5804. ast_log(LOG_ERROR, "Failed to allocate ICE host candidate mapping.\n");
  5805. break;
  5806. }
  5807. pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&local_addr)), &candidate->local);
  5808. pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&advertised_addr)), &candidate->advertised);
  5809. AST_RWLIST_INSERT_TAIL(&host_candidates, candidate, next);
  5810. }
  5811. AST_RWLIST_UNLOCK(&host_candidates);
  5812. /* Read ICE blacklist configuration lines */
  5813. blacklist_config_load(cfg, "ice_blacklist", &ice_blacklist_lock, &ice_blacklist);
  5814. /* Read STUN blacklist configuration lines */
  5815. blacklist_config_load(cfg, "stun_blacklist", &stun_blacklist_lock, &stun_blacklist);
  5816. #endif
  5817. ast_config_destroy(cfg);
  5818. if (rtpstart >= rtpend) {
  5819. ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
  5820. rtpstart = DEFAULT_RTP_START;
  5821. rtpend = DEFAULT_RTP_END;
  5822. }
  5823. ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
  5824. return 0;
  5825. }
  5826. static int reload_module(void)
  5827. {
  5828. rtp_reload(1);
  5829. return 0;
  5830. }
  5831. #ifdef HAVE_PJPROJECT
  5832. static void rtp_terminate_pjproject(void)
  5833. {
  5834. pj_thread_register_check();
  5835. if (timer_thread) {
  5836. timer_terminate = 1;
  5837. pj_thread_join(timer_thread);
  5838. pj_thread_destroy(timer_thread);
  5839. }
  5840. ast_pjproject_caching_pool_destroy(&cachingpool);
  5841. pj_shutdown();
  5842. }
  5843. #endif
  5844. static int load_module(void)
  5845. {
  5846. #ifdef HAVE_PJPROJECT
  5847. pj_lock_t *lock;
  5848. AST_PJPROJECT_INIT_LOG_LEVEL();
  5849. if (pj_init() != PJ_SUCCESS) {
  5850. return AST_MODULE_LOAD_DECLINE;
  5851. }
  5852. if (pjlib_util_init() != PJ_SUCCESS) {
  5853. rtp_terminate_pjproject();
  5854. return AST_MODULE_LOAD_DECLINE;
  5855. }
  5856. if (pjnath_init() != PJ_SUCCESS) {
  5857. rtp_terminate_pjproject();
  5858. return AST_MODULE_LOAD_DECLINE;
  5859. }
  5860. ast_pjproject_caching_pool_init(&cachingpool, &pj_pool_factory_default_policy, 0);
  5861. pool = pj_pool_create(&cachingpool.factory, "timer", 512, 512, NULL);
  5862. if (pj_timer_heap_create(pool, 100, &timer_heap) != PJ_SUCCESS) {
  5863. rtp_terminate_pjproject();
  5864. return AST_MODULE_LOAD_DECLINE;
  5865. }
  5866. if (pj_lock_create_recursive_mutex(pool, "rtp%p", &lock) != PJ_SUCCESS) {
  5867. rtp_terminate_pjproject();
  5868. return AST_MODULE_LOAD_DECLINE;
  5869. }
  5870. pj_timer_heap_set_lock(timer_heap, lock, PJ_TRUE);
  5871. if (pj_thread_create(pool, "timer", &timer_worker_thread, NULL, 0, 0, &timer_thread) != PJ_SUCCESS) {
  5872. rtp_terminate_pjproject();
  5873. return AST_MODULE_LOAD_DECLINE;
  5874. }
  5875. #endif
  5876. if (ast_rtp_engine_register(&asterisk_rtp_engine)) {
  5877. #ifdef HAVE_PJPROJECT
  5878. rtp_terminate_pjproject();
  5879. #endif
  5880. return AST_MODULE_LOAD_DECLINE;
  5881. }
  5882. if (ast_cli_register_multiple(cli_rtp, ARRAY_LEN(cli_rtp))) {
  5883. #ifdef HAVE_PJPROJECT
  5884. ast_rtp_engine_unregister(&asterisk_rtp_engine);
  5885. rtp_terminate_pjproject();
  5886. #endif
  5887. return AST_MODULE_LOAD_DECLINE;
  5888. }
  5889. rtp_reload(0);
  5890. return AST_MODULE_LOAD_SUCCESS;
  5891. }
  5892. static int unload_module(void)
  5893. {
  5894. ast_rtp_engine_unregister(&asterisk_rtp_engine);
  5895. ast_cli_unregister_multiple(cli_rtp, ARRAY_LEN(cli_rtp));
  5896. #ifdef HAVE_PJPROJECT
  5897. host_candidate_overrides_clear();
  5898. pj_thread_register_check();
  5899. rtp_terminate_pjproject();
  5900. #endif
  5901. return 0;
  5902. }
  5903. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk RTP Stack",
  5904. .support_level = AST_MODULE_SUPPORT_CORE,
  5905. .load = load_module,
  5906. .unload = unload_module,
  5907. .reload = reload_module,
  5908. .load_pri = AST_MODPRI_CHANNEL_DEPEND,
  5909. );