res_rtp_asterisk.c 175 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368
  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">pjproject</use>
  31. <support_level>core</support_level>
  32. ***/
  33. #include "asterisk.h"
  34. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  35. #include <sys/time.h>
  36. #include <signal.h>
  37. #include <fcntl.h>
  38. #ifdef HAVE_OPENSSL_SRTP
  39. #include <openssl/ssl.h>
  40. #include <openssl/err.h>
  41. #include <openssl/bio.h>
  42. #endif
  43. #ifdef HAVE_PJPROJECT
  44. #include <pjlib.h>
  45. #include <pjlib-util.h>
  46. #include <pjnath.h>
  47. #endif
  48. #include "asterisk/stun.h"
  49. #include "asterisk/pbx.h"
  50. #include "asterisk/frame.h"
  51. #include "asterisk/format_cache.h"
  52. #include "asterisk/channel.h"
  53. #include "asterisk/acl.h"
  54. #include "asterisk/config.h"
  55. #include "asterisk/lock.h"
  56. #include "asterisk/utils.h"
  57. #include "asterisk/cli.h"
  58. #include "asterisk/manager.h"
  59. #include "asterisk/unaligned.h"
  60. #include "asterisk/module.h"
  61. #include "asterisk/rtp_engine.h"
  62. #include "asterisk/smoother.h"
  63. #include "asterisk/test.h"
  64. #define MAX_TIMESTAMP_SKEW 640
  65. #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
  66. #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
  67. #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
  68. #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
  69. #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
  70. #define DEFAULT_RTP_END 31000 /*!< Default maximum port number to end allocating RTP ports at */
  71. #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
  72. #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
  73. #define DEFAULT_TURN_PORT 3478
  74. #define TURN_STATE_WAIT_TIME 2000
  75. #define RTCP_PT_FUR 192
  76. #define RTCP_PT_SR AST_RTP_RTCP_SR
  77. #define RTCP_PT_RR AST_RTP_RTCP_RR
  78. #define RTCP_PT_SDES 202
  79. #define RTCP_PT_BYE 203
  80. #define RTCP_PT_APP 204
  81. /* VP8: RTCP Feedback */
  82. #define RTCP_PT_PSFB 206
  83. #define RTP_MTU 1200
  84. #define DTMF_SAMPLE_RATE_MS 8 /*!< DTMF samples per millisecond */
  85. #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
  86. #define ZFONE_PROFILE_ID 0x505a
  87. #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
  88. #define SRTP_MASTER_KEY_LEN 16
  89. #define SRTP_MASTER_SALT_LEN 14
  90. #define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
  91. enum strict_rtp_state {
  92. STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
  93. STRICT_RTP_LEARN, /*! Accept next packet as source */
  94. STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
  95. };
  96. #define DEFAULT_STRICT_RTP STRICT_RTP_CLOSED
  97. #define DEFAULT_ICESUPPORT 1
  98. extern struct ast_srtp_res *res_srtp;
  99. extern struct ast_srtp_policy_res *res_srtp_policy;
  100. static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  101. static int rtpstart = DEFAULT_RTP_START; /*!< First port for RTP sessions (set in rtp.conf) */
  102. static int rtpend = DEFAULT_RTP_END; /*!< Last port for RTP sessions (set in rtp.conf) */
  103. static int rtpdebug; /*!< Are we debugging? */
  104. static int rtcpdebug; /*!< Are we debugging RTCP? */
  105. static int rtcpstats; /*!< Are we debugging RTCP? */
  106. static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
  107. static struct ast_sockaddr rtpdebugaddr; /*!< Debug packets to/from this host */
  108. static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
  109. static int rtpdebugport; /*< Debug only RTP packets from IP or IP+Port if port is > 0 */
  110. static int rtcpdebugport; /*< Debug only RTCP packets from IP or IP+Port if port is > 0 */
  111. #ifdef SO_NO_CHECK
  112. static int nochecksums;
  113. #endif
  114. 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. */
  115. 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. */
  116. #ifdef HAVE_PJPROJECT
  117. static int icesupport = DEFAULT_ICESUPPORT;
  118. static struct sockaddr_in stunaddr;
  119. static pj_str_t turnaddr;
  120. static int turnport = DEFAULT_TURN_PORT;
  121. static pj_str_t turnusername;
  122. static pj_str_t turnpassword;
  123. /*! \brief Pool factory used by pjlib to allocate memory. */
  124. static pj_caching_pool cachingpool;
  125. /*! \brief Global memory pool for configuration and timers */
  126. static pj_pool_t *pool;
  127. /*! \brief Global timer heap */
  128. static pj_timer_heap_t *timer_heap;
  129. /*! \brief Thread executing the timer heap */
  130. static pj_thread_t *timer_thread;
  131. /*! \brief Used to tell the timer thread to terminate */
  132. static int timer_terminate;
  133. /*! \brief Structure which contains ioqueue thread information */
  134. struct ast_rtp_ioqueue_thread {
  135. /*! \brief Pool used by the thread */
  136. pj_pool_t *pool;
  137. /*! \brief The thread handling the queue and timer heap */
  138. pj_thread_t *thread;
  139. /*! \brief Ioqueue which polls on sockets */
  140. pj_ioqueue_t *ioqueue;
  141. /*! \brief Timer heap for scheduled items */
  142. pj_timer_heap_t *timerheap;
  143. /*! \brief Termination request */
  144. int terminate;
  145. /*! \brief Current number of descriptors being waited on */
  146. unsigned int count;
  147. /*! \brief Linked list information */
  148. AST_LIST_ENTRY(ast_rtp_ioqueue_thread) next;
  149. };
  150. /*! \brief List of ioqueue threads */
  151. static AST_LIST_HEAD_STATIC(ioqueues, ast_rtp_ioqueue_thread);
  152. #endif
  153. #define FLAG_3389_WARNING (1 << 0)
  154. #define FLAG_NAT_ACTIVE (3 << 1)
  155. #define FLAG_NAT_INACTIVE (0 << 1)
  156. #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
  157. #define FLAG_NEED_MARKER_BIT (1 << 3)
  158. #define FLAG_DTMF_COMPENSATE (1 << 4)
  159. #define TRANSPORT_SOCKET_RTP 0
  160. #define TRANSPORT_SOCKET_RTCP 1
  161. #define TRANSPORT_TURN_RTP 2
  162. #define TRANSPORT_TURN_RTCP 3
  163. /*! \brief RTP learning mode tracking information */
  164. struct rtp_learning_info {
  165. int max_seq; /*!< The highest sequence number received */
  166. int packets; /*!< The number of remaining packets before the source is accepted */
  167. };
  168. #ifdef HAVE_OPENSSL_SRTP
  169. struct dtls_details {
  170. SSL *ssl; /*!< SSL session */
  171. BIO *read_bio; /*!< Memory buffer for reading */
  172. BIO *write_bio; /*!< Memory buffer for writing */
  173. enum ast_rtp_dtls_setup dtls_setup; /*!< Current setup state */
  174. enum ast_rtp_dtls_connection connection; /*!< Whether this is a new or existing connection */
  175. };
  176. #endif
  177. /*! \brief RTP session description */
  178. struct ast_rtp {
  179. int s;
  180. struct ast_frame f;
  181. unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
  182. unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
  183. unsigned int themssrc; /*!< Their SSRC */
  184. unsigned int rxssrc;
  185. unsigned int lastts;
  186. unsigned int lastrxts;
  187. unsigned int lastividtimestamp;
  188. unsigned int lastovidtimestamp;
  189. unsigned int lastitexttimestamp;
  190. unsigned int lastotexttimestamp;
  191. unsigned int lasteventseqn;
  192. int lastrxseqno; /*!< Last received sequence number */
  193. unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
  194. unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
  195. unsigned int rxcount; /*!< How many packets have we received? */
  196. unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
  197. unsigned int txcount; /*!< How many packets have we sent? */
  198. unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
  199. unsigned int cycles; /*!< Shifted count of sequence number cycles */
  200. double rxjitter; /*!< Interarrival jitter at the moment in seconds */
  201. double rxtransit; /*!< Relative transit time for previous packet */
  202. struct ast_format *lasttxformat;
  203. struct ast_format *lastrxformat;
  204. int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
  205. int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
  206. int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
  207. /* DTMF Reception Variables */
  208. char resp; /*!< The current digit being processed */
  209. unsigned int last_seqno; /*!< The last known sequence number for any DTMF packet */
  210. unsigned int last_end_timestamp; /*!< The last known timestamp received from an END packet */
  211. unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
  212. unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
  213. unsigned int dtmfsamples;
  214. enum ast_rtp_dtmf_mode dtmfmode; /*!< The current DTMF mode of the RTP stream */
  215. /* DTMF Transmission Variables */
  216. unsigned int lastdigitts;
  217. char sending_digit; /*!< boolean - are we sending digits */
  218. char send_digit; /*!< digit we are sending */
  219. int send_payload;
  220. int send_duration;
  221. unsigned int flags;
  222. struct timeval rxcore;
  223. struct timeval txcore;
  224. double drxcore; /*!< The double representation of the first received packet */
  225. struct timeval lastrx; /*!< timeval when we last received a packet */
  226. struct timeval dtmfmute;
  227. struct ast_smoother *smoother;
  228. int *ioid;
  229. unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
  230. unsigned short rxseqno;
  231. struct ast_sched_context *sched;
  232. struct io_context *io;
  233. void *data;
  234. struct ast_rtcp *rtcp;
  235. struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
  236. enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
  237. struct ast_sockaddr strict_rtp_address; /*!< Remote address information for strict RTP purposes */
  238. /*
  239. * Learning mode values based on pjmedia's probation mode. Many of these values are redundant to the above,
  240. * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
  241. */
  242. struct rtp_learning_info rtp_source_learn; /* Learning mode track for the expected RTP source */
  243. struct rtp_learning_info alt_source_learn; /* Learning mode tracking for a new RTP source after one has been chosen */
  244. struct rtp_red *red;
  245. ast_mutex_t lock; /*!< Lock for synchronization purposes */
  246. ast_cond_t cond; /*!< Condition for signaling */
  247. #ifdef HAVE_PJPROJECT
  248. pj_ice_sess *ice; /*!< ICE session */
  249. pj_turn_sock *turn_rtp; /*!< RTP TURN relay */
  250. pj_turn_sock *turn_rtcp; /*!< RTCP TURN relay */
  251. pj_turn_state_t turn_state; /*!< Current state of the TURN relay session */
  252. unsigned int passthrough:1; /*!< Bit to indicate that the received packet should be passed through */
  253. unsigned int rtp_passthrough:1; /*!< Bit to indicate that TURN RTP should be passed through */
  254. unsigned int rtcp_passthrough:1; /*!< Bit to indicate that TURN RTCP should be passed through */
  255. unsigned int ice_port; /*!< Port that ICE was started with if it was previously started */
  256. struct ast_sockaddr rtp_loop; /*!< Loopback address for forwarding RTP from TURN */
  257. struct ast_sockaddr rtcp_loop; /*!< Loopback address for forwarding RTCP from TURN */
  258. struct ast_rtp_ioqueue_thread *ioqueue; /*!< The ioqueue thread handling us */
  259. char remote_ufrag[256]; /*!< The remote ICE username */
  260. char remote_passwd[256]; /*!< The remote ICE password */
  261. char local_ufrag[256]; /*!< The local ICE username */
  262. char local_passwd[256]; /*!< The local ICE password */
  263. struct ao2_container *ice_local_candidates; /*!< The local ICE candidates */
  264. struct ao2_container *ice_active_remote_candidates; /*!< The remote ICE candidates */
  265. struct ao2_container *ice_proposed_remote_candidates; /*!< Incoming remote ICE candidates for new session */
  266. struct ast_sockaddr ice_original_rtp_addr; /*!< rtp address that ICE started on first session */
  267. #endif
  268. #ifdef HAVE_OPENSSL_SRTP
  269. SSL_CTX *ssl_ctx; /*!< SSL context */
  270. ast_mutex_t dtls_timer_lock; /*!< Lock for synchronization purposes */
  271. enum ast_rtp_dtls_verify dtls_verify; /*!< What to verify */
  272. enum ast_srtp_suite suite; /*!< SRTP crypto suite */
  273. enum ast_rtp_dtls_hash local_hash; /*!< Local hash used for the fingerprint */
  274. char local_fingerprint[160]; /*!< Fingerprint of our certificate */
  275. enum ast_rtp_dtls_hash remote_hash; /*!< Remote hash used for the fingerprint */
  276. unsigned char remote_fingerprint[EVP_MAX_MD_SIZE]; /*!< Fingerprint of the peer certificate */
  277. unsigned int rekey; /*!< Interval at which to renegotiate and rekey */
  278. int rekeyid; /*!< Scheduled item id for rekeying */
  279. int dtlstimerid; /*!< Scheduled item id for DTLS retransmission for RTP */
  280. struct dtls_details dtls; /*!< DTLS state information */
  281. #endif
  282. };
  283. /*!
  284. * \brief Structure defining an RTCP session.
  285. *
  286. * The concept "RTCP session" is not defined in RFC 3550, but since
  287. * this structure is analogous to ast_rtp, which tracks a RTP session,
  288. * it is logical to think of this as a RTCP session.
  289. *
  290. * RTCP packet is defined on page 9 of RFC 3550.
  291. *
  292. */
  293. struct ast_rtcp {
  294. int rtcp_info;
  295. int s; /*!< Socket */
  296. struct ast_sockaddr us; /*!< Socket representation of the local endpoint. */
  297. struct ast_sockaddr them; /*!< Socket representation of the remote endpoint. */
  298. unsigned int soc; /*!< What they told us */
  299. unsigned int spc; /*!< What they told us */
  300. unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
  301. struct timeval rxlsr; /*!< Time when we got their last SR */
  302. struct timeval txlsr; /*!< Time when we sent or last SR*/
  303. unsigned int expected_prior; /*!< no. packets in previous interval */
  304. unsigned int received_prior; /*!< no. packets received in previous interval */
  305. int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
  306. unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
  307. unsigned int sr_count; /*!< number of SRs we've sent */
  308. unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
  309. double accumulated_transit; /*!< accumulated a-dlsr-lsr */
  310. double rtt; /*!< Last reported rtt */
  311. unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
  312. unsigned int reported_lost; /*!< Reported lost packets in their RR */
  313. double reported_maxjitter;
  314. double reported_minjitter;
  315. double reported_normdev_jitter;
  316. double reported_stdev_jitter;
  317. unsigned int reported_jitter_count;
  318. double reported_maxlost;
  319. double reported_minlost;
  320. double reported_normdev_lost;
  321. double reported_stdev_lost;
  322. double rxlost;
  323. double maxrxlost;
  324. double minrxlost;
  325. double normdev_rxlost;
  326. double stdev_rxlost;
  327. unsigned int rxlost_count;
  328. double maxrxjitter;
  329. double minrxjitter;
  330. double normdev_rxjitter;
  331. double stdev_rxjitter;
  332. unsigned int rxjitter_count;
  333. double maxrtt;
  334. double minrtt;
  335. double normdevrtt;
  336. double stdevrtt;
  337. unsigned int rtt_count;
  338. /* VP8: sequence number for the RTCP FIR FCI */
  339. int firseq;
  340. #ifdef HAVE_OPENSSL_SRTP
  341. struct dtls_details dtls; /*!< DTLS state information */
  342. #endif
  343. };
  344. struct rtp_red {
  345. struct ast_frame t140; /*!< Primary data */
  346. struct ast_frame t140red; /*!< Redundant t140*/
  347. unsigned char pt[AST_RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
  348. unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
  349. unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
  350. int num_gen; /*!< Number of generations */
  351. int schedid; /*!< Timer id */
  352. int ti; /*!< How long to buffer data before send */
  353. unsigned char t140red_data[64000];
  354. unsigned char buf_data[64000]; /*!< buffered primary data */
  355. int hdrlen;
  356. long int prev_ts;
  357. };
  358. AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
  359. /* Forward Declarations */
  360. static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
  361. static int ast_rtp_destroy(struct ast_rtp_instance *instance);
  362. static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
  363. static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
  364. static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
  365. static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
  366. static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
  367. static void ast_rtp_update_source(struct ast_rtp_instance *instance);
  368. static void ast_rtp_change_source(struct ast_rtp_instance *instance);
  369. static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
  370. static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
  371. static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
  372. static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
  373. static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
  374. static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
  375. static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
  376. static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
  377. static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
  378. static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
  379. static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
  380. static void ast_rtp_stop(struct ast_rtp_instance *instance);
  381. static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
  382. static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
  383. #ifdef HAVE_OPENSSL_SRTP
  384. static int ast_rtp_activate(struct ast_rtp_instance *instance);
  385. static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
  386. #endif
  387. static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *ice, int use_srtp);
  388. #ifdef HAVE_PJPROJECT
  389. /*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
  390. static void update_address_with_ice_candidate(struct ast_rtp *rtp, enum ast_rtp_ice_component_type component,
  391. struct ast_sockaddr *cand_address)
  392. {
  393. char address[PJ_INET6_ADDRSTRLEN];
  394. if (!rtp->ice || (component < 1) || !rtp->ice->comp[component - 1].valid_check) {
  395. return;
  396. }
  397. ast_sockaddr_parse(cand_address, pj_sockaddr_print(&rtp->ice->comp[component - 1].valid_check->rcand->addr, address, sizeof(address), 0), 0);
  398. ast_sockaddr_set_port(cand_address, pj_sockaddr_get_port(&rtp->ice->comp[component - 1].valid_check->rcand->addr));
  399. }
  400. /*! \brief Destructor for locally created ICE candidates */
  401. static void ast_rtp_ice_candidate_destroy(void *obj)
  402. {
  403. struct ast_rtp_engine_ice_candidate *candidate = obj;
  404. if (candidate->foundation) {
  405. ast_free(candidate->foundation);
  406. }
  407. if (candidate->transport) {
  408. ast_free(candidate->transport);
  409. }
  410. }
  411. static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
  412. {
  413. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  414. if (!ast_strlen_zero(ufrag)) {
  415. ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
  416. }
  417. if (!ast_strlen_zero(password)) {
  418. ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
  419. }
  420. }
  421. static int ice_candidate_cmp(void *obj, void *arg, int flags)
  422. {
  423. struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
  424. if (strcmp(candidate1->foundation, candidate2->foundation) ||
  425. candidate1->id != candidate2->id ||
  426. ast_sockaddr_cmp(&candidate1->address, &candidate2->address) ||
  427. candidate1->type != candidate1->type) {
  428. return 0;
  429. }
  430. return CMP_MATCH | CMP_STOP;
  431. }
  432. static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
  433. {
  434. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  435. struct ast_rtp_engine_ice_candidate *remote_candidate;
  436. /* ICE sessions only support UDP candidates */
  437. if (strcasecmp(candidate->transport, "udp")) {
  438. return;
  439. }
  440. if (!rtp->ice_proposed_remote_candidates &&
  441. !(rtp->ice_proposed_remote_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
  442. return;
  443. }
  444. /* If this is going to exceed the maximum number of ICE candidates don't even add it */
  445. if (ao2_container_count(rtp->ice_proposed_remote_candidates) == PJ_ICE_MAX_CAND) {
  446. return;
  447. }
  448. if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
  449. return;
  450. }
  451. remote_candidate->foundation = ast_strdup(candidate->foundation);
  452. remote_candidate->id = candidate->id;
  453. remote_candidate->transport = ast_strdup(candidate->transport);
  454. remote_candidate->priority = candidate->priority;
  455. ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
  456. ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
  457. remote_candidate->type = candidate->type;
  458. ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
  459. ao2_ref(remote_candidate, -1);
  460. }
  461. AST_THREADSTORAGE(pj_thread_storage);
  462. /*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
  463. static void pj_thread_register_check(void)
  464. {
  465. pj_thread_desc *desc;
  466. pj_thread_t *thread;
  467. if (pj_thread_is_registered() == PJ_TRUE) {
  468. return;
  469. }
  470. desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
  471. if (!desc) {
  472. ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
  473. return;
  474. }
  475. pj_bzero(*desc, sizeof(*desc));
  476. if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
  477. ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
  478. }
  479. return;
  480. }
  481. static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
  482. int port, int replace);
  483. static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
  484. {
  485. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  486. if (!rtp->ice) {
  487. return;
  488. }
  489. pj_thread_register_check();
  490. pj_ice_sess_destroy(rtp->ice);
  491. rtp->ice = NULL;
  492. }
  493. static int ice_reset_session(struct ast_rtp_instance *instance)
  494. {
  495. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  496. pj_ice_sess_role role = rtp->ice->role;
  497. int res;
  498. if (!rtp->ice->is_nominating && !rtp->ice->is_complete) {
  499. return 0;
  500. }
  501. ast_rtp_ice_stop(instance);
  502. res = ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
  503. if (!res) {
  504. /* Preserve the role that the old ICE session used */
  505. pj_ice_sess_change_role(rtp->ice, role);
  506. }
  507. return res;
  508. }
  509. static int ice_candidates_compare(struct ao2_container *left, struct ao2_container *right)
  510. {
  511. struct ao2_iterator i;
  512. struct ast_rtp_engine_ice_candidate *right_candidate;
  513. if (ao2_container_count(left) != ao2_container_count(right)) {
  514. return -1;
  515. }
  516. i = ao2_iterator_init(right, 0);
  517. while ((right_candidate = ao2_iterator_next(&i))) {
  518. struct ast_rtp_engine_ice_candidate *left_candidate = ao2_find(left, right_candidate, OBJ_POINTER);
  519. if (!left_candidate) {
  520. ao2_ref(right_candidate, -1);
  521. ao2_iterator_destroy(&i);
  522. return -1;
  523. }
  524. ao2_ref(left_candidate, -1);
  525. ao2_ref(right_candidate, -1);
  526. }
  527. ao2_iterator_destroy(&i);
  528. return 0;
  529. }
  530. static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
  531. {
  532. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  533. pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
  534. pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
  535. struct ao2_iterator i;
  536. struct ast_rtp_engine_ice_candidate *candidate;
  537. int cand_cnt = 0, has_rtp = 0, has_rtcp = 0;
  538. if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
  539. return;
  540. }
  541. /* Check for equivalence in the lists */
  542. if (rtp->ice_active_remote_candidates &&
  543. !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
  544. ao2_cleanup(rtp->ice_proposed_remote_candidates);
  545. rtp->ice_proposed_remote_candidates = NULL;
  546. return;
  547. }
  548. /* Out with the old, in with the new */
  549. ao2_cleanup(rtp->ice_active_remote_candidates);
  550. rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
  551. rtp->ice_proposed_remote_candidates = NULL;
  552. /* Reset the ICE session. Is this going to work? */
  553. if (ice_reset_session(instance)) {
  554. ast_log(LOG_NOTICE, "Failed to create replacement ICE session\n");
  555. return;
  556. }
  557. pj_thread_register_check();
  558. i = ao2_iterator_init(rtp->ice_active_remote_candidates, 0);
  559. while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
  560. pj_str_t address;
  561. /* there needs to be at least one rtp and rtcp candidate in the list */
  562. has_rtp |= candidate->id == AST_RTP_ICE_COMPONENT_RTP;
  563. has_rtcp |= candidate->id == AST_RTP_ICE_COMPONENT_RTCP;
  564. pj_strdup2(rtp->ice->pool, &candidates[cand_cnt].foundation, candidate->foundation);
  565. candidates[cand_cnt].comp_id = candidate->id;
  566. candidates[cand_cnt].prio = candidate->priority;
  567. pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
  568. if (!ast_sockaddr_isnull(&candidate->relay_address)) {
  569. pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
  570. }
  571. if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
  572. candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
  573. } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
  574. candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
  575. } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
  576. candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
  577. }
  578. if (candidate->id == AST_RTP_ICE_COMPONENT_RTP && rtp->turn_rtp) {
  579. pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
  580. } else if (candidate->id == AST_RTP_ICE_COMPONENT_RTCP && rtp->turn_rtcp) {
  581. pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
  582. }
  583. cand_cnt++;
  584. ao2_ref(candidate, -1);
  585. }
  586. ao2_iterator_destroy(&i);
  587. if (has_rtp && has_rtcp &&
  588. pj_ice_sess_create_check_list(rtp->ice, &ufrag, &passwd, ao2_container_count(
  589. rtp->ice_active_remote_candidates), &candidates[0]) == PJ_SUCCESS) {
  590. ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: SUCCESS");
  591. pj_ice_sess_start_check(rtp->ice);
  592. pj_timer_heap_poll(timer_heap, NULL);
  593. rtp->strict_rtp_state = STRICT_RTP_OPEN;
  594. return;
  595. }
  596. ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: FAILURE");
  597. /* even though create check list failed don't stop ice as
  598. it might still work */
  599. ast_debug(1, "Failed to create ICE session check list\n");
  600. /* however we do need to reset remote candidates since
  601. this function may be re-entered */
  602. ao2_ref(rtp->ice_active_remote_candidates, -1);
  603. rtp->ice_active_remote_candidates = NULL;
  604. rtp->ice->rcand_cnt = rtp->ice->clist.count = 0;
  605. }
  606. static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
  607. {
  608. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  609. return rtp->local_ufrag;
  610. }
  611. static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
  612. {
  613. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  614. return rtp->local_passwd;
  615. }
  616. static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
  617. {
  618. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  619. if (rtp->ice_local_candidates) {
  620. ao2_ref(rtp->ice_local_candidates, +1);
  621. }
  622. return rtp->ice_local_candidates;
  623. }
  624. static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
  625. {
  626. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  627. if (!rtp->ice) {
  628. return;
  629. }
  630. pj_thread_register_check();
  631. pj_ice_sess_change_role(rtp->ice, PJ_ICE_SESS_ROLE_CONTROLLING);
  632. }
  633. static void ast_rtp_ice_set_role(struct ast_rtp_instance *instance, enum ast_rtp_ice_role role)
  634. {
  635. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  636. if (!rtp->ice) {
  637. return;
  638. }
  639. pj_thread_register_check();
  640. pj_ice_sess_change_role(rtp->ice, role == AST_RTP_ICE_ROLE_CONTROLLED ?
  641. PJ_ICE_SESS_ROLE_CONTROLLED : PJ_ICE_SESS_ROLE_CONTROLLING);
  642. }
  643. static void ast_rtp_ice_add_cand(struct ast_rtp *rtp, unsigned comp_id, unsigned transport_id, pj_ice_cand_type type, pj_uint16_t local_pref,
  644. const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr, int addr_len)
  645. {
  646. pj_str_t foundation;
  647. struct ast_rtp_engine_ice_candidate *candidate, *existing;
  648. char address[PJ_INET6_ADDRSTRLEN];
  649. pj_thread_register_check();
  650. pj_ice_calc_foundation(rtp->ice->pool, &foundation, type, addr);
  651. if (!rtp->ice_local_candidates && !(rtp->ice_local_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
  652. return;
  653. }
  654. if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
  655. return;
  656. }
  657. candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
  658. candidate->id = comp_id;
  659. candidate->transport = ast_strdup("UDP");
  660. ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
  661. ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
  662. if (rel_addr) {
  663. ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
  664. ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
  665. }
  666. if (type == PJ_ICE_CAND_TYPE_HOST) {
  667. candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
  668. } else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
  669. candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
  670. } else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
  671. candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
  672. }
  673. if ((existing = ao2_find(rtp->ice_local_candidates, candidate, OBJ_POINTER))) {
  674. ao2_ref(existing, -1);
  675. ao2_ref(candidate, -1);
  676. return;
  677. }
  678. if (pj_ice_sess_add_cand(rtp->ice, comp_id, transport_id, type, local_pref, &foundation, addr, base_addr, rel_addr, addr_len, NULL) != PJ_SUCCESS) {
  679. ao2_ref(candidate, -1);
  680. return;
  681. }
  682. /* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
  683. candidate->priority = rtp->ice->lcand[rtp->ice->lcand_cnt - 1].prio;
  684. ao2_link(rtp->ice_local_candidates, candidate);
  685. ao2_ref(candidate, -1);
  686. }
  687. 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)
  688. {
  689. struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
  690. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  691. pj_status_t status;
  692. status = pj_ice_sess_on_rx_pkt(rtp->ice, AST_RTP_ICE_COMPONENT_RTP, TRANSPORT_TURN_RTP, pkt, pkt_len, peer_addr,
  693. addr_len);
  694. if (status != PJ_SUCCESS) {
  695. char buf[100];
  696. pj_strerror(status, buf, sizeof(buf));
  697. ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
  698. (int)status, buf);
  699. return;
  700. }
  701. if (!rtp->rtp_passthrough) {
  702. return;
  703. }
  704. rtp->rtp_passthrough = 0;
  705. ast_sendto(rtp->s, pkt, pkt_len, 0, &rtp->rtp_loop);
  706. }
  707. 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)
  708. {
  709. struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
  710. struct ast_rtp *rtp;
  711. /* If this is a leftover from an already notified RTP instance just ignore the state change */
  712. if (!instance) {
  713. return;
  714. }
  715. rtp = ast_rtp_instance_get_data(instance);
  716. /* We store the new state so the other thread can actually handle it */
  717. ast_mutex_lock(&rtp->lock);
  718. rtp->turn_state = new_state;
  719. ast_cond_signal(&rtp->cond);
  720. if (new_state == PJ_TURN_STATE_DESTROYING) {
  721. pj_turn_sock_set_user_data(rtp->turn_rtp, NULL);
  722. rtp->turn_rtp = NULL;
  723. }
  724. ast_mutex_unlock(&rtp->lock);
  725. }
  726. /* RTP TURN Socket interface declaration */
  727. static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
  728. .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
  729. .on_state = ast_rtp_on_turn_rtp_state,
  730. };
  731. 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)
  732. {
  733. struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
  734. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  735. pj_status_t status;
  736. status = pj_ice_sess_on_rx_pkt(rtp->ice, AST_RTP_ICE_COMPONENT_RTCP, TRANSPORT_TURN_RTCP, pkt, pkt_len, peer_addr,
  737. addr_len);
  738. if (status != PJ_SUCCESS) {
  739. char buf[100];
  740. pj_strerror(status, buf, sizeof(buf));
  741. ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
  742. (int)status, buf);
  743. return;
  744. }
  745. if (!rtp->rtcp_passthrough) {
  746. return;
  747. }
  748. rtp->rtcp_passthrough = 0;
  749. ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp_loop);
  750. }
  751. 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)
  752. {
  753. struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
  754. struct ast_rtp *rtp = NULL;
  755. /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
  756. if (!instance) {
  757. return;
  758. }
  759. rtp = ast_rtp_instance_get_data(instance);
  760. /* We store the new state so the other thread can actually handle it */
  761. ast_mutex_lock(&rtp->lock);
  762. rtp->turn_state = new_state;
  763. ast_cond_signal(&rtp->cond);
  764. if (new_state == PJ_TURN_STATE_DESTROYING) {
  765. pj_turn_sock_set_user_data(rtp->turn_rtcp, NULL);
  766. rtp->turn_rtcp = NULL;
  767. }
  768. ast_mutex_unlock(&rtp->lock);
  769. }
  770. /* RTCP TURN Socket interface declaration */
  771. static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
  772. .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
  773. .on_state = ast_rtp_on_turn_rtcp_state,
  774. };
  775. /*! \brief Worker thread for ioqueue and timerheap */
  776. static int ioqueue_worker_thread(void *data)
  777. {
  778. struct ast_rtp_ioqueue_thread *ioqueue = data;
  779. while (!ioqueue->terminate) {
  780. const pj_time_val delay = {0, 10};
  781. pj_ioqueue_poll(ioqueue->ioqueue, &delay);
  782. pj_timer_heap_poll(ioqueue->timerheap, NULL);
  783. }
  784. return 0;
  785. }
  786. /*! \brief Destroyer for ioqueue thread */
  787. static void rtp_ioqueue_thread_destroy(struct ast_rtp_ioqueue_thread *ioqueue)
  788. {
  789. if (ioqueue->thread) {
  790. ioqueue->terminate = 1;
  791. pj_thread_join(ioqueue->thread);
  792. pj_thread_destroy(ioqueue->thread);
  793. }
  794. pj_pool_release(ioqueue->pool);
  795. ast_free(ioqueue);
  796. }
  797. /*! \brief Removal function for ioqueue thread, determines if it should be terminated and destroyed */
  798. static void rtp_ioqueue_thread_remove(struct ast_rtp_ioqueue_thread *ioqueue)
  799. {
  800. int destroy = 0;
  801. /* If nothing is using this ioqueue thread destroy it */
  802. AST_LIST_LOCK(&ioqueues);
  803. if ((ioqueue->count - 2) == 0) {
  804. destroy = 1;
  805. AST_LIST_REMOVE(&ioqueues, ioqueue, next);
  806. }
  807. AST_LIST_UNLOCK(&ioqueues);
  808. if (!destroy) {
  809. return;
  810. }
  811. rtp_ioqueue_thread_destroy(ioqueue);
  812. }
  813. /*! \brief Finder and allocator for an ioqueue thread */
  814. static struct ast_rtp_ioqueue_thread *rtp_ioqueue_thread_get_or_create(void)
  815. {
  816. struct ast_rtp_ioqueue_thread *ioqueue;
  817. pj_lock_t *lock;
  818. AST_LIST_LOCK(&ioqueues);
  819. /* See if an ioqueue thread exists that can handle more */
  820. AST_LIST_TRAVERSE(&ioqueues, ioqueue, next) {
  821. if ((ioqueue->count + 2) < PJ_IOQUEUE_MAX_HANDLES) {
  822. break;
  823. }
  824. }
  825. /* If we found one bump it up and return it */
  826. if (ioqueue) {
  827. ioqueue->count += 2;
  828. goto end;
  829. }
  830. ioqueue = ast_calloc(1, sizeof(*ioqueue));
  831. if (!ioqueue) {
  832. goto end;
  833. }
  834. ioqueue->pool = pj_pool_create(&cachingpool.factory, "rtp", 512, 512, NULL);
  835. /* We use a timer on the ioqueue thread for TURN so that two threads aren't operating
  836. * on a session at the same time
  837. */
  838. if (pj_timer_heap_create(ioqueue->pool, 4, &ioqueue->timerheap) != PJ_SUCCESS) {
  839. goto fatal;
  840. }
  841. if (pj_lock_create_recursive_mutex(ioqueue->pool, "rtp%p", &lock) != PJ_SUCCESS) {
  842. goto fatal;
  843. }
  844. pj_timer_heap_set_lock(ioqueue->timerheap, lock, PJ_TRUE);
  845. if (pj_ioqueue_create(ioqueue->pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue->ioqueue) != PJ_SUCCESS) {
  846. goto fatal;
  847. }
  848. if (pj_thread_create(ioqueue->pool, "ice", &ioqueue_worker_thread, ioqueue, 0, 0, &ioqueue->thread) != PJ_SUCCESS) {
  849. goto fatal;
  850. }
  851. AST_LIST_INSERT_HEAD(&ioqueues, ioqueue, next);
  852. /* Since this is being returned to an active session the count always starts at 2 */
  853. ioqueue->count = 2;
  854. goto end;
  855. fatal:
  856. rtp_ioqueue_thread_destroy(ioqueue);
  857. ioqueue = NULL;
  858. end:
  859. AST_LIST_UNLOCK(&ioqueues);
  860. return ioqueue;
  861. }
  862. static void ast_rtp_ice_turn_request(struct ast_rtp_instance *instance, enum ast_rtp_ice_component_type component,
  863. enum ast_transport transport, const char *server, unsigned int port, const char *username, const char *password)
  864. {
  865. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  866. pj_turn_sock **turn_sock;
  867. const pj_turn_sock_cb *turn_cb;
  868. pj_turn_tp_type conn_type;
  869. int conn_transport;
  870. pj_stun_auth_cred cred = { 0, };
  871. pj_str_t turn_addr;
  872. struct ast_sockaddr addr = { { 0, } };
  873. pj_stun_config stun_config;
  874. struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
  875. struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
  876. pj_turn_session_info info;
  877. struct ast_sockaddr local, loop;
  878. ast_rtp_instance_get_local_address(instance, &local);
  879. if (ast_sockaddr_is_ipv4(&local)) {
  880. ast_sockaddr_parse(&loop, "127.0.0.1", PARSE_PORT_FORBID);
  881. } else {
  882. ast_sockaddr_parse(&loop, "::1", PARSE_PORT_FORBID);
  883. }
  884. /* Determine what component we are requesting a TURN session for */
  885. if (component == AST_RTP_ICE_COMPONENT_RTP) {
  886. turn_sock = &rtp->turn_rtp;
  887. turn_cb = &ast_rtp_turn_rtp_sock_cb;
  888. conn_transport = TRANSPORT_TURN_RTP;
  889. ast_sockaddr_set_port(&loop, ast_sockaddr_port(&local));
  890. } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
  891. turn_sock = &rtp->turn_rtcp;
  892. turn_cb = &ast_rtp_turn_rtcp_sock_cb;
  893. conn_transport = TRANSPORT_TURN_RTCP;
  894. ast_sockaddr_set_port(&loop, ast_sockaddr_port(&rtp->rtcp->us));
  895. } else {
  896. return;
  897. }
  898. if (transport == AST_TRANSPORT_UDP) {
  899. conn_type = PJ_TURN_TP_UDP;
  900. } else if (transport == AST_TRANSPORT_TCP) {
  901. conn_type = PJ_TURN_TP_TCP;
  902. } else {
  903. ast_assert(0);
  904. return;
  905. }
  906. ast_sockaddr_parse(&addr, server, PARSE_PORT_FORBID);
  907. ast_mutex_lock(&rtp->lock);
  908. if (*turn_sock) {
  909. pj_turn_sock_destroy(*turn_sock);
  910. rtp->turn_state = PJ_TURN_STATE_NULL;
  911. while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
  912. ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
  913. }
  914. }
  915. ast_mutex_unlock(&rtp->lock);
  916. if (component == AST_RTP_ICE_COMPONENT_RTP && !rtp->ioqueue) {
  917. rtp->ioqueue = rtp_ioqueue_thread_get_or_create();
  918. if (!rtp->ioqueue) {
  919. return;
  920. }
  921. }
  922. pj_stun_config_init(&stun_config, &cachingpool.factory, 0, rtp->ioqueue->ioqueue, rtp->ioqueue->timerheap);
  923. if (pj_turn_sock_create(&stun_config, ast_sockaddr_is_ipv4(&addr) ? pj_AF_INET() : pj_AF_INET6(), conn_type,
  924. turn_cb, NULL, instance, turn_sock) != PJ_SUCCESS) {
  925. ast_log(LOG_WARNING, "Could not create a TURN client socket\n");
  926. return;
  927. }
  928. cred.type = PJ_STUN_AUTH_CRED_STATIC;
  929. pj_strset2(&cred.data.static_cred.username, (char*)username);
  930. cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
  931. pj_strset2(&cred.data.static_cred.data, (char*)password);
  932. /* Because the TURN socket is asynchronous but we are synchronous we need to wait until it is done */
  933. ast_mutex_lock(&rtp->lock);
  934. pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port, NULL, &cred, NULL);
  935. while (rtp->turn_state < PJ_TURN_STATE_READY) {
  936. ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
  937. }
  938. ast_mutex_unlock(&rtp->lock);
  939. /* If a TURN session was allocated add it as a candidate */
  940. if (rtp->turn_state != PJ_TURN_STATE_READY) {
  941. return;
  942. }
  943. pj_turn_sock_get_info(*turn_sock, &info);
  944. ast_rtp_ice_add_cand(rtp, component, conn_transport, PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr,
  945. &info.relay_addr, &info.mapped_addr, pj_sockaddr_get_len(&info.relay_addr));
  946. if (component == AST_RTP_ICE_COMPONENT_RTP) {
  947. ast_sockaddr_copy(&rtp->rtp_loop, &loop);
  948. } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
  949. ast_sockaddr_copy(&rtp->rtcp_loop, &loop);
  950. }
  951. }
  952. static char *generate_random_string(char *buf, size_t size)
  953. {
  954. long val[4];
  955. int x;
  956. for (x=0; x<4; x++) {
  957. val[x] = ast_random();
  958. }
  959. snprintf(buf, size, "%08lx%08lx%08lx%08lx", (long unsigned)val[0], (long unsigned)val[1], (long unsigned)val[2], (long unsigned)val[3]);
  960. return buf;
  961. }
  962. /* ICE RTP Engine interface declaration */
  963. static struct ast_rtp_engine_ice ast_rtp_ice = {
  964. .set_authentication = ast_rtp_ice_set_authentication,
  965. .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
  966. .start = ast_rtp_ice_start,
  967. .stop = ast_rtp_ice_stop,
  968. .get_ufrag = ast_rtp_ice_get_ufrag,
  969. .get_password = ast_rtp_ice_get_password,
  970. .get_local_candidates = ast_rtp_ice_get_local_candidates,
  971. .ice_lite = ast_rtp_ice_lite,
  972. .set_role = ast_rtp_ice_set_role,
  973. .turn_request = ast_rtp_ice_turn_request,
  974. };
  975. #endif
  976. #ifdef HAVE_OPENSSL_SRTP
  977. static int dtls_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
  978. {
  979. /* We don't want to actually verify the certificate so just accept what they have provided */
  980. return 1;
  981. }
  982. static int dtls_details_initialize(struct dtls_details *dtls, SSL_CTX *ssl_ctx,
  983. enum ast_rtp_dtls_setup setup)
  984. {
  985. dtls->dtls_setup = setup;
  986. if (!(dtls->ssl = SSL_new(ssl_ctx))) {
  987. ast_log(LOG_ERROR, "Failed to allocate memory for SSL\n");
  988. goto error;
  989. }
  990. if (!(dtls->read_bio = BIO_new(BIO_s_mem()))) {
  991. ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic\n");
  992. goto error;
  993. }
  994. BIO_set_mem_eof_return(dtls->read_bio, -1);
  995. if (!(dtls->write_bio = BIO_new(BIO_s_mem()))) {
  996. ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
  997. goto error;
  998. }
  999. BIO_set_mem_eof_return(dtls->write_bio, -1);
  1000. SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
  1001. if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
  1002. SSL_set_accept_state(dtls->ssl);
  1003. } else {
  1004. SSL_set_connect_state(dtls->ssl);
  1005. }
  1006. dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
  1007. return 0;
  1008. error:
  1009. if (dtls->read_bio) {
  1010. BIO_free(dtls->read_bio);
  1011. dtls->read_bio = NULL;
  1012. }
  1013. if (dtls->write_bio) {
  1014. BIO_free(dtls->write_bio);
  1015. dtls->write_bio = NULL;
  1016. }
  1017. if (dtls->ssl) {
  1018. SSL_free(dtls->ssl);
  1019. dtls->ssl = NULL;
  1020. }
  1021. return -1;
  1022. }
  1023. static int dtls_setup_rtcp(struct ast_rtp_instance *instance)
  1024. {
  1025. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1026. if (!rtp->ssl_ctx || !rtp->rtcp) {
  1027. return 0;
  1028. }
  1029. return dtls_details_initialize(&rtp->rtcp->dtls, rtp->ssl_ctx, rtp->dtls.dtls_setup);
  1030. }
  1031. static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
  1032. {
  1033. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1034. int res;
  1035. if (!dtls_cfg->enabled) {
  1036. return 0;
  1037. }
  1038. if (!ast_rtp_engine_srtp_is_registered()) {
  1039. return -1;
  1040. }
  1041. if (rtp->ssl_ctx) {
  1042. return 0;
  1043. }
  1044. if (!(rtp->ssl_ctx = SSL_CTX_new(DTLSv1_method()))) {
  1045. return -1;
  1046. }
  1047. rtp->dtls_verify = dtls_cfg->verify;
  1048. SSL_CTX_set_verify(rtp->ssl_ctx, (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) || (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
  1049. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, !(rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
  1050. dtls_verify_callback : NULL);
  1051. if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
  1052. SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
  1053. } else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
  1054. SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
  1055. } else {
  1056. ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
  1057. return -1;
  1058. }
  1059. rtp->local_hash = dtls_cfg->hash;
  1060. if (!ast_strlen_zero(dtls_cfg->certfile)) {
  1061. char *private = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
  1062. BIO *certbio;
  1063. X509 *cert;
  1064. const EVP_MD *type;
  1065. unsigned int size, i;
  1066. unsigned char fingerprint[EVP_MAX_MD_SIZE];
  1067. char *local_fingerprint = rtp->local_fingerprint;
  1068. if (!SSL_CTX_use_certificate_file(rtp->ssl_ctx, dtls_cfg->certfile, SSL_FILETYPE_PEM)) {
  1069. ast_log(LOG_ERROR, "Specified certificate file '%s' for RTP instance '%p' could not be used\n",
  1070. dtls_cfg->certfile, instance);
  1071. return -1;
  1072. }
  1073. if (!SSL_CTX_use_PrivateKey_file(rtp->ssl_ctx, private, SSL_FILETYPE_PEM) ||
  1074. !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
  1075. ast_log(LOG_ERROR, "Specified private key file '%s' for RTP instance '%p' could not be used\n",
  1076. private, instance);
  1077. return -1;
  1078. }
  1079. if (!(certbio = BIO_new(BIO_s_file()))) {
  1080. ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
  1081. instance);
  1082. return -1;
  1083. }
  1084. if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA1) {
  1085. type = EVP_sha1();
  1086. } else if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA256) {
  1087. type = EVP_sha256();
  1088. } else {
  1089. ast_log(LOG_ERROR, "Unsupported fingerprint hash type on RTP instance '%p'\n",
  1090. instance);
  1091. return -1;
  1092. }
  1093. if (!BIO_read_filename(certbio, dtls_cfg->certfile) ||
  1094. !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL)) ||
  1095. !X509_digest(cert, type, fingerprint, &size) ||
  1096. !size) {
  1097. ast_log(LOG_ERROR, "Could not produce fingerprint from certificate '%s' for RTP instance '%p'\n",
  1098. dtls_cfg->certfile, instance);
  1099. BIO_free_all(certbio);
  1100. return -1;
  1101. }
  1102. for (i = 0; i < size; i++) {
  1103. sprintf(local_fingerprint, "%.2X:", (unsigned)fingerprint[i]);
  1104. local_fingerprint += 3;
  1105. }
  1106. *(local_fingerprint-1) = 0;
  1107. BIO_free_all(certbio);
  1108. }
  1109. if (!ast_strlen_zero(dtls_cfg->cipher)) {
  1110. if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
  1111. ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
  1112. dtls_cfg->cipher, instance);
  1113. return -1;
  1114. }
  1115. }
  1116. if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
  1117. if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
  1118. ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
  1119. S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
  1120. return -1;
  1121. }
  1122. }
  1123. rtp->rekey = dtls_cfg->rekey;
  1124. rtp->suite = dtls_cfg->suite;
  1125. res = dtls_details_initialize(&rtp->dtls, rtp->ssl_ctx, dtls_cfg->default_setup);
  1126. if (!res) {
  1127. dtls_setup_rtcp(instance);
  1128. }
  1129. return res;
  1130. }
  1131. static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
  1132. {
  1133. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1134. return !rtp->ssl_ctx ? 0 : 1;
  1135. }
  1136. static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
  1137. {
  1138. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1139. if (rtp->ssl_ctx) {
  1140. SSL_CTX_free(rtp->ssl_ctx);
  1141. rtp->ssl_ctx = NULL;
  1142. }
  1143. if (rtp->dtls.ssl) {
  1144. SSL_free(rtp->dtls.ssl);
  1145. rtp->dtls.ssl = NULL;
  1146. }
  1147. if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
  1148. SSL_free(rtp->rtcp->dtls.ssl);
  1149. rtp->rtcp->dtls.ssl = NULL;
  1150. }
  1151. }
  1152. static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
  1153. {
  1154. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1155. if (SSL_is_init_finished(rtp->dtls.ssl)) {
  1156. SSL_shutdown(rtp->dtls.ssl);
  1157. rtp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
  1158. }
  1159. if (rtp->rtcp && SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
  1160. SSL_shutdown(rtp->rtcp->dtls.ssl);
  1161. rtp->rtcp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
  1162. }
  1163. }
  1164. static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
  1165. {
  1166. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1167. return rtp->dtls.connection;
  1168. }
  1169. static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
  1170. {
  1171. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1172. return rtp->dtls.dtls_setup;
  1173. }
  1174. static void dtls_set_setup(enum ast_rtp_dtls_setup *dtls_setup, enum ast_rtp_dtls_setup setup, SSL *ssl)
  1175. {
  1176. enum ast_rtp_dtls_setup old = *dtls_setup;
  1177. switch (setup) {
  1178. case AST_RTP_DTLS_SETUP_ACTIVE:
  1179. *dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
  1180. break;
  1181. case AST_RTP_DTLS_SETUP_PASSIVE:
  1182. *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
  1183. break;
  1184. case AST_RTP_DTLS_SETUP_ACTPASS:
  1185. /* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
  1186. if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
  1187. *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
  1188. }
  1189. break;
  1190. case AST_RTP_DTLS_SETUP_HOLDCONN:
  1191. *dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
  1192. break;
  1193. default:
  1194. /* This should never occur... if it does exit early as we don't know what state things are in */
  1195. return;
  1196. }
  1197. /* If the setup state did not change we go on as if nothing happened */
  1198. if (old == *dtls_setup) {
  1199. return;
  1200. }
  1201. /* If they don't want us to establish a connection wait until later */
  1202. if (*dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
  1203. return;
  1204. }
  1205. if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
  1206. SSL_set_connect_state(ssl);
  1207. } else if (*dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
  1208. SSL_set_accept_state(ssl);
  1209. } else {
  1210. return;
  1211. }
  1212. }
  1213. static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
  1214. {
  1215. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1216. if (rtp->dtls.ssl) {
  1217. dtls_set_setup(&rtp->dtls.dtls_setup, setup, rtp->dtls.ssl);
  1218. }
  1219. if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
  1220. dtls_set_setup(&rtp->rtcp->dtls.dtls_setup, setup, rtp->rtcp->dtls.ssl);
  1221. }
  1222. }
  1223. static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
  1224. {
  1225. char *tmp = ast_strdupa(fingerprint), *value;
  1226. int pos = 0;
  1227. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1228. if (hash != AST_RTP_DTLS_HASH_SHA1 && hash != AST_RTP_DTLS_HASH_SHA256) {
  1229. return;
  1230. }
  1231. rtp->remote_hash = hash;
  1232. while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
  1233. sscanf(value, "%02x", (unsigned int*)&rtp->remote_fingerprint[pos++]);
  1234. }
  1235. }
  1236. static enum ast_rtp_dtls_hash ast_rtp_dtls_get_fingerprint_hash(struct ast_rtp_instance *instance)
  1237. {
  1238. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1239. return rtp->local_hash;
  1240. }
  1241. static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance)
  1242. {
  1243. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1244. return rtp->local_fingerprint;
  1245. }
  1246. /* DTLS RTP Engine interface declaration */
  1247. static struct ast_rtp_engine_dtls ast_rtp_dtls = {
  1248. .set_configuration = ast_rtp_dtls_set_configuration,
  1249. .active = ast_rtp_dtls_active,
  1250. .stop = ast_rtp_dtls_stop,
  1251. .reset = ast_rtp_dtls_reset,
  1252. .get_connection = ast_rtp_dtls_get_connection,
  1253. .get_setup = ast_rtp_dtls_get_setup,
  1254. .set_setup = ast_rtp_dtls_set_setup,
  1255. .set_fingerprint = ast_rtp_dtls_set_fingerprint,
  1256. .get_fingerprint_hash = ast_rtp_dtls_get_fingerprint_hash,
  1257. .get_fingerprint = ast_rtp_dtls_get_fingerprint,
  1258. };
  1259. #endif
  1260. /* RTP Engine Declaration */
  1261. static struct ast_rtp_engine asterisk_rtp_engine = {
  1262. .name = "asterisk",
  1263. .new = ast_rtp_new,
  1264. .destroy = ast_rtp_destroy,
  1265. .dtmf_begin = ast_rtp_dtmf_begin,
  1266. .dtmf_end = ast_rtp_dtmf_end,
  1267. .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
  1268. .dtmf_mode_set = ast_rtp_dtmf_mode_set,
  1269. .dtmf_mode_get = ast_rtp_dtmf_mode_get,
  1270. .update_source = ast_rtp_update_source,
  1271. .change_source = ast_rtp_change_source,
  1272. .write = ast_rtp_write,
  1273. .read = ast_rtp_read,
  1274. .prop_set = ast_rtp_prop_set,
  1275. .fd = ast_rtp_fd,
  1276. .remote_address_set = ast_rtp_remote_address_set,
  1277. .red_init = rtp_red_init,
  1278. .red_buffer = rtp_red_buffer,
  1279. .local_bridge = ast_rtp_local_bridge,
  1280. .get_stat = ast_rtp_get_stat,
  1281. .dtmf_compatible = ast_rtp_dtmf_compatible,
  1282. .stun_request = ast_rtp_stun_request,
  1283. .stop = ast_rtp_stop,
  1284. .qos = ast_rtp_qos_set,
  1285. .sendcng = ast_rtp_sendcng,
  1286. #ifdef HAVE_PJPROJECT
  1287. .ice = &ast_rtp_ice,
  1288. #endif
  1289. #ifdef HAVE_OPENSSL_SRTP
  1290. .dtls = &ast_rtp_dtls,
  1291. .activate = ast_rtp_activate,
  1292. #endif
  1293. };
  1294. #ifdef HAVE_OPENSSL_SRTP
  1295. static void dtls_perform_handshake(struct ast_rtp_instance *instance, struct dtls_details *dtls, int rtcp)
  1296. {
  1297. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1298. if (!dtls->ssl) {
  1299. return;
  1300. }
  1301. if (SSL_is_init_finished(dtls->ssl)) {
  1302. SSL_clear(dtls->ssl);
  1303. if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
  1304. SSL_set_accept_state(dtls->ssl);
  1305. } else {
  1306. SSL_set_connect_state(dtls->ssl);
  1307. }
  1308. dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
  1309. }
  1310. SSL_do_handshake(dtls->ssl);
  1311. dtls_srtp_check_pending(instance, rtp, rtcp);
  1312. }
  1313. #endif
  1314. #ifdef HAVE_PJPROJECT
  1315. static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq);
  1316. static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
  1317. {
  1318. struct ast_rtp_instance *instance = ice->user_data;
  1319. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1320. if (status == PJ_SUCCESS) {
  1321. struct ast_sockaddr remote_address;
  1322. /* Symmetric RTP must be disabled for the remote address to not get overwritten */
  1323. ast_rtp_instance_set_prop(instance, AST_RTP_PROPERTY_NAT, 0);
  1324. update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
  1325. ast_rtp_instance_set_remote_address(instance, &remote_address);
  1326. if (rtp->rtcp) {
  1327. update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTCP, &rtp->rtcp->them);
  1328. }
  1329. }
  1330. #ifdef HAVE_OPENSSL_SRTP
  1331. dtls_perform_handshake(instance, &rtp->dtls, 0);
  1332. if (rtp->rtcp) {
  1333. dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
  1334. }
  1335. #endif
  1336. if (!strictrtp) {
  1337. return;
  1338. }
  1339. rtp->strict_rtp_state = STRICT_RTP_LEARN;
  1340. rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
  1341. }
  1342. 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)
  1343. {
  1344. struct ast_rtp_instance *instance = ice->user_data;
  1345. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1346. /* 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
  1347. * returns */
  1348. if (transport_id == TRANSPORT_SOCKET_RTP || transport_id == TRANSPORT_SOCKET_RTCP) {
  1349. rtp->passthrough = 1;
  1350. } else if (transport_id == TRANSPORT_TURN_RTP) {
  1351. rtp->rtp_passthrough = 1;
  1352. } else if (transport_id == TRANSPORT_TURN_RTCP) {
  1353. rtp->rtcp_passthrough = 1;
  1354. }
  1355. }
  1356. 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)
  1357. {
  1358. struct ast_rtp_instance *instance = ice->user_data;
  1359. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1360. pj_status_t status = PJ_EINVALIDOP;
  1361. pj_ssize_t _size = (pj_ssize_t)size;
  1362. if (transport_id == TRANSPORT_SOCKET_RTP) {
  1363. /* Traffic is destined to go right out the RTP socket we already have */
  1364. status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
  1365. /* sendto on a connectionless socket should send all the data, or none at all */
  1366. ast_assert(_size == size || status != PJ_SUCCESS);
  1367. } else if (transport_id == TRANSPORT_SOCKET_RTCP) {
  1368. /* Traffic is destined to go right out the RTCP socket we already have */
  1369. if (rtp->rtcp) {
  1370. status = pj_sock_sendto(rtp->rtcp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
  1371. /* sendto on a connectionless socket should send all the data, or none at all */
  1372. ast_assert(_size == size || status != PJ_SUCCESS);
  1373. } else {
  1374. status = PJ_SUCCESS;
  1375. }
  1376. } else if (transport_id == TRANSPORT_TURN_RTP) {
  1377. /* Traffic is going through the RTP TURN relay */
  1378. if (rtp->turn_rtp) {
  1379. status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
  1380. }
  1381. } else if (transport_id == TRANSPORT_TURN_RTCP) {
  1382. /* Traffic is going through the RTCP TURN relay */
  1383. if (rtp->turn_rtcp) {
  1384. status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
  1385. }
  1386. }
  1387. return status;
  1388. }
  1389. /* ICE Session interface declaration */
  1390. static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
  1391. .on_ice_complete = ast_rtp_on_ice_complete,
  1392. .on_rx_data = ast_rtp_on_ice_rx_data,
  1393. .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
  1394. };
  1395. /*! \brief Worker thread for timerheap */
  1396. static int timer_worker_thread(void *data)
  1397. {
  1398. pj_ioqueue_t *ioqueue;
  1399. if (pj_ioqueue_create(pool, 1, &ioqueue) != PJ_SUCCESS) {
  1400. return -1;
  1401. }
  1402. while (!timer_terminate) {
  1403. const pj_time_val delay = {0, 10};
  1404. pj_timer_heap_poll(timer_heap, NULL);
  1405. pj_ioqueue_poll(ioqueue, &delay);
  1406. }
  1407. return 0;
  1408. }
  1409. #endif
  1410. static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
  1411. {
  1412. if (!rtpdebug) {
  1413. return 0;
  1414. }
  1415. if (!ast_sockaddr_isnull(&rtpdebugaddr)) {
  1416. if (rtpdebugport) {
  1417. return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
  1418. } else {
  1419. return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
  1420. }
  1421. }
  1422. return 1;
  1423. }
  1424. static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
  1425. {
  1426. if (!rtcpdebug) {
  1427. return 0;
  1428. }
  1429. if (!ast_sockaddr_isnull(&rtcpdebugaddr)) {
  1430. if (rtcpdebugport) {
  1431. return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
  1432. } else {
  1433. return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
  1434. }
  1435. }
  1436. return 1;
  1437. }
  1438. #ifdef HAVE_OPENSSL_SRTP
  1439. static int dtls_srtp_handle_timeout(const void *data)
  1440. {
  1441. struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
  1442. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1443. if (!rtp)
  1444. {
  1445. return 0;
  1446. }
  1447. ast_mutex_lock(&rtp->dtls_timer_lock);
  1448. if (rtp->dtlstimerid == -1)
  1449. {
  1450. ast_mutex_unlock(&rtp->dtls_timer_lock);
  1451. ao2_ref(instance, -1);
  1452. return 0;
  1453. }
  1454. rtp->dtlstimerid = -1;
  1455. ast_mutex_unlock(&rtp->dtls_timer_lock);
  1456. if (rtp->dtls.ssl && !SSL_is_init_finished(rtp->dtls.ssl)) {
  1457. DTLSv1_handle_timeout(rtp->dtls.ssl);
  1458. }
  1459. dtls_srtp_check_pending(instance, rtp, 0);
  1460. if (rtp->rtcp && rtp->rtcp->dtls.ssl && !SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
  1461. DTLSv1_handle_timeout(rtp->rtcp->dtls.ssl);
  1462. }
  1463. dtls_srtp_check_pending(instance, rtp, 1);
  1464. ao2_ref(instance, -1);
  1465. return 0;
  1466. }
  1467. static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
  1468. {
  1469. struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
  1470. size_t pending;
  1471. struct timeval dtls_timeout; /* timeout on DTLS */
  1472. if (!dtls->ssl || !dtls->write_bio) {
  1473. return;
  1474. }
  1475. pending = BIO_ctrl_pending(dtls->write_bio);
  1476. if (pending > 0) {
  1477. char outgoing[pending];
  1478. size_t out;
  1479. struct ast_sockaddr remote_address = { {0, } };
  1480. int ice;
  1481. if (!rtcp) {
  1482. ast_rtp_instance_get_remote_address(instance, &remote_address);
  1483. } else {
  1484. ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
  1485. }
  1486. /* If we do not yet know an address to send this to defer it until we do */
  1487. if (ast_sockaddr_isnull(&remote_address)) {
  1488. return;
  1489. }
  1490. out = BIO_read(dtls->write_bio, outgoing, sizeof(outgoing));
  1491. /* Stop existing DTLS timer if running */
  1492. ast_mutex_lock(&rtp->dtls_timer_lock);
  1493. if (rtp->dtlstimerid > -1) {
  1494. AST_SCHED_DEL_UNREF(rtp->sched, rtp->dtlstimerid, ao2_ref(instance, -1));
  1495. rtp->dtlstimerid = -1;
  1496. }
  1497. if (DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
  1498. int timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
  1499. ao2_ref(instance, +1);
  1500. if ((rtp->dtlstimerid = ast_sched_add(rtp->sched, timeout, dtls_srtp_handle_timeout, instance)) < 0) {
  1501. ao2_ref(instance, -1);
  1502. ast_log(LOG_WARNING, "scheduling DTLS retransmission for RTP instance [%p] failed.\n", instance);
  1503. }
  1504. }
  1505. ast_mutex_unlock(&rtp->dtls_timer_lock);
  1506. __rtp_sendto(instance, outgoing, out, 0, &remote_address, rtcp, &ice, 0);
  1507. }
  1508. }
  1509. static int dtls_srtp_renegotiate(const void *data)
  1510. {
  1511. struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
  1512. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1513. SSL_renegotiate(rtp->dtls.ssl);
  1514. SSL_do_handshake(rtp->dtls.ssl);
  1515. dtls_srtp_check_pending(instance, rtp, 0);
  1516. if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
  1517. SSL_renegotiate(rtp->rtcp->dtls.ssl);
  1518. SSL_do_handshake(rtp->rtcp->dtls.ssl);
  1519. dtls_srtp_check_pending(instance, rtp, 1);
  1520. }
  1521. rtp->rekeyid = -1;
  1522. ao2_ref(instance, -1);
  1523. return 0;
  1524. }
  1525. static int dtls_srtp_setup(struct ast_rtp *rtp, struct ast_srtp *srtp, struct ast_rtp_instance *instance)
  1526. {
  1527. unsigned char material[SRTP_MASTER_LEN * 2];
  1528. unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
  1529. struct ast_srtp_policy *local_policy, *remote_policy = NULL;
  1530. struct ast_rtp_instance_stats stats = { 0, };
  1531. /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
  1532. if (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) {
  1533. X509 *certificate;
  1534. if (!(certificate = SSL_get_peer_certificate(rtp->dtls.ssl))) {
  1535. ast_log(LOG_WARNING, "No certificate was provided by the peer on RTP instance '%p'\n", instance);
  1536. return -1;
  1537. }
  1538. /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
  1539. if (rtp->remote_fingerprint[0]) {
  1540. const EVP_MD *type;
  1541. unsigned char fingerprint[EVP_MAX_MD_SIZE];
  1542. unsigned int size;
  1543. if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA1) {
  1544. type = EVP_sha1();
  1545. } else if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA256) {
  1546. type = EVP_sha256();
  1547. } else {
  1548. ast_log(LOG_WARNING, "Unsupported fingerprint hash type on RTP instance '%p'\n", instance);
  1549. return -1;
  1550. }
  1551. if (!X509_digest(certificate, type, fingerprint, &size) ||
  1552. !size ||
  1553. memcmp(fingerprint, rtp->remote_fingerprint, size)) {
  1554. X509_free(certificate);
  1555. ast_log(LOG_WARNING, "Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
  1556. instance);
  1557. return -1;
  1558. }
  1559. }
  1560. X509_free(certificate);
  1561. }
  1562. /* Ensure that certificate verification was successful */
  1563. if ((rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) && SSL_get_verify_result(rtp->dtls.ssl) != X509_V_OK) {
  1564. ast_log(LOG_WARNING, "Peer certificate on RTP instance '%p' failed verification test\n",
  1565. instance);
  1566. return -1;
  1567. }
  1568. /* Produce key information and set up SRTP */
  1569. if (!SSL_export_keying_material(rtp->dtls.ssl, material, SRTP_MASTER_LEN * 2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
  1570. ast_log(LOG_WARNING, "Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
  1571. instance);
  1572. return -1;
  1573. }
  1574. /* Whether we are acting as a server or client determines where the keys/salts are */
  1575. if (rtp->dtls.dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
  1576. local_key = material;
  1577. remote_key = local_key + SRTP_MASTER_KEY_LEN;
  1578. local_salt = remote_key + SRTP_MASTER_KEY_LEN;
  1579. remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
  1580. } else {
  1581. remote_key = material;
  1582. local_key = remote_key + SRTP_MASTER_KEY_LEN;
  1583. remote_salt = local_key + SRTP_MASTER_KEY_LEN;
  1584. local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
  1585. }
  1586. if (!(local_policy = res_srtp_policy->alloc())) {
  1587. return -1;
  1588. }
  1589. if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
  1590. ast_log(LOG_WARNING, "Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
  1591. goto error;
  1592. }
  1593. if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
  1594. ast_log(LOG_WARNING, "Could not set suite to '%u' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
  1595. goto error;
  1596. }
  1597. if (ast_rtp_instance_get_stats(instance, &stats, AST_RTP_INSTANCE_STAT_LOCAL_SSRC)) {
  1598. goto error;
  1599. }
  1600. res_srtp_policy->set_ssrc(local_policy, stats.local_ssrc, 0);
  1601. if (!(remote_policy = res_srtp_policy->alloc())) {
  1602. goto error;
  1603. }
  1604. if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
  1605. ast_log(LOG_WARNING, "Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
  1606. goto error;
  1607. }
  1608. if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
  1609. ast_log(LOG_WARNING, "Could not set suite to '%u' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
  1610. goto error;
  1611. }
  1612. res_srtp_policy->set_ssrc(remote_policy, 0, 1);
  1613. if (ast_rtp_instance_add_srtp_policy(instance, remote_policy, local_policy)) {
  1614. ast_log(LOG_WARNING, "Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
  1615. goto error;
  1616. }
  1617. if (rtp->rekey) {
  1618. ao2_ref(instance, +1);
  1619. if ((rtp->rekeyid = ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
  1620. ao2_ref(instance, -1);
  1621. goto error;
  1622. }
  1623. }
  1624. return 0;
  1625. error:
  1626. res_srtp_policy->destroy(local_policy);
  1627. if (remote_policy) {
  1628. res_srtp_policy->destroy(remote_policy);
  1629. }
  1630. return -1;
  1631. }
  1632. #endif
  1633. static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
  1634. {
  1635. int len;
  1636. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1637. struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
  1638. char *in = buf;
  1639. #ifdef HAVE_PJPROJECT
  1640. struct ast_sockaddr *loop = rtcp ? &rtp->rtcp_loop : &rtp->rtp_loop;
  1641. #endif
  1642. if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
  1643. return len;
  1644. }
  1645. #ifdef HAVE_OPENSSL_SRTP
  1646. dtls_srtp_check_pending(instance, rtp, rtcp);
  1647. /* If this is an SSL packet pass it to OpenSSL for processing */
  1648. if ((*in >= 20) && (*in <= 64)) {
  1649. struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
  1650. int res = 0;
  1651. /* If no SSL session actually exists terminate things */
  1652. if (!dtls->ssl) {
  1653. ast_log(LOG_ERROR, "Received SSL traffic on RTP instance '%p' without an SSL session\n",
  1654. instance);
  1655. return -1;
  1656. }
  1657. /* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
  1658. if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
  1659. dtls->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
  1660. SSL_set_accept_state(dtls->ssl);
  1661. }
  1662. dtls_srtp_check_pending(instance, rtp, rtcp);
  1663. BIO_write(dtls->read_bio, buf, len);
  1664. len = SSL_read(dtls->ssl, buf, len);
  1665. if ((len < 0) && (SSL_get_error(dtls->ssl, len) == SSL_ERROR_SSL)) {
  1666. unsigned long error = ERR_get_error();
  1667. ast_log(LOG_ERROR, "DTLS failure occurred on RTP instance '%p' due to reason '%s', terminating\n",
  1668. instance, ERR_reason_error_string(error));
  1669. return -1;
  1670. }
  1671. dtls_srtp_check_pending(instance, rtp, rtcp);
  1672. if (SSL_is_init_finished(dtls->ssl)) {
  1673. /* Any further connections will be existing since this is now established */
  1674. dtls->connection = AST_RTP_DTLS_CONNECTION_EXISTING;
  1675. if (!rtcp) {
  1676. /* Use the keying material to set up key/salt information */
  1677. res = dtls_srtp_setup(rtp, srtp, instance);
  1678. }
  1679. }
  1680. return res;
  1681. }
  1682. #endif
  1683. #ifdef HAVE_PJPROJECT
  1684. if (!ast_sockaddr_isnull(loop) && !ast_sockaddr_cmp(loop, sa)) {
  1685. /* ICE traffic will have been handled in the TURN callback, so skip it but update the address
  1686. * so it reflects the actual source and not the loopback
  1687. */
  1688. if (rtcp) {
  1689. ast_sockaddr_copy(sa, &rtp->rtcp->them);
  1690. } else {
  1691. ast_rtp_instance_get_remote_address(instance, sa);
  1692. }
  1693. } else if (rtp->ice) {
  1694. pj_str_t combined = pj_str(ast_sockaddr_stringify(sa));
  1695. pj_sockaddr address;
  1696. pj_status_t status;
  1697. pj_thread_register_check();
  1698. pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
  1699. status = pj_ice_sess_on_rx_pkt(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP,
  1700. rtcp ? TRANSPORT_SOCKET_RTCP : TRANSPORT_SOCKET_RTP, buf, len, &address,
  1701. pj_sockaddr_get_len(&address));
  1702. if (status != PJ_SUCCESS) {
  1703. char buf[100];
  1704. pj_strerror(status, buf, sizeof(buf));
  1705. ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
  1706. (int)status, buf);
  1707. return -1;
  1708. }
  1709. if (!rtp->passthrough) {
  1710. return 0;
  1711. }
  1712. rtp->passthrough = 0;
  1713. }
  1714. #endif
  1715. if ((*in & 0xC0) && res_srtp && srtp && res_srtp->unprotect(srtp, buf, &len, rtcp) < 0) {
  1716. return -1;
  1717. }
  1718. return len;
  1719. }
  1720. static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
  1721. {
  1722. return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
  1723. }
  1724. static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
  1725. {
  1726. return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
  1727. }
  1728. static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *ice, int use_srtp)
  1729. {
  1730. int len = size;
  1731. void *temp = buf;
  1732. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1733. struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
  1734. *ice = 0;
  1735. if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
  1736. return -1;
  1737. }
  1738. #ifdef HAVE_PJPROJECT
  1739. if (rtp->ice) {
  1740. pj_thread_register_check();
  1741. if (pj_ice_sess_send_data(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP, temp, len) == PJ_SUCCESS) {
  1742. *ice = 1;
  1743. return len;
  1744. }
  1745. }
  1746. #endif
  1747. return ast_sendto(rtcp ? rtp->rtcp->s : rtp->s, temp, len, flags, sa);
  1748. }
  1749. static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
  1750. {
  1751. return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
  1752. }
  1753. static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
  1754. {
  1755. return __rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1);
  1756. }
  1757. static int rtp_get_rate(struct ast_format *format)
  1758. {
  1759. /* For those wondering: due to a fluke in RFC publication, G.722 is advertised
  1760. * as having a sample rate of 8kHz, while implementations must know that its
  1761. * real rate is 16kHz. Seriously.
  1762. */
  1763. return (ast_format_cmp(format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) ? 8000 : (int)ast_format_get_sample_rate(format);
  1764. }
  1765. static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
  1766. {
  1767. unsigned int interval;
  1768. /*! \todo XXX Do a more reasonable calculation on this one
  1769. * Look in RFC 3550 Section A.7 for an example*/
  1770. interval = rtcpinterval;
  1771. return interval;
  1772. }
  1773. /*! \brief Calculate normal deviation */
  1774. static double normdev_compute(double normdev, double sample, unsigned int sample_count)
  1775. {
  1776. normdev = normdev * sample_count + sample;
  1777. sample_count++;
  1778. return normdev / sample_count;
  1779. }
  1780. static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
  1781. {
  1782. /*
  1783. for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
  1784. return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
  1785. 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
  1786. optimized formula
  1787. */
  1788. #define SQUARE(x) ((x) * (x))
  1789. stddev = sample_count * stddev;
  1790. sample_count++;
  1791. return stddev +
  1792. ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
  1793. ( SQUARE(sample - normdev_curent) / sample_count );
  1794. #undef SQUARE
  1795. }
  1796. static int create_new_socket(const char *type, int af)
  1797. {
  1798. int sock = socket(af, SOCK_DGRAM, 0);
  1799. if (sock < 0) {
  1800. if (!type) {
  1801. type = "RTP/RTCP";
  1802. }
  1803. ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
  1804. } else {
  1805. long flags = fcntl(sock, F_GETFL);
  1806. fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  1807. #ifdef SO_NO_CHECK
  1808. if (nochecksums) {
  1809. setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
  1810. }
  1811. #endif
  1812. }
  1813. return sock;
  1814. }
  1815. /*!
  1816. * \internal
  1817. * \brief Initializes sequence values and probation for learning mode.
  1818. * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
  1819. *
  1820. * \param info The learning information to track
  1821. * \param seq sequence number read from the rtp header to initialize the information with
  1822. */
  1823. static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
  1824. {
  1825. info->max_seq = seq - 1;
  1826. info->packets = learning_min_sequential;
  1827. }
  1828. /*!
  1829. * \internal
  1830. * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
  1831. * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
  1832. *
  1833. * \param info Structure tracking the learning progress of some address
  1834. * \param seq sequence number read from the rtp header
  1835. * \retval 0 if probation mode should exit for this address
  1836. * \retval non-zero if probation mode should continue
  1837. */
  1838. static int rtp_learning_rtp_seq_update(struct rtp_learning_info *info, uint16_t seq)
  1839. {
  1840. if (seq == info->max_seq + 1) {
  1841. /* packet is in sequence */
  1842. info->packets--;
  1843. } else {
  1844. /* Sequence discontinuity; reset */
  1845. info->packets = learning_min_sequential - 1;
  1846. }
  1847. info->max_seq = seq;
  1848. return (info->packets == 0);
  1849. }
  1850. #ifdef HAVE_PJPROJECT
  1851. static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component,
  1852. int transport)
  1853. {
  1854. pj_sockaddr address[16];
  1855. unsigned int count = PJ_ARRAY_SIZE(address), pos = 0;
  1856. /* Add all the local interface IP addresses */
  1857. if (ast_sockaddr_is_ipv4(addr)) {
  1858. pj_enum_ip_interface(pj_AF_INET(), &count, address);
  1859. } else if (ast_sockaddr_is_any(addr)) {
  1860. pj_enum_ip_interface(pj_AF_UNSPEC(), &count, address);
  1861. } else {
  1862. pj_enum_ip_interface(pj_AF_INET6(), &count, address);
  1863. }
  1864. for (pos = 0; pos < count; pos++) {
  1865. pj_sockaddr_set_port(&address[pos], port);
  1866. ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_HOST, 65535, &address[pos], &address[pos], NULL,
  1867. pj_sockaddr_get_len(&address[pos]));
  1868. }
  1869. /* If configured to use a STUN server to get our external mapped address do so */
  1870. if (stunaddr.sin_addr.s_addr && ast_sockaddr_is_ipv4(addr) && count) {
  1871. struct sockaddr_in answer;
  1872. if (!ast_stun_request(component == AST_RTP_ICE_COMPONENT_RTCP ? rtp->rtcp->s : rtp->s, &stunaddr, NULL, &answer)) {
  1873. pj_sockaddr base;
  1874. pj_str_t mapped = pj_str(ast_strdupa(ast_inet_ntoa(answer.sin_addr)));
  1875. /* Use the first local host candidate as the base */
  1876. pj_sockaddr_cp(&base, &address[0]);
  1877. pj_sockaddr_init(pj_AF_INET(), &address[0], &mapped, ntohs(answer.sin_port));
  1878. ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_SRFLX, 65535, &address[0], &base,
  1879. &base, pj_sockaddr_get_len(&address[0]));
  1880. }
  1881. }
  1882. /* If configured to use a TURN relay create a session and allocate */
  1883. if (pj_strlen(&turnaddr)) {
  1884. ast_rtp_ice_turn_request(instance, component, AST_TRANSPORT_TCP, pj_strbuf(&turnaddr), turnport,
  1885. pj_strbuf(&turnusername), pj_strbuf(&turnpassword));
  1886. }
  1887. }
  1888. #endif
  1889. /*!
  1890. * \internal
  1891. * \brief Calculates the elapsed time from issue of the first tx packet in an
  1892. * rtp session and a specified time
  1893. *
  1894. * \param rtp pointer to the rtp struct with the transmitted rtp packet
  1895. * \param delivery time of delivery - if NULL or zero value, will be ast_tvnow()
  1896. *
  1897. * \return time elapsed in milliseconds
  1898. */
  1899. static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
  1900. {
  1901. struct timeval t;
  1902. long ms;
  1903. if (ast_tvzero(rtp->txcore)) {
  1904. rtp->txcore = ast_tvnow();
  1905. rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
  1906. }
  1907. t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
  1908. if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
  1909. ms = 0;
  1910. }
  1911. rtp->txcore = t;
  1912. return (unsigned int) ms;
  1913. }
  1914. #ifdef HAVE_PJPROJECT
  1915. /*!
  1916. * \internal
  1917. * \brief Creates an ICE session. Can be used to replace a destroyed ICE session.
  1918. *
  1919. * \param instance RTP instance for which the ICE session is being replaced
  1920. * \param addr ast_sockaddr to use for adding RTP candidates to the ICE session
  1921. * \param port port to use for adding RTP candidates to the ICE session
  1922. * \param replace 0 when creating a new session, 1 when replacing a destroyed session
  1923. *
  1924. * \retval 0 on success
  1925. * \retval -1 on failure
  1926. */
  1927. static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
  1928. int port, int replace)
  1929. {
  1930. pj_stun_config stun_config;
  1931. pj_str_t ufrag, passwd;
  1932. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1933. ao2_cleanup(rtp->ice_local_candidates);
  1934. rtp->ice_local_candidates = NULL;
  1935. pj_thread_register_check();
  1936. pj_stun_config_init(&stun_config, &cachingpool.factory, 0, NULL, timer_heap);
  1937. ufrag = pj_str(rtp->local_ufrag);
  1938. passwd = pj_str(rtp->local_passwd);
  1939. /* Create an ICE session for ICE negotiation */
  1940. if (pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN, 2,
  1941. &ast_rtp_ice_sess_cb, &ufrag, &passwd, NULL, &rtp->ice) == PJ_SUCCESS) {
  1942. /* Make this available for the callbacks */
  1943. rtp->ice->user_data = instance;
  1944. /* Add all of the available candidates to the ICE session */
  1945. rtp_add_candidates_to_ice(instance, rtp, addr, port, AST_RTP_ICE_COMPONENT_RTP,
  1946. TRANSPORT_SOCKET_RTP);
  1947. /* Only add the RTCP candidates to ICE when replacing the session. New sessions
  1948. * handle this in a separate part of the setup phase */
  1949. if (replace && rtp->rtcp) {
  1950. rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us,
  1951. ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP,
  1952. TRANSPORT_SOCKET_RTCP);
  1953. }
  1954. return 0;
  1955. }
  1956. return -1;
  1957. }
  1958. #endif
  1959. static int ast_rtp_new(struct ast_rtp_instance *instance,
  1960. struct ast_sched_context *sched, struct ast_sockaddr *addr,
  1961. void *data)
  1962. {
  1963. struct ast_rtp *rtp = NULL;
  1964. int x, startplace;
  1965. /* Create a new RTP structure to hold all of our data */
  1966. if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
  1967. return -1;
  1968. }
  1969. /* Initialize synchronization aspects */
  1970. ast_mutex_init(&rtp->lock);
  1971. ast_cond_init(&rtp->cond, NULL);
  1972. /* Set default parameters on the newly created RTP structure */
  1973. rtp->ssrc = ast_random();
  1974. rtp->seqno = ast_random() & 0xffff;
  1975. rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
  1976. if (strictrtp) {
  1977. rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
  1978. rtp_learning_seq_init(&rtp->alt_source_learn, (uint16_t)rtp->seqno);
  1979. }
  1980. /* Create a new socket for us to listen on and use */
  1981. if ((rtp->s =
  1982. create_new_socket("RTP",
  1983. ast_sockaddr_is_ipv4(addr) ? AF_INET :
  1984. ast_sockaddr_is_ipv6(addr) ? AF_INET6 : -1)) < 0) {
  1985. ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
  1986. ast_free(rtp);
  1987. return -1;
  1988. }
  1989. /* Now actually find a free RTP port to use */
  1990. x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
  1991. x = x & ~1;
  1992. startplace = x;
  1993. for (;;) {
  1994. ast_sockaddr_set_port(addr, x);
  1995. /* Try to bind, this will tell us whether the port is available or not */
  1996. if (!ast_bind(rtp->s, addr)) {
  1997. ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
  1998. ast_rtp_instance_set_local_address(instance, addr);
  1999. break;
  2000. }
  2001. x += 2;
  2002. if (x > rtpend) {
  2003. x = (rtpstart + 1) & ~1;
  2004. }
  2005. /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
  2006. if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
  2007. ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
  2008. close(rtp->s);
  2009. ast_free(rtp);
  2010. return -1;
  2011. }
  2012. }
  2013. #ifdef HAVE_PJPROJECT
  2014. generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
  2015. generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
  2016. #endif
  2017. ast_rtp_instance_set_data(instance, rtp);
  2018. #ifdef HAVE_PJPROJECT
  2019. /* Create an ICE session for ICE negotiation */
  2020. if (icesupport) {
  2021. if (ice_create(instance, addr, x, 0)) {
  2022. ast_log(LOG_NOTICE, "Failed to start ICE session\n");
  2023. } else {
  2024. rtp->ice_port = x;
  2025. ast_sockaddr_copy(&rtp->ice_original_rtp_addr, addr);
  2026. }
  2027. }
  2028. #endif
  2029. /* Record any information we may need */
  2030. rtp->sched = sched;
  2031. #ifdef HAVE_OPENSSL_SRTP
  2032. rtp->rekeyid = -1;
  2033. rtp->dtlstimerid = -1;
  2034. #endif
  2035. rtp->f.subclass.format = ao2_bump(ast_format_none);
  2036. rtp->lastrxformat = ao2_bump(ast_format_none);
  2037. rtp->lasttxformat = ao2_bump(ast_format_none);
  2038. return 0;
  2039. }
  2040. static int ast_rtp_destroy(struct ast_rtp_instance *instance)
  2041. {
  2042. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2043. #ifdef HAVE_PJPROJECT
  2044. struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
  2045. struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
  2046. #endif
  2047. /* Destroy the smoother that was smoothing out audio if present */
  2048. if (rtp->smoother) {
  2049. ast_smoother_free(rtp->smoother);
  2050. }
  2051. /* Close our own socket so we no longer get packets */
  2052. if (rtp->s > -1) {
  2053. close(rtp->s);
  2054. }
  2055. /* Destroy RTCP if it was being used */
  2056. if (rtp->rtcp) {
  2057. /*
  2058. * It is not possible for there to be an active RTCP scheduler
  2059. * entry at this point since it holds a reference to the
  2060. * RTP instance while it's active.
  2061. */
  2062. close(rtp->rtcp->s);
  2063. #ifdef HAVE_OPENSSL_SRTP
  2064. if (rtp->rtcp->dtls.ssl) {
  2065. SSL_free(rtp->rtcp->dtls.ssl);
  2066. }
  2067. #endif
  2068. ast_free(rtp->rtcp);
  2069. }
  2070. /* Destroy RED if it was being used */
  2071. if (rtp->red) {
  2072. AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
  2073. ast_free(rtp->red);
  2074. }
  2075. #ifdef HAVE_PJPROJECT
  2076. pj_thread_register_check();
  2077. /* Destroy the RTP TURN relay if being used */
  2078. ast_mutex_lock(&rtp->lock);
  2079. if (rtp->turn_rtp) {
  2080. pj_turn_sock_destroy(rtp->turn_rtp);
  2081. rtp->turn_state = PJ_TURN_STATE_NULL;
  2082. while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
  2083. ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
  2084. }
  2085. }
  2086. /* Destroy the RTCP TURN relay if being used */
  2087. if (rtp->turn_rtcp) {
  2088. pj_turn_sock_destroy(rtp->turn_rtcp);
  2089. rtp->turn_state = PJ_TURN_STATE_NULL;
  2090. while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
  2091. ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
  2092. }
  2093. }
  2094. ast_mutex_unlock(&rtp->lock);
  2095. if (rtp->ioqueue) {
  2096. rtp_ioqueue_thread_remove(rtp->ioqueue);
  2097. }
  2098. /* Destroy the ICE session if being used */
  2099. if (rtp->ice) {
  2100. pj_ice_sess_destroy(rtp->ice);
  2101. }
  2102. /* Destroy any candidates */
  2103. if (rtp->ice_local_candidates) {
  2104. ao2_ref(rtp->ice_local_candidates, -1);
  2105. }
  2106. if (rtp->ice_active_remote_candidates) {
  2107. ao2_ref(rtp->ice_active_remote_candidates, -1);
  2108. }
  2109. #endif
  2110. #ifdef HAVE_OPENSSL_SRTP
  2111. /* Destroy the SSL context if present */
  2112. if (rtp->ssl_ctx) {
  2113. SSL_CTX_free(rtp->ssl_ctx);
  2114. }
  2115. /* Destroy the SSL session if present */
  2116. if (rtp->dtls.ssl) {
  2117. SSL_free(rtp->dtls.ssl);
  2118. }
  2119. #endif
  2120. ao2_cleanup(rtp->lasttxformat);
  2121. ao2_cleanup(rtp->lastrxformat);
  2122. ao2_cleanup(rtp->f.subclass.format);
  2123. /* Destroy synchronization items */
  2124. ast_mutex_destroy(&rtp->lock);
  2125. ast_cond_destroy(&rtp->cond);
  2126. /* Finally destroy ourselves */
  2127. ast_free(rtp);
  2128. return 0;
  2129. }
  2130. static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
  2131. {
  2132. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2133. rtp->dtmfmode = dtmf_mode;
  2134. return 0;
  2135. }
  2136. static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
  2137. {
  2138. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2139. return rtp->dtmfmode;
  2140. }
  2141. static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
  2142. {
  2143. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2144. struct ast_sockaddr remote_address = { {0,} };
  2145. int hdrlen = 12, res = 0, i = 0, payload = 101;
  2146. char data[256];
  2147. unsigned int *rtpheader = (unsigned int*)data;
  2148. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2149. /* If we have no remote address information bail out now */
  2150. if (ast_sockaddr_isnull(&remote_address)) {
  2151. return -1;
  2152. }
  2153. /* Convert given digit into what we want to transmit */
  2154. if ((digit <= '9') && (digit >= '0')) {
  2155. digit -= '0';
  2156. } else if (digit == '*') {
  2157. digit = 10;
  2158. } else if (digit == '#') {
  2159. digit = 11;
  2160. } else if ((digit >= 'A') && (digit <= 'D')) {
  2161. digit = digit - 'A' + 12;
  2162. } else if ((digit >= 'a') && (digit <= 'd')) {
  2163. digit = digit - 'a' + 12;
  2164. } else {
  2165. ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
  2166. return -1;
  2167. }
  2168. /* Grab the payload that they expect the RFC2833 packet to be received in */
  2169. payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_DTMF);
  2170. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  2171. rtp->send_duration = 160;
  2172. rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
  2173. rtp->lastdigitts = rtp->lastts + rtp->send_duration;
  2174. /* Create the actual packet that we will be sending */
  2175. rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
  2176. rtpheader[1] = htonl(rtp->lastdigitts);
  2177. rtpheader[2] = htonl(rtp->ssrc);
  2178. /* Actually send the packet */
  2179. for (i = 0; i < 2; i++) {
  2180. int ice;
  2181. rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
  2182. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
  2183. if (res < 0) {
  2184. ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
  2185. ast_sockaddr_stringify(&remote_address),
  2186. strerror(errno));
  2187. }
  2188. if (rtp_debug_test_addr(&remote_address)) {
  2189. ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
  2190. ast_sockaddr_stringify(&remote_address),
  2191. ice ? " (via ICE)" : "",
  2192. payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  2193. }
  2194. rtp->seqno++;
  2195. rtp->send_duration += 160;
  2196. rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
  2197. }
  2198. /* Record that we are in the process of sending a digit and information needed to continue doing so */
  2199. rtp->sending_digit = 1;
  2200. rtp->send_digit = digit;
  2201. rtp->send_payload = payload;
  2202. return 0;
  2203. }
  2204. static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
  2205. {
  2206. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2207. struct ast_sockaddr remote_address = { {0,} };
  2208. int hdrlen = 12, res = 0;
  2209. char data[256];
  2210. unsigned int *rtpheader = (unsigned int*)data;
  2211. int ice;
  2212. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2213. /* Make sure we know where the other side is so we can send them the packet */
  2214. if (ast_sockaddr_isnull(&remote_address)) {
  2215. return -1;
  2216. }
  2217. /* Actually create the packet we will be sending */
  2218. rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
  2219. rtpheader[1] = htonl(rtp->lastdigitts);
  2220. rtpheader[2] = htonl(rtp->ssrc);
  2221. rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
  2222. /* Boom, send it on out */
  2223. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
  2224. if (res < 0) {
  2225. ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
  2226. ast_sockaddr_stringify(&remote_address),
  2227. strerror(errno));
  2228. }
  2229. if (rtp_debug_test_addr(&remote_address)) {
  2230. ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
  2231. ast_sockaddr_stringify(&remote_address),
  2232. ice ? " (via ICE)" : "",
  2233. rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  2234. }
  2235. /* And now we increment some values for the next time we swing by */
  2236. rtp->seqno++;
  2237. rtp->send_duration += 160;
  2238. rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
  2239. return 0;
  2240. }
  2241. static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
  2242. {
  2243. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2244. struct ast_sockaddr remote_address = { {0,} };
  2245. int hdrlen = 12, res = -1, i = 0;
  2246. char data[256];
  2247. unsigned int *rtpheader = (unsigned int*)data;
  2248. unsigned int measured_samples;
  2249. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2250. /* Make sure we know where the remote side is so we can send them the packet we construct */
  2251. if (ast_sockaddr_isnull(&remote_address)) {
  2252. goto cleanup;
  2253. }
  2254. /* Convert the given digit to the one we are going to send */
  2255. if ((digit <= '9') && (digit >= '0')) {
  2256. digit -= '0';
  2257. } else if (digit == '*') {
  2258. digit = 10;
  2259. } else if (digit == '#') {
  2260. digit = 11;
  2261. } else if ((digit >= 'A') && (digit <= 'D')) {
  2262. digit = digit - 'A' + 12;
  2263. } else if ((digit >= 'a') && (digit <= 'd')) {
  2264. digit = digit - 'a' + 12;
  2265. } else {
  2266. ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
  2267. goto cleanup;
  2268. }
  2269. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  2270. if (duration > 0 && (measured_samples = duration * rtp_get_rate(rtp->f.subclass.format) / 1000) > rtp->send_duration) {
  2271. ast_debug(2, "Adjusting final end duration from %d to %u\n", rtp->send_duration, measured_samples);
  2272. rtp->send_duration = measured_samples;
  2273. }
  2274. /* Construct the packet we are going to send */
  2275. rtpheader[1] = htonl(rtp->lastdigitts);
  2276. rtpheader[2] = htonl(rtp->ssrc);
  2277. rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
  2278. rtpheader[3] |= htonl((1 << 23));
  2279. /* Send it 3 times, that's the magical number */
  2280. for (i = 0; i < 3; i++) {
  2281. int ice;
  2282. rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
  2283. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
  2284. if (res < 0) {
  2285. ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
  2286. ast_sockaddr_stringify(&remote_address),
  2287. strerror(errno));
  2288. }
  2289. if (rtp_debug_test_addr(&remote_address)) {
  2290. ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
  2291. ast_sockaddr_stringify(&remote_address),
  2292. ice ? " (via ICE)" : "",
  2293. rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  2294. }
  2295. rtp->seqno++;
  2296. }
  2297. res = 0;
  2298. /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
  2299. rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
  2300. cleanup:
  2301. rtp->sending_digit = 0;
  2302. rtp->send_digit = 0;
  2303. return res;
  2304. }
  2305. static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
  2306. {
  2307. return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
  2308. }
  2309. static void ast_rtp_update_source(struct ast_rtp_instance *instance)
  2310. {
  2311. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2312. /* We simply set this bit so that the next packet sent will have the marker bit turned on */
  2313. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  2314. ast_debug(3, "Setting the marker bit due to a source update\n");
  2315. return;
  2316. }
  2317. static void ast_rtp_change_source(struct ast_rtp_instance *instance)
  2318. {
  2319. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2320. struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
  2321. unsigned int ssrc = ast_random();
  2322. if (!rtp->lastts) {
  2323. ast_debug(3, "Not changing SSRC since we haven't sent any RTP yet\n");
  2324. return;
  2325. }
  2326. /* We simply set this bit so that the next packet sent will have the marker bit turned on */
  2327. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  2328. ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
  2329. if (srtp) {
  2330. ast_debug(3, "Changing ssrc for SRTP from %u to %u\n", rtp->ssrc, ssrc);
  2331. res_srtp->change_source(srtp, rtp->ssrc, ssrc);
  2332. }
  2333. rtp->ssrc = ssrc;
  2334. return;
  2335. }
  2336. static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
  2337. {
  2338. unsigned int sec, usec, frac;
  2339. sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
  2340. usec = tv.tv_usec;
  2341. frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
  2342. *msw = sec;
  2343. *lsw = frac;
  2344. }
  2345. static void ntp2timeval(unsigned int msw, unsigned int lsw, struct timeval *tv)
  2346. {
  2347. tv->tv_sec = msw - 2208988800u;
  2348. tv->tv_usec = ((lsw << 6) / 3650) - (lsw >> 12) - (lsw >> 8);
  2349. }
  2350. static void calculate_lost_packet_statistics(struct ast_rtp *rtp,
  2351. unsigned int *lost_packets,
  2352. int *fraction_lost)
  2353. {
  2354. unsigned int extended_seq_no;
  2355. unsigned int expected_packets;
  2356. unsigned int expected_interval;
  2357. unsigned int received_interval;
  2358. double rxlost_current;
  2359. int lost_interval;
  2360. /* Compute statistics */
  2361. extended_seq_no = rtp->cycles + rtp->lastrxseqno;
  2362. expected_packets = extended_seq_no - rtp->seedrxseqno + 1;
  2363. if (rtp->rxcount > expected_packets) {
  2364. expected_packets += rtp->rxcount - expected_packets;
  2365. }
  2366. *lost_packets = expected_packets - rtp->rxcount;
  2367. expected_interval = expected_packets - rtp->rtcp->expected_prior;
  2368. received_interval = rtp->rxcount - rtp->rtcp->received_prior;
  2369. lost_interval = expected_interval - received_interval;
  2370. if (expected_interval == 0 || lost_interval <= 0) {
  2371. *fraction_lost = 0;
  2372. } else {
  2373. *fraction_lost = (lost_interval << 8) / expected_interval;
  2374. }
  2375. /* Update RTCP statistics */
  2376. rtp->rtcp->received_prior = rtp->rxcount;
  2377. rtp->rtcp->expected_prior = expected_packets;
  2378. if (lost_interval <= 0) {
  2379. rtp->rtcp->rxlost = 0;
  2380. } else {
  2381. rtp->rtcp->rxlost = lost_interval;
  2382. }
  2383. if (rtp->rtcp->rxlost_count == 0) {
  2384. rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
  2385. }
  2386. if (lost_interval < rtp->rtcp->minrxlost) {
  2387. rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
  2388. }
  2389. if (lost_interval > rtp->rtcp->maxrxlost) {
  2390. rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
  2391. }
  2392. rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost,
  2393. rtp->rtcp->rxlost,
  2394. rtp->rtcp->rxlost_count);
  2395. rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost,
  2396. rtp->rtcp->rxlost,
  2397. rtp->rtcp->normdev_rxlost,
  2398. rxlost_current,
  2399. rtp->rtcp->rxlost_count);
  2400. rtp->rtcp->normdev_rxlost = rxlost_current;
  2401. rtp->rtcp->rxlost_count++;
  2402. }
  2403. /*! \brief Send RTCP SR or RR report */
  2404. static int ast_rtcp_write_report(struct ast_rtp_instance *instance, int sr)
  2405. {
  2406. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2407. RAII_VAR(struct ast_json *, message_blob, NULL, ast_json_unref);
  2408. int res;
  2409. int len = 0;
  2410. struct timeval now;
  2411. unsigned int now_lsw;
  2412. unsigned int now_msw;
  2413. unsigned int *rtcpheader;
  2414. unsigned int lost_packets;
  2415. int fraction_lost;
  2416. struct timeval dlsr = { 0, };
  2417. char bdata[512];
  2418. int rate = rtp_get_rate(rtp->f.subclass.format);
  2419. int ice;
  2420. int header_offset = 0;
  2421. char *str_remote_address;
  2422. char *str_local_address;
  2423. struct ast_sockaddr remote_address = { { 0, } };
  2424. struct ast_sockaddr local_address = { { 0, } };
  2425. struct ast_sockaddr real_remote_address = { { 0, } };
  2426. struct ast_sockaddr real_local_address = { { 0, } };
  2427. struct ast_rtp_rtcp_report_block *report_block = NULL;
  2428. RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report,
  2429. ast_rtp_rtcp_report_alloc(rtp->themssrc ? 1 : 0),
  2430. ao2_cleanup);
  2431. if (!rtp || !rtp->rtcp) {
  2432. return 0;
  2433. }
  2434. if (ast_sockaddr_isnull(&rtp->rtcp->them)) { /* This'll stop rtcp for this rtp session */
  2435. /* RTCP was stopped. */
  2436. return 0;
  2437. }
  2438. if (!rtcp_report) {
  2439. return 1;
  2440. }
  2441. /* Compute statistics */
  2442. calculate_lost_packet_statistics(rtp, &lost_packets, &fraction_lost);
  2443. gettimeofday(&now, NULL);
  2444. rtcp_report->reception_report_count = rtp->themssrc ? 1 : 0;
  2445. rtcp_report->ssrc = rtp->ssrc;
  2446. rtcp_report->type = sr ? RTCP_PT_SR : RTCP_PT_RR;
  2447. if (sr) {
  2448. rtcp_report->sender_information.ntp_timestamp = now;
  2449. rtcp_report->sender_information.rtp_timestamp = rtp->lastts;
  2450. rtcp_report->sender_information.packet_count = rtp->txcount;
  2451. rtcp_report->sender_information.octet_count = rtp->txoctetcount;
  2452. }
  2453. if (rtp->themssrc) {
  2454. report_block = ast_calloc(1, sizeof(*report_block));
  2455. if (!report_block) {
  2456. return 1;
  2457. }
  2458. rtcp_report->report_block[0] = report_block;
  2459. report_block->source_ssrc = rtp->themssrc;
  2460. report_block->lost_count.fraction = (fraction_lost & 0xff);
  2461. report_block->lost_count.packets = (lost_packets & 0xffffff);
  2462. report_block->highest_seq_no = (rtp->cycles | (rtp->lastrxseqno & 0xffff));
  2463. report_block->ia_jitter = (unsigned int)(rtp->rxjitter * rate);
  2464. report_block->lsr = rtp->rtcp->themrxlsr;
  2465. /* If we haven't received an SR report, DLSR should be 0 */
  2466. if (!ast_tvzero(rtp->rtcp->rxlsr)) {
  2467. timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
  2468. report_block->dlsr = (((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000;
  2469. }
  2470. }
  2471. timeval2ntp(rtcp_report->sender_information.ntp_timestamp, &now_msw, &now_lsw);
  2472. rtcpheader = (unsigned int *)bdata;
  2473. rtcpheader[1] = htonl(rtcp_report->ssrc); /* Our SSRC */
  2474. len += 8;
  2475. if (sr) {
  2476. header_offset = 5;
  2477. rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
  2478. rtcpheader[3] = htonl(now_lsw); /* now, LSW */
  2479. rtcpheader[4] = htonl(rtcp_report->sender_information.rtp_timestamp);
  2480. rtcpheader[5] = htonl(rtcp_report->sender_information.packet_count);
  2481. rtcpheader[6] = htonl(rtcp_report->sender_information.octet_count);
  2482. len += 20;
  2483. }
  2484. if (report_block) {
  2485. rtcpheader[2 + header_offset] = htonl(report_block->source_ssrc); /* Their SSRC */
  2486. rtcpheader[3 + header_offset] = htonl((report_block->lost_count.fraction << 24) | report_block->lost_count.packets);
  2487. rtcpheader[4 + header_offset] = htonl(report_block->highest_seq_no);
  2488. rtcpheader[5 + header_offset] = htonl(report_block->ia_jitter);
  2489. rtcpheader[6 + header_offset] = htonl(report_block->lsr);
  2490. rtcpheader[7 + header_offset] = htonl(report_block->dlsr);
  2491. len += 24;
  2492. }
  2493. rtcpheader[0] = htonl((2 << 30) | (rtcp_report->reception_report_count << 24)
  2494. | ((sr ? RTCP_PT_SR : RTCP_PT_RR) << 16) | ((len/4)-1));
  2495. /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
  2496. /* it can change mid call, and SDES can't) */
  2497. rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
  2498. rtcpheader[(len/4)+1] = htonl(rtcp_report->ssrc);
  2499. rtcpheader[(len/4)+2] = htonl(0x01 << 24);
  2500. len += 12;
  2501. ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
  2502. res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &remote_address, &ice);
  2503. if (res < 0) {
  2504. ast_log(LOG_ERROR, "RTCP %s transmission error to %s, rtcp halted %s\n",
  2505. sr ? "SR" : "RR",
  2506. ast_sockaddr_stringify(&rtp->rtcp->them),
  2507. strerror(errno));
  2508. return 0;
  2509. }
  2510. /* Update RTCP SR/RR statistics */
  2511. if (sr) {
  2512. rtp->rtcp->txlsr = rtcp_report->sender_information.ntp_timestamp;
  2513. rtp->rtcp->sr_count++;
  2514. rtp->rtcp->lastsrtxcount = rtp->txcount;
  2515. } else {
  2516. rtp->rtcp->rr_count++;
  2517. }
  2518. if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
  2519. ast_verbose("* Sent RTCP %s to %s%s\n", sr ? "SR" : "RR",
  2520. ast_sockaddr_stringify(&remote_address), ice ? " (via ICE)" : "");
  2521. ast_verbose(" Our SSRC: %u\n", rtcp_report->ssrc);
  2522. if (sr) {
  2523. ast_verbose(" Sent(NTP): %u.%010u\n",
  2524. (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
  2525. (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec * 4096);
  2526. ast_verbose(" Sent(RTP): %u\n", rtcp_report->sender_information.rtp_timestamp);
  2527. ast_verbose(" Sent packets: %u\n", rtcp_report->sender_information.packet_count);
  2528. ast_verbose(" Sent octets: %u\n", rtcp_report->sender_information.octet_count);
  2529. }
  2530. ast_verbose(" Report block:\n");
  2531. ast_verbose(" Their SSRC: %u\n", report_block->source_ssrc);
  2532. ast_verbose(" Fraction lost: %d\n", report_block->lost_count.fraction);
  2533. ast_verbose(" Cumulative loss: %u\n", report_block->lost_count.packets);
  2534. ast_verbose(" Highest seq no: %u\n", report_block->highest_seq_no);
  2535. ast_verbose(" IA jitter: %.4f\n", (double)report_block->ia_jitter / rate);
  2536. ast_verbose(" Their last SR: %u\n", report_block->lsr);
  2537. ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(report_block->dlsr / 65536.0));
  2538. }
  2539. ast_rtp_instance_get_local_address(instance, &local_address);
  2540. if (!ast_find_ourip(&real_local_address, &local_address, 0)) {
  2541. str_local_address = ast_strdupa(ast_sockaddr_stringify(&real_local_address));
  2542. } else {
  2543. str_local_address = ast_strdupa(ast_sockaddr_stringify(&local_address));
  2544. }
  2545. if (!ast_find_ourip(&real_remote_address, &remote_address, 0)) {
  2546. str_remote_address = ast_strdupa(ast_sockaddr_stringify(&real_remote_address));
  2547. } else {
  2548. str_remote_address = ast_strdupa(ast_sockaddr_stringify(&remote_address));
  2549. }
  2550. message_blob = ast_json_pack("{s: s, s: s}",
  2551. "to", str_remote_address,
  2552. "from", str_local_address);
  2553. ast_rtp_publish_rtcp_message(instance, ast_rtp_rtcp_sent_type(),
  2554. rtcp_report,
  2555. message_blob);
  2556. return res;
  2557. }
  2558. /*! \brief Write and RTCP packet to the far end
  2559. * \note Decide if we are going to send an SR (with Reception Block) or RR
  2560. * RR is sent if we have not sent any rtp packets in the previous interval */
  2561. static int ast_rtcp_write(const void *data)
  2562. {
  2563. struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
  2564. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2565. int res;
  2566. if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
  2567. ao2_ref(instance, -1);
  2568. return 0;
  2569. }
  2570. if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
  2571. /* Send an SR */
  2572. res = ast_rtcp_write_report(instance, 1);
  2573. } else {
  2574. /* Send an RR */
  2575. res = ast_rtcp_write_report(instance, 0);
  2576. }
  2577. if (!res) {
  2578. /*
  2579. * Not being rescheduled.
  2580. */
  2581. ao2_ref(instance, -1);
  2582. rtp->rtcp->schedid = -1;
  2583. }
  2584. return res;
  2585. }
  2586. static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
  2587. {
  2588. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2589. int pred, mark = 0;
  2590. unsigned int ms = calc_txstamp(rtp, &frame->delivery);
  2591. struct ast_sockaddr remote_address = { {0,} };
  2592. int rate = rtp_get_rate(frame->subclass.format) / 1000;
  2593. if (ast_format_cmp(frame->subclass.format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) {
  2594. frame->samples /= 2;
  2595. }
  2596. if (rtp->sending_digit) {
  2597. return 0;
  2598. }
  2599. if (frame->frametype == AST_FRAME_VOICE) {
  2600. pred = rtp->lastts + frame->samples;
  2601. /* Re-calculate last TS */
  2602. rtp->lastts = rtp->lastts + ms * rate;
  2603. if (ast_tvzero(frame->delivery)) {
  2604. /* If this isn't an absolute delivery time, Check if it is close to our prediction,
  2605. and if so, go with our prediction */
  2606. if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
  2607. rtp->lastts = pred;
  2608. } else {
  2609. ast_debug(3, "Difference is %d, ms is %u\n", abs(rtp->lastts - pred), ms);
  2610. mark = 1;
  2611. }
  2612. }
  2613. } else if (frame->frametype == AST_FRAME_VIDEO) {
  2614. mark = frame->subclass.frame_ending;
  2615. pred = rtp->lastovidtimestamp + frame->samples;
  2616. /* Re-calculate last TS */
  2617. rtp->lastts = rtp->lastts + ms * 90;
  2618. /* If it's close to our prediction, go for it */
  2619. if (ast_tvzero(frame->delivery)) {
  2620. if (abs(rtp->lastts - pred) < 7200) {
  2621. rtp->lastts = pred;
  2622. rtp->lastovidtimestamp += frame->samples;
  2623. } else {
  2624. ast_debug(3, "Difference is %d, ms is %u (%u), pred/ts/samples %u/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
  2625. rtp->lastovidtimestamp = rtp->lastts;
  2626. }
  2627. }
  2628. } else {
  2629. pred = rtp->lastotexttimestamp + frame->samples;
  2630. /* Re-calculate last TS */
  2631. rtp->lastts = rtp->lastts + ms;
  2632. /* If it's close to our prediction, go for it */
  2633. if (ast_tvzero(frame->delivery)) {
  2634. if (abs(rtp->lastts - pred) < 7200) {
  2635. rtp->lastts = pred;
  2636. rtp->lastotexttimestamp += frame->samples;
  2637. } else {
  2638. ast_debug(3, "Difference is %d, ms is %u, pred/ts/samples %u/%d/%d\n", abs(rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
  2639. rtp->lastotexttimestamp = rtp->lastts;
  2640. }
  2641. }
  2642. }
  2643. /* If we have been explicitly told to set the marker bit then do so */
  2644. if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
  2645. mark = 1;
  2646. ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
  2647. }
  2648. /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
  2649. if (rtp->lastts > rtp->lastdigitts) {
  2650. rtp->lastdigitts = rtp->lastts;
  2651. }
  2652. if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
  2653. rtp->lastts = frame->ts * rate;
  2654. }
  2655. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2656. /* If we know the remote address construct a packet and send it out */
  2657. if (!ast_sockaddr_isnull(&remote_address)) {
  2658. int hdrlen = 12, res, ice;
  2659. unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
  2660. put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
  2661. put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
  2662. put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
  2663. if ((res = rtp_sendto(instance, (void *)rtpheader, frame->datalen + hdrlen, 0, &remote_address, &ice)) < 0) {
  2664. 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))) {
  2665. ast_debug(1, "RTP Transmission error of packet %d to %s: %s\n",
  2666. rtp->seqno,
  2667. ast_sockaddr_stringify(&remote_address),
  2668. strerror(errno));
  2669. } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
  2670. /* Only give this error message once if we are not RTP debugging */
  2671. if (rtpdebug)
  2672. ast_debug(0, "RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
  2673. ast_sockaddr_stringify(&remote_address));
  2674. ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
  2675. }
  2676. } else {
  2677. rtp->txcount++;
  2678. rtp->txoctetcount += (res - hdrlen);
  2679. if (rtp->rtcp && rtp->rtcp->schedid < 1) {
  2680. ast_debug(1, "Starting RTCP transmission on RTP instance '%p'\n", instance);
  2681. ao2_ref(instance, +1);
  2682. rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
  2683. if (rtp->rtcp->schedid < 0) {
  2684. ao2_ref(instance, -1);
  2685. ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
  2686. }
  2687. }
  2688. }
  2689. if (rtp_debug_test_addr(&remote_address)) {
  2690. ast_verbose("Sent RTP packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
  2691. ast_sockaddr_stringify(&remote_address),
  2692. ice ? " (via ICE)" : "",
  2693. codec, rtp->seqno, rtp->lastts, res - hdrlen);
  2694. }
  2695. }
  2696. rtp->seqno++;
  2697. return 0;
  2698. }
  2699. static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
  2700. unsigned char *data = red->t140red.data.ptr;
  2701. int len = 0;
  2702. int i;
  2703. /* replace most aged generation */
  2704. if (red->len[0]) {
  2705. for (i = 1; i < red->num_gen+1; i++)
  2706. len += red->len[i];
  2707. memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
  2708. }
  2709. /* Store length of each generation and primary data length*/
  2710. for (i = 0; i < red->num_gen; i++)
  2711. red->len[i] = red->len[i+1];
  2712. red->len[i] = red->t140.datalen;
  2713. /* write each generation length in red header */
  2714. len = red->hdrlen;
  2715. for (i = 0; i < red->num_gen; i++) {
  2716. len += data[i*4+3] = red->len[i];
  2717. }
  2718. /* add primary data to buffer */
  2719. memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
  2720. red->t140red.datalen = len + red->t140.datalen;
  2721. /* no primary data and no generations to send */
  2722. if (len == red->hdrlen && !red->t140.datalen) {
  2723. return NULL;
  2724. }
  2725. /* reset t.140 buffer */
  2726. red->t140.datalen = 0;
  2727. return &red->t140red;
  2728. }
  2729. static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
  2730. {
  2731. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2732. struct ast_sockaddr remote_address = { {0,} };
  2733. struct ast_format *format;
  2734. int codec;
  2735. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2736. /* If we don't actually know the remote address don't even bother doing anything */
  2737. if (ast_sockaddr_isnull(&remote_address)) {
  2738. ast_debug(1, "No remote address on RTP instance '%p' so dropping frame\n", instance);
  2739. return 0;
  2740. }
  2741. /* VP8: is this a request to send a RTCP FIR? */
  2742. if (frame->frametype == AST_FRAME_CONTROL && frame->subclass.integer == AST_CONTROL_VIDUPDATE) {
  2743. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2744. unsigned int *rtcpheader;
  2745. char bdata[1024];
  2746. int len = 20;
  2747. int ice;
  2748. int res;
  2749. if (!rtp || !rtp->rtcp) {
  2750. return 0;
  2751. }
  2752. if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
  2753. /*
  2754. * RTCP was stopped.
  2755. */
  2756. return 0;
  2757. }
  2758. /* Prepare RTCP FIR (PT=206, FMT=4) */
  2759. rtp->rtcp->firseq++;
  2760. if(rtp->rtcp->firseq == 256) {
  2761. rtp->rtcp->firseq = 0;
  2762. }
  2763. rtcpheader = (unsigned int *)bdata;
  2764. rtcpheader[0] = htonl((2 << 30) | (4 << 24) | (RTCP_PT_PSFB << 16) | ((len/4)-1));
  2765. rtcpheader[1] = htonl(rtp->ssrc);
  2766. rtcpheader[2] = htonl(rtp->themssrc);
  2767. rtcpheader[3] = htonl(rtp->themssrc); /* FCI: SSRC */
  2768. rtcpheader[4] = htonl(rtp->rtcp->firseq << 24); /* FCI: Sequence number */
  2769. res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &rtp->rtcp->them, &ice);
  2770. if (res < 0) {
  2771. ast_log(LOG_ERROR, "RTCP FIR transmission error: %s\n", strerror(errno));
  2772. }
  2773. return 0;
  2774. }
  2775. /* If there is no data length we can't very well send the packet */
  2776. if (!frame->datalen) {
  2777. ast_debug(1, "Received frame with no data for RTP instance '%p' so dropping frame\n", instance);
  2778. return 0;
  2779. }
  2780. /* If the packet is not one our RTP stack supports bail out */
  2781. if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
  2782. ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
  2783. return -1;
  2784. }
  2785. if (rtp->red) {
  2786. /* return 0; */
  2787. /* no primary data or generations to send */
  2788. if ((frame = red_t140_to_red(rtp->red)) == NULL)
  2789. return 0;
  2790. }
  2791. /* Grab the subclass and look up the payload we are going to use */
  2792. codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance),
  2793. 1,
  2794. frame->subclass.format,
  2795. 0);
  2796. if (codec < 0) {
  2797. ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n",
  2798. ast_format_get_name(frame->subclass.format));
  2799. return -1;
  2800. }
  2801. /* Note that we do not increase the ref count here as this pointer
  2802. * will not be held by any thing explicitly. The format variable is
  2803. * merely a convenience reference to frame->subclass.format */
  2804. format = frame->subclass.format;
  2805. if (ast_format_cmp(rtp->lasttxformat, format) == AST_FORMAT_CMP_NOT_EQUAL) {
  2806. /* Oh dear, if the format changed we will have to set up a new smoother */
  2807. if (option_debug > 0) {
  2808. ast_debug(1, "Ooh, format changed from %s to %s\n",
  2809. ast_format_get_name(rtp->lasttxformat),
  2810. ast_format_get_name(frame->subclass.format));
  2811. }
  2812. ao2_replace(rtp->lasttxformat, format);
  2813. if (rtp->smoother) {
  2814. ast_smoother_free(rtp->smoother);
  2815. rtp->smoother = NULL;
  2816. }
  2817. }
  2818. /* If no smoother is present see if we have to set one up */
  2819. if (!rtp->smoother && ast_format_can_be_smoothed(format)) {
  2820. unsigned int framing_ms = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(instance));
  2821. if (framing_ms) {
  2822. rtp->smoother = ast_smoother_new((framing_ms * ast_format_get_minimum_bytes(format)) / ast_format_get_minimum_ms(format));
  2823. if (!rtp->smoother) {
  2824. ast_log(LOG_WARNING, "Unable to create smoother: format %s ms: %u len: %u\n",
  2825. ast_format_get_name(format), framing_ms, ast_format_get_minimum_bytes(format));
  2826. return -1;
  2827. }
  2828. }
  2829. }
  2830. /* Feed audio frames into the actual function that will create a frame and send it */
  2831. if (rtp->smoother) {
  2832. struct ast_frame *f;
  2833. if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
  2834. ast_smoother_feed_be(rtp->smoother, frame);
  2835. } else {
  2836. ast_smoother_feed(rtp->smoother, frame);
  2837. }
  2838. while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
  2839. ast_rtp_raw_write(instance, f, codec);
  2840. }
  2841. } else {
  2842. int hdrlen = 12;
  2843. struct ast_frame *f = NULL;
  2844. if (frame->offset < hdrlen) {
  2845. f = ast_frdup(frame);
  2846. } else {
  2847. f = frame;
  2848. }
  2849. if (f->data.ptr) {
  2850. ast_rtp_raw_write(instance, f, codec);
  2851. }
  2852. if (f != frame) {
  2853. ast_frfree(f);
  2854. }
  2855. }
  2856. return 0;
  2857. }
  2858. static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
  2859. {
  2860. struct timeval now;
  2861. struct timeval tmp;
  2862. double transit;
  2863. double current_time;
  2864. double d;
  2865. double dtv;
  2866. double prog;
  2867. int rate = rtp_get_rate(rtp->f.subclass.format);
  2868. double normdev_rxjitter_current;
  2869. if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
  2870. gettimeofday(&rtp->rxcore, NULL);
  2871. rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
  2872. /* map timestamp to a real time */
  2873. rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
  2874. tmp = ast_samp2tv(timestamp, rate);
  2875. rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
  2876. /* Round to 0.1ms for nice, pretty timestamps */
  2877. rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
  2878. }
  2879. gettimeofday(&now,NULL);
  2880. /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
  2881. tmp = ast_samp2tv(timestamp, rate);
  2882. *tv = ast_tvadd(rtp->rxcore, tmp);
  2883. prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
  2884. dtv = (double)rtp->drxcore + (double)(prog);
  2885. current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
  2886. transit = current_time - dtv;
  2887. d = transit - rtp->rxtransit;
  2888. rtp->rxtransit = transit;
  2889. if (d<0) {
  2890. d=-d;
  2891. }
  2892. rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
  2893. if (rtp->rtcp) {
  2894. if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
  2895. rtp->rtcp->maxrxjitter = rtp->rxjitter;
  2896. if (rtp->rtcp->rxjitter_count == 1)
  2897. rtp->rtcp->minrxjitter = rtp->rxjitter;
  2898. if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
  2899. rtp->rtcp->minrxjitter = rtp->rxjitter;
  2900. normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
  2901. rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
  2902. rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
  2903. rtp->rtcp->rxjitter_count++;
  2904. }
  2905. }
  2906. static struct ast_frame *create_dtmf_frame(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
  2907. {
  2908. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2909. struct ast_sockaddr remote_address = { {0,} };
  2910. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2911. if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
  2912. ast_debug(1, "Ignore potential DTMF echo from '%s'\n",
  2913. ast_sockaddr_stringify(&remote_address));
  2914. rtp->resp = 0;
  2915. rtp->dtmfsamples = 0;
  2916. return &ast_null_frame;
  2917. }
  2918. ast_debug(1, "Creating %s DTMF Frame: %d (%c), at %s\n",
  2919. type == AST_FRAME_DTMF_END ? "END" : "BEGIN",
  2920. rtp->resp, rtp->resp,
  2921. ast_sockaddr_stringify(&remote_address));
  2922. if (rtp->resp == 'X') {
  2923. rtp->f.frametype = AST_FRAME_CONTROL;
  2924. rtp->f.subclass.integer = AST_CONTROL_FLASH;
  2925. } else {
  2926. rtp->f.frametype = type;
  2927. rtp->f.subclass.integer = rtp->resp;
  2928. }
  2929. rtp->f.datalen = 0;
  2930. rtp->f.samples = 0;
  2931. rtp->f.mallocd = 0;
  2932. rtp->f.src = "RTP";
  2933. AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
  2934. return &rtp->f;
  2935. }
  2936. 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)
  2937. {
  2938. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2939. struct ast_sockaddr remote_address = { {0,} };
  2940. unsigned int event, event_end, samples;
  2941. char resp = 0;
  2942. struct ast_frame *f = NULL;
  2943. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2944. /* Figure out event, event end, and samples */
  2945. event = ntohl(*((unsigned int *)(data)));
  2946. event >>= 24;
  2947. event_end = ntohl(*((unsigned int *)(data)));
  2948. event_end <<= 8;
  2949. event_end >>= 24;
  2950. samples = ntohl(*((unsigned int *)(data)));
  2951. samples &= 0xFFFF;
  2952. if (rtp_debug_test_addr(&remote_address)) {
  2953. 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",
  2954. ast_sockaddr_stringify(&remote_address),
  2955. payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
  2956. }
  2957. /* Print out debug if turned on */
  2958. if (rtpdebug)
  2959. ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
  2960. /* Figure out what digit was pressed */
  2961. if (event < 10) {
  2962. resp = '0' + event;
  2963. } else if (event < 11) {
  2964. resp = '*';
  2965. } else if (event < 12) {
  2966. resp = '#';
  2967. } else if (event < 16) {
  2968. resp = 'A' + (event - 12);
  2969. } else if (event < 17) { /* Event 16: Hook flash */
  2970. resp = 'X';
  2971. } else {
  2972. /* Not a supported event */
  2973. ast_debug(1, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
  2974. return;
  2975. }
  2976. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
  2977. if ((rtp->last_end_timestamp != timestamp) || (rtp->resp && rtp->resp != resp)) {
  2978. rtp->resp = resp;
  2979. rtp->dtmf_timeout = 0;
  2980. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)));
  2981. f->len = 0;
  2982. rtp->last_end_timestamp = timestamp;
  2983. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  2984. }
  2985. } else {
  2986. /* The duration parameter measures the complete
  2987. duration of the event (from the beginning) - RFC2833.
  2988. Account for the fact that duration is only 16 bits long
  2989. (about 8 seconds at 8000 Hz) and can wrap is digit
  2990. is hold for too long. */
  2991. unsigned int new_duration = rtp->dtmf_duration;
  2992. unsigned int last_duration = new_duration & 0xFFFF;
  2993. if (last_duration > 64000 && samples < last_duration) {
  2994. new_duration += 0xFFFF + 1;
  2995. }
  2996. new_duration = (new_duration & ~0xFFFF) | samples;
  2997. if (event_end & 0x80) {
  2998. /* End event */
  2999. if ((rtp->last_seqno != seqno) && (timestamp > rtp->last_end_timestamp)) {
  3000. rtp->last_end_timestamp = timestamp;
  3001. rtp->dtmf_duration = new_duration;
  3002. rtp->resp = resp;
  3003. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
  3004. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.format)), ast_tv(0, 0));
  3005. rtp->resp = 0;
  3006. rtp->dtmf_duration = rtp->dtmf_timeout = 0;
  3007. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  3008. } else if (rtpdebug) {
  3009. ast_debug(1, "Dropping duplicate or out of order DTMF END frame (seqno: %u, ts %u, digit %c)\n",
  3010. seqno, timestamp, resp);
  3011. }
  3012. } else {
  3013. /* Begin/continuation */
  3014. /* The second portion of the seqno check is to not mistakenly
  3015. * stop accepting DTMF if the seqno rolls over beyond
  3016. * 65535.
  3017. */
  3018. if ((rtp->last_seqno > seqno && rtp->last_seqno - seqno < 50)
  3019. || timestamp <= rtp->last_end_timestamp) {
  3020. /* Out of order frame. Processing this can cause us to
  3021. * improperly duplicate incoming DTMF, so just drop
  3022. * this.
  3023. */
  3024. if (rtpdebug) {
  3025. ast_debug(1, "Dropping out of order DTMF frame (seqno %u, ts %u, digit %c)\n",
  3026. seqno, timestamp, resp);
  3027. }
  3028. return;
  3029. }
  3030. if (rtp->resp && rtp->resp != resp) {
  3031. /* Another digit already began. End it */
  3032. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
  3033. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.format)), ast_tv(0, 0));
  3034. rtp->resp = 0;
  3035. rtp->dtmf_duration = rtp->dtmf_timeout = 0;
  3036. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  3037. }
  3038. if (rtp->resp) {
  3039. /* Digit continues */
  3040. rtp->dtmf_duration = new_duration;
  3041. } else {
  3042. /* New digit began */
  3043. rtp->resp = resp;
  3044. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0));
  3045. rtp->dtmf_duration = samples;
  3046. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  3047. }
  3048. rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
  3049. }
  3050. rtp->last_seqno = seqno;
  3051. }
  3052. rtp->dtmfsamples = samples;
  3053. return;
  3054. }
  3055. 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)
  3056. {
  3057. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3058. unsigned int event, flags, power;
  3059. char resp = 0;
  3060. unsigned char seq;
  3061. struct ast_frame *f = NULL;
  3062. if (len < 4) {
  3063. return NULL;
  3064. }
  3065. /* The format of Cisco RTP DTMF packet looks like next:
  3066. +0 - sequence number of DTMF RTP packet (begins from 1,
  3067. wrapped to 0)
  3068. +1 - set of flags
  3069. +1 (bit 0) - flaps by different DTMF digits delimited by audio
  3070. or repeated digit without audio???
  3071. +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
  3072. then falls to 0 at its end)
  3073. +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
  3074. Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
  3075. by each new packet and thus provides some redudancy.
  3076. Sample of Cisco RTP DTMF packet is (all data in hex):
  3077. 19 07 00 02 12 02 20 02
  3078. showing end of DTMF digit '2'.
  3079. The packets
  3080. 27 07 00 02 0A 02 20 02
  3081. 28 06 20 02 00 02 0A 02
  3082. shows begin of new digit '2' with very short pause (20 ms) after
  3083. previous digit '2'. Bit +1.0 flips at begin of new digit.
  3084. Cisco RTP DTMF packets comes as replacement of audio RTP packets
  3085. so its uses the same sequencing and timestamping rules as replaced
  3086. audio packets. Repeat interval of DTMF packets is 20 ms and not rely
  3087. on audio framing parameters. Marker bit isn't used within stream of
  3088. DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
  3089. are not sequential at borders between DTMF and audio streams,
  3090. */
  3091. seq = data[0];
  3092. flags = data[1];
  3093. power = data[2];
  3094. event = data[3] & 0x1f;
  3095. if (rtpdebug)
  3096. 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);
  3097. if (event < 10) {
  3098. resp = '0' + event;
  3099. } else if (event < 11) {
  3100. resp = '*';
  3101. } else if (event < 12) {
  3102. resp = '#';
  3103. } else if (event < 16) {
  3104. resp = 'A' + (event - 12);
  3105. } else if (event < 17) {
  3106. resp = 'X';
  3107. }
  3108. if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
  3109. rtp->resp = resp;
  3110. /* Why we should care on DTMF compensation at reception? */
  3111. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
  3112. f = create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0);
  3113. rtp->dtmfsamples = 0;
  3114. }
  3115. } else if ((rtp->resp == resp) && !power) {
  3116. f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE));
  3117. f->samples = rtp->dtmfsamples * (rtp_get_rate(rtp->lastrxformat) / 1000);
  3118. rtp->resp = 0;
  3119. } else if (rtp->resp == resp) {
  3120. rtp->dtmfsamples += 20 * (rtp_get_rate(rtp->lastrxformat) / 1000);
  3121. }
  3122. rtp->dtmf_timeout = 0;
  3123. return f;
  3124. }
  3125. 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)
  3126. {
  3127. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3128. /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
  3129. totally help us out becuase we don't have an engine to keep it going and we are not
  3130. guaranteed to have it every 20ms or anything */
  3131. if (rtpdebug) {
  3132. ast_debug(0, "- RTP 3389 Comfort noise event: Format %s (len = %d)\n",
  3133. ast_format_get_name(rtp->lastrxformat), len);
  3134. }
  3135. if (ast_test_flag(rtp, FLAG_3389_WARNING)) {
  3136. struct ast_sockaddr remote_address = { {0,} };
  3137. ast_rtp_instance_get_remote_address(instance, &remote_address);
  3138. ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client address: %s\n",
  3139. ast_sockaddr_stringify(&remote_address));
  3140. ast_set_flag(rtp, FLAG_3389_WARNING);
  3141. }
  3142. /* Must have at least one byte */
  3143. if (!len) {
  3144. return NULL;
  3145. }
  3146. if (len < 24) {
  3147. rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
  3148. rtp->f.datalen = len - 1;
  3149. rtp->f.offset = AST_FRIENDLY_OFFSET;
  3150. memcpy(rtp->f.data.ptr, data + 1, len - 1);
  3151. } else {
  3152. rtp->f.data.ptr = NULL;
  3153. rtp->f.offset = 0;
  3154. rtp->f.datalen = 0;
  3155. }
  3156. rtp->f.frametype = AST_FRAME_CNG;
  3157. rtp->f.subclass.integer = data[0] & 0x7f;
  3158. rtp->f.samples = 0;
  3159. rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
  3160. return &rtp->f;
  3161. }
  3162. static int update_rtt_stats(struct ast_rtp *rtp, unsigned int lsr, unsigned int dlsr)
  3163. {
  3164. struct timeval now;
  3165. struct timeval rtt_tv;
  3166. unsigned int msw;
  3167. unsigned int lsw;
  3168. unsigned int rtt_msw;
  3169. unsigned int rtt_lsw;
  3170. unsigned int lsr_a;
  3171. unsigned int rtt;
  3172. double normdevrtt_current;
  3173. gettimeofday(&now, NULL);
  3174. timeval2ntp(now, &msw, &lsw);
  3175. lsr_a = ((msw & 0x0000ffff) << 16) | ((lsw & 0xffff0000) >> 16);
  3176. rtt = lsr_a - lsr - dlsr;
  3177. rtt_msw = (rtt & 0xffff0000) >> 16;
  3178. rtt_lsw = (rtt & 0x0000ffff) << 16;
  3179. rtt_tv.tv_sec = rtt_msw;
  3180. rtt_tv.tv_usec = ((rtt_lsw << 6) / 3650) - (rtt_lsw >> 12) - (rtt_lsw >> 8);
  3181. rtp->rtcp->rtt = (double)rtt_tv.tv_sec + ((double)rtt_tv.tv_usec / 1000000);
  3182. if (lsr_a - dlsr < lsr) {
  3183. return 1;
  3184. }
  3185. rtp->rtcp->accumulated_transit += rtp->rtcp->rtt;
  3186. if (rtp->rtcp->rtt_count == 0 || rtp->rtcp->minrtt > rtp->rtcp->rtt) {
  3187. rtp->rtcp->minrtt = rtp->rtcp->rtt;
  3188. }
  3189. if (rtp->rtcp->maxrtt < rtp->rtcp->rtt) {
  3190. rtp->rtcp->maxrtt = rtp->rtcp->rtt;
  3191. }
  3192. normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt,
  3193. rtp->rtcp->rtt,
  3194. rtp->rtcp->rtt_count);
  3195. rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt,
  3196. rtp->rtcp->rtt,
  3197. rtp->rtcp->normdevrtt,
  3198. normdevrtt_current,
  3199. rtp->rtcp->rtt_count);
  3200. rtp->rtcp->normdevrtt = normdevrtt_current;
  3201. rtp->rtcp->rtt_count++;
  3202. return 0;
  3203. }
  3204. /*!
  3205. * \internal
  3206. * \brief Update RTCP interarrival jitter stats
  3207. */
  3208. static void update_jitter_stats(struct ast_rtp *rtp, unsigned int ia_jitter)
  3209. {
  3210. double reported_jitter;
  3211. double reported_normdev_jitter_current;
  3212. rtp->rtcp->reported_jitter = ia_jitter;
  3213. reported_jitter = (double) rtp->rtcp->reported_jitter;
  3214. if (rtp->rtcp->reported_jitter_count == 0) {
  3215. rtp->rtcp->reported_minjitter = reported_jitter;
  3216. }
  3217. if (reported_jitter < rtp->rtcp->reported_minjitter) {
  3218. rtp->rtcp->reported_minjitter = reported_jitter;
  3219. }
  3220. if (reported_jitter > rtp->rtcp->reported_maxjitter) {
  3221. rtp->rtcp->reported_maxjitter = reported_jitter;
  3222. }
  3223. reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);
  3224. 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);
  3225. rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;
  3226. }
  3227. /*!
  3228. * \internal
  3229. * \brief Update RTCP lost packet stats
  3230. */
  3231. static void update_lost_stats(struct ast_rtp *rtp, unsigned int lost_packets)
  3232. {
  3233. double reported_lost;
  3234. double reported_normdev_lost_current;
  3235. rtp->rtcp->reported_lost = lost_packets;
  3236. reported_lost = (double)rtp->rtcp->reported_lost;
  3237. if (rtp->rtcp->reported_jitter_count == 0) {
  3238. rtp->rtcp->reported_minlost = reported_lost;
  3239. }
  3240. if (reported_lost < rtp->rtcp->reported_minlost) {
  3241. rtp->rtcp->reported_minlost = reported_lost;
  3242. }
  3243. if (reported_lost > rtp->rtcp->reported_maxlost) {
  3244. rtp->rtcp->reported_maxlost = reported_lost;
  3245. }
  3246. reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);
  3247. 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);
  3248. rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;
  3249. }
  3250. static struct ast_frame *ast_rtcp_read(struct ast_rtp_instance *instance)
  3251. {
  3252. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3253. struct ast_sockaddr addr;
  3254. unsigned char rtcpdata[8192 + AST_FRIENDLY_OFFSET];
  3255. unsigned int *rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
  3256. int res, packetwords, position = 0;
  3257. int report_counter = 0;
  3258. struct ast_rtp_rtcp_report_block *report_block;
  3259. struct ast_frame *f = &ast_null_frame;
  3260. char *str_local_address;
  3261. char *str_remote_address;
  3262. struct ast_sockaddr local_address = { { 0,} };
  3263. struct ast_sockaddr real_local_address = { { 0, } };
  3264. struct ast_sockaddr real_remote_address = { { 0, } };
  3265. /* Read in RTCP data from the socket */
  3266. if ((res = rtcp_recvfrom(instance, rtcpdata + AST_FRIENDLY_OFFSET,
  3267. sizeof(rtcpdata) - AST_FRIENDLY_OFFSET,
  3268. 0, &addr)) < 0) {
  3269. ast_assert(errno != EBADF);
  3270. if (errno != EAGAIN) {
  3271. ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n",
  3272. (errno) ? strerror(errno) : "Unspecified");
  3273. return NULL;
  3274. }
  3275. return &ast_null_frame;
  3276. }
  3277. /* If this was handled by the ICE session don't do anything further */
  3278. if (!res) {
  3279. return &ast_null_frame;
  3280. }
  3281. if (!*(rtcpdata + AST_FRIENDLY_OFFSET)) {
  3282. struct sockaddr_in addr_tmp;
  3283. struct ast_sockaddr addr_v4;
  3284. if (ast_sockaddr_is_ipv4(&addr)) {
  3285. ast_sockaddr_to_sin(&addr, &addr_tmp);
  3286. } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
  3287. ast_debug(1, "Using IPv6 mapped address %s for STUN\n",
  3288. ast_sockaddr_stringify(&addr));
  3289. ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
  3290. } else {
  3291. ast_debug(1, "Cannot do STUN for non IPv4 address %s\n",
  3292. ast_sockaddr_stringify(&addr));
  3293. return &ast_null_frame;
  3294. }
  3295. if ((ast_stun_handle_packet(rtp->rtcp->s, &addr_tmp, rtcpdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == AST_STUN_ACCEPT)) {
  3296. ast_sockaddr_from_sin(&addr, &addr_tmp);
  3297. ast_sockaddr_copy(&rtp->rtcp->them, &addr);
  3298. }
  3299. return &ast_null_frame;
  3300. }
  3301. packetwords = res / 4;
  3302. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
  3303. /* Send to whoever sent to us */
  3304. if (ast_sockaddr_cmp(&rtp->rtcp->them, &addr)) {
  3305. ast_sockaddr_copy(&rtp->rtcp->them, &addr);
  3306. if (rtpdebug) {
  3307. ast_debug(0, "RTCP NAT: Got RTCP from other end. Now sending to address %s\n",
  3308. ast_sockaddr_stringify(&rtp->rtcp->them));
  3309. }
  3310. }
  3311. }
  3312. ast_debug(1, "Got RTCP report of %d bytes\n", res);
  3313. ast_rtp_instance_get_local_address(instance, &local_address);
  3314. while (position < packetwords) {
  3315. int i, pt, rc;
  3316. unsigned int length;
  3317. struct ast_json *message_blob;
  3318. RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report, NULL, ao2_cleanup);
  3319. i = position;
  3320. length = ntohl(rtcpheader[i]);
  3321. pt = (length & 0xff0000) >> 16;
  3322. rc = (length & 0x1f000000) >> 24;
  3323. length &= 0xffff;
  3324. rtcp_report = ast_rtp_rtcp_report_alloc(rc);
  3325. if (!rtcp_report) {
  3326. return &ast_null_frame;
  3327. }
  3328. rtcp_report->reception_report_count = rc;
  3329. rtcp_report->ssrc = ntohl(rtcpheader[i + 1]);
  3330. if ((i + length) > packetwords) {
  3331. if (rtpdebug) {
  3332. ast_debug(1, "RTCP Read too short\n");
  3333. }
  3334. return &ast_null_frame;
  3335. }
  3336. if (rtcp_debug_test_addr(&addr)) {
  3337. ast_verbose("\n\nGot RTCP from %s\n",
  3338. ast_sockaddr_stringify(&addr));
  3339. ast_verbose("PT: %d(%s)\n", pt, (pt == RTCP_PT_SR) ? "Sender Report" :
  3340. (pt == RTCP_PT_RR) ? "Receiver Report" :
  3341. (pt == RTCP_PT_FUR) ? "H.261 FUR" : "Unknown");
  3342. ast_verbose("Reception reports: %d\n", rc);
  3343. ast_verbose("SSRC of sender: %u\n", rtcp_report->ssrc);
  3344. }
  3345. i += 2; /* Advance past header and ssrc */
  3346. switch (pt) {
  3347. case RTCP_PT_SR:
  3348. gettimeofday(&rtp->rtcp->rxlsr, NULL);
  3349. rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16);
  3350. rtp->rtcp->spc = ntohl(rtcpheader[i + 3]);
  3351. rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
  3352. rtcp_report->type = RTCP_PT_SR;
  3353. rtcp_report->sender_information.packet_count = rtp->rtcp->spc;
  3354. rtcp_report->sender_information.octet_count = rtp->rtcp->soc;
  3355. ntp2timeval((unsigned int)ntohl(rtcpheader[i]),
  3356. (unsigned int)ntohl(rtcpheader[i + 1]),
  3357. &rtcp_report->sender_information.ntp_timestamp);
  3358. rtcp_report->sender_information.rtp_timestamp = ntohl(rtcpheader[i + 2]);
  3359. if (rtcp_debug_test_addr(&addr)) {
  3360. ast_verbose("NTP timestamp: %u.%010u\n",
  3361. (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
  3362. (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec * 4096);
  3363. ast_verbose("RTP timestamp: %u\n", rtcp_report->sender_information.rtp_timestamp);
  3364. ast_verbose("SPC: %u\tSOC: %u\n",
  3365. rtcp_report->sender_information.packet_count,
  3366. rtcp_report->sender_information.octet_count);
  3367. }
  3368. i += 5;
  3369. /* Intentional fall through */
  3370. case RTCP_PT_RR:
  3371. if (rtcp_report->type != RTCP_PT_SR) {
  3372. rtcp_report->type = RTCP_PT_RR;
  3373. }
  3374. if (rc > 0) {
  3375. /* Don't handle multiple reception reports (rc > 1) yet */
  3376. report_block = ast_calloc(1, sizeof(*report_block));
  3377. if (!report_block) {
  3378. return &ast_null_frame;
  3379. }
  3380. rtcp_report->report_block[report_counter] = report_block;
  3381. report_block->source_ssrc = ntohl(rtcpheader[i]);
  3382. report_block->lost_count.packets = ntohl(rtcpheader[i + 1]) & 0x00ffffff;
  3383. report_block->lost_count.fraction = ((ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24);
  3384. report_block->highest_seq_no = ntohl(rtcpheader[i + 2]);
  3385. report_block->ia_jitter = ntohl(rtcpheader[i + 3]);
  3386. report_block->lsr = ntohl(rtcpheader[i + 4]);
  3387. report_block->dlsr = ntohl(rtcpheader[i + 5]);
  3388. if (report_block->lsr
  3389. && update_rtt_stats(rtp, report_block->lsr, report_block->dlsr)
  3390. && rtcp_debug_test_addr(&addr)) {
  3391. struct timeval now;
  3392. unsigned int lsr_now, lsw, msw;
  3393. gettimeofday(&now, NULL);
  3394. timeval2ntp(now, &msw, &lsw);
  3395. lsr_now = (((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16));
  3396. ast_verbose("Internal RTCP NTP clock skew detected: "
  3397. "lsr=%u, now=%u, dlsr=%u (%u:%03ums), "
  3398. "diff=%u\n",
  3399. report_block->lsr, lsr_now, report_block->dlsr, report_block->dlsr / 65536,
  3400. (report_block->dlsr % 65536) * 1000 / 65536,
  3401. report_block->dlsr - (lsr_now - report_block->lsr));
  3402. }
  3403. update_jitter_stats(rtp, report_block->ia_jitter);
  3404. update_lost_stats(rtp, report_block->lost_count.packets);
  3405. rtp->rtcp->reported_jitter_count++;
  3406. if (rtcp_debug_test_addr(&addr)) {
  3407. ast_verbose(" Fraction lost: %d\n", report_block->lost_count.fraction);
  3408. ast_verbose(" Packets lost so far: %u\n", report_block->lost_count.packets);
  3409. ast_verbose(" Highest sequence number: %u\n", report_block->highest_seq_no & 0x0000ffff);
  3410. ast_verbose(" Sequence number cycles: %u\n", report_block->highest_seq_no >> 16);
  3411. ast_verbose(" Interarrival jitter: %u\n", report_block->ia_jitter);
  3412. ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long)(report_block->lsr) >> 16,((unsigned long)(report_block->lsr) << 16) * 4096);
  3413. ast_verbose(" DLSR: %4.4f (sec)\n",(double)report_block->dlsr / 65536.0);
  3414. ast_verbose(" RTT: %4.4f(sec)\n", rtp->rtcp->rtt);
  3415. }
  3416. report_counter++;
  3417. }
  3418. /* If and when we handle more than one report block, this should occur outside
  3419. * this loop.
  3420. */
  3421. if (!ast_find_ourip(&real_local_address, &local_address, 0)) {
  3422. str_local_address = ast_strdupa(ast_sockaddr_stringify(&real_local_address));
  3423. } else {
  3424. str_local_address = ast_strdupa(ast_sockaddr_stringify(&local_address));
  3425. }
  3426. if (!ast_find_ourip(&real_remote_address, &addr, 0)) {
  3427. str_remote_address = ast_strdupa(ast_sockaddr_stringify(&real_remote_address));
  3428. } else {
  3429. str_remote_address = ast_strdupa(ast_sockaddr_stringify(&addr));
  3430. }
  3431. message_blob = ast_json_pack("{s: s, s: s, s: f}",
  3432. "from", str_remote_address,
  3433. "to", str_local_address,
  3434. "rtt", rtp->rtcp->rtt);
  3435. ast_rtp_publish_rtcp_message(instance, ast_rtp_rtcp_received_type(),
  3436. rtcp_report,
  3437. message_blob);
  3438. ast_json_unref(message_blob);
  3439. break;
  3440. case RTCP_PT_FUR:
  3441. /* Handle RTCP FIR as FUR */
  3442. case RTCP_PT_PSFB:
  3443. if (rtcp_debug_test_addr(&addr)) {
  3444. ast_verbose("Received an RTCP Fast Update Request\n");
  3445. }
  3446. rtp->f.frametype = AST_FRAME_CONTROL;
  3447. rtp->f.subclass.integer = AST_CONTROL_VIDUPDATE;
  3448. rtp->f.datalen = 0;
  3449. rtp->f.samples = 0;
  3450. rtp->f.mallocd = 0;
  3451. rtp->f.src = "RTP";
  3452. f = &rtp->f;
  3453. break;
  3454. case RTCP_PT_SDES:
  3455. if (rtcp_debug_test_addr(&addr)) {
  3456. ast_verbose("Received an SDES from %s\n",
  3457. ast_sockaddr_stringify(&rtp->rtcp->them));
  3458. }
  3459. break;
  3460. case RTCP_PT_BYE:
  3461. if (rtcp_debug_test_addr(&addr)) {
  3462. ast_verbose("Received a BYE from %s\n",
  3463. ast_sockaddr_stringify(&rtp->rtcp->them));
  3464. }
  3465. break;
  3466. default:
  3467. ast_debug(1, "Unknown RTCP packet (pt=%d) received from %s\n",
  3468. pt, ast_sockaddr_stringify(&rtp->rtcp->them));
  3469. break;
  3470. }
  3471. position += (length + 1);
  3472. }
  3473. rtp->rtcp->rtcp_info = 1;
  3474. return f;
  3475. }
  3476. static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance, unsigned int *rtpheader, int len, int hdrlen)
  3477. {
  3478. struct ast_rtp_instance *instance1 = ast_rtp_instance_get_bridged(instance);
  3479. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance), *bridged = ast_rtp_instance_get_data(instance1);
  3480. int res = 0, payload = 0, bridged_payload = 0, mark;
  3481. RAII_VAR(struct ast_rtp_payload_type *, payload_type, NULL, ao2_cleanup);
  3482. int reconstruct = ntohl(rtpheader[0]);
  3483. struct ast_sockaddr remote_address = { {0,} };
  3484. int ice;
  3485. /* Get fields from packet */
  3486. payload = (reconstruct & 0x7f0000) >> 16;
  3487. mark = (((reconstruct & 0x800000) >> 23) != 0);
  3488. /* Check what the payload value should be */
  3489. payload_type = ast_rtp_codecs_get_payload(ast_rtp_instance_get_codecs(instance), payload);
  3490. if (!payload_type) {
  3491. return -1;
  3492. }
  3493. /* Otherwise adjust bridged payload to match */
  3494. bridged_payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance1), payload_type->asterisk_format, payload_type->format, payload_type->rtp_code);
  3495. /* If no codec could be matched between instance and instance1, then somehow things were made incompatible while we were still bridged. Bail. */
  3496. if (bridged_payload < 0) {
  3497. return -1;
  3498. }
  3499. /* 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 */
  3500. if (ast_rtp_codecs_find_payload_code(ast_rtp_instance_get_codecs(instance1), bridged_payload) == -1) {
  3501. ast_debug(1, "Unsupported payload type received \n");
  3502. return -1;
  3503. }
  3504. /* If the marker bit has been explicitly set turn it on */
  3505. if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
  3506. mark = 1;
  3507. ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
  3508. }
  3509. /* Reconstruct part of the packet */
  3510. reconstruct &= 0xFF80FFFF;
  3511. reconstruct |= (bridged_payload << 16);
  3512. reconstruct |= (mark << 23);
  3513. rtpheader[0] = htonl(reconstruct);
  3514. ast_rtp_instance_get_remote_address(instance1, &remote_address);
  3515. if (ast_sockaddr_isnull(&remote_address)) {
  3516. ast_debug(1, "Remote address is null, most likely RTP has been stopped\n");
  3517. return 0;
  3518. }
  3519. /* Send the packet back out */
  3520. res = rtp_sendto(instance1, (void *)rtpheader, len, 0, &remote_address, &ice);
  3521. if (res < 0) {
  3522. 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))) {
  3523. ast_log(LOG_WARNING,
  3524. "RTP Transmission error of packet to %s: %s\n",
  3525. ast_sockaddr_stringify(&remote_address),
  3526. strerror(errno));
  3527. } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
  3528. if (option_debug || rtpdebug) {
  3529. ast_log(LOG_WARNING,
  3530. "RTP NAT: Can't write RTP to private "
  3531. "address %s, waiting for other end to "
  3532. "send audio...\n",
  3533. ast_sockaddr_stringify(&remote_address));
  3534. }
  3535. ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
  3536. }
  3537. return 0;
  3538. }
  3539. if (rtp_debug_test_addr(&remote_address)) {
  3540. ast_verbose("Sent RTP P2P packet to %s%s (type %-2.2d, len %-6.6d)\n",
  3541. ast_sockaddr_stringify(&remote_address),
  3542. ice ? " (via ICE)" : "",
  3543. bridged_payload, len - hdrlen);
  3544. }
  3545. return 0;
  3546. }
  3547. static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
  3548. {
  3549. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3550. struct ast_sockaddr addr;
  3551. int res, hdrlen = 12, version, payloadtype, padding, mark, ext, cc, prev_seqno;
  3552. unsigned int *rtpheader = (unsigned int*)(rtp->rawdata + AST_FRIENDLY_OFFSET), seqno, ssrc, timestamp;
  3553. RAII_VAR(struct ast_rtp_payload_type *, payload, NULL, ao2_cleanup);
  3554. struct ast_sockaddr remote_address = { {0,} };
  3555. struct frame_list frames;
  3556. /* If this is actually RTCP let's hop on over and handle it */
  3557. if (rtcp) {
  3558. if (rtp->rtcp) {
  3559. return ast_rtcp_read(instance);
  3560. }
  3561. return &ast_null_frame;
  3562. }
  3563. /* If we are currently sending DTMF to the remote party send a continuation packet */
  3564. if (rtp->sending_digit) {
  3565. ast_rtp_dtmf_continuation(instance);
  3566. }
  3567. /* Actually read in the data from the socket */
  3568. if ((res = rtp_recvfrom(instance, rtp->rawdata + AST_FRIENDLY_OFFSET,
  3569. sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0,
  3570. &addr)) < 0) {
  3571. ast_assert(errno != EBADF);
  3572. if (errno != EAGAIN) {
  3573. ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n",
  3574. (errno) ? strerror(errno) : "Unspecified");
  3575. return NULL;
  3576. }
  3577. return &ast_null_frame;
  3578. }
  3579. /* If this was handled by the ICE session don't do anything */
  3580. if (!res) {
  3581. return &ast_null_frame;
  3582. }
  3583. /* Make sure the data that was read in is actually enough to make up an RTP packet */
  3584. if (res < hdrlen) {
  3585. /* If this is a keepalive containing only nulls, don't bother with a warning */
  3586. int i;
  3587. for (i = 0; i < res; ++i) {
  3588. if (rtp->rawdata[AST_FRIENDLY_OFFSET + i] != '\0') {
  3589. ast_log(LOG_WARNING, "RTP Read too short\n");
  3590. return &ast_null_frame;
  3591. }
  3592. }
  3593. return &ast_null_frame;
  3594. }
  3595. /* Get fields and verify this is an RTP packet */
  3596. seqno = ntohl(rtpheader[0]);
  3597. ast_rtp_instance_get_remote_address(instance, &remote_address);
  3598. if (!(version = (seqno & 0xC0000000) >> 30)) {
  3599. struct sockaddr_in addr_tmp;
  3600. struct ast_sockaddr addr_v4;
  3601. if (ast_sockaddr_is_ipv4(&addr)) {
  3602. ast_sockaddr_to_sin(&addr, &addr_tmp);
  3603. } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
  3604. ast_debug(1, "Using IPv6 mapped address %s for STUN\n",
  3605. ast_sockaddr_stringify(&addr));
  3606. ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
  3607. } else {
  3608. ast_debug(1, "Cannot do STUN for non IPv4 address %s\n",
  3609. ast_sockaddr_stringify(&addr));
  3610. return &ast_null_frame;
  3611. }
  3612. if ((ast_stun_handle_packet(rtp->s, &addr_tmp, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == AST_STUN_ACCEPT) &&
  3613. ast_sockaddr_isnull(&remote_address)) {
  3614. ast_sockaddr_from_sin(&addr, &addr_tmp);
  3615. ast_rtp_instance_set_remote_address(instance, &addr);
  3616. }
  3617. return &ast_null_frame;
  3618. }
  3619. /* If strict RTP protection is enabled see if we need to learn the remote address or if we need to drop the packet */
  3620. if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
  3621. ast_debug(1, "%p -- Probation learning mode pass with source address %s\n", rtp, ast_sockaddr_stringify(&addr));
  3622. /* For now, we always copy the address. */
  3623. ast_sockaddr_copy(&rtp->strict_rtp_address, &addr);
  3624. /* Send the rtp and the seqno from header to rtp_learning_rtp_seq_update to see whether we can exit or not*/
  3625. if (rtp_learning_rtp_seq_update(&rtp->rtp_source_learn, seqno)) {
  3626. ast_debug(1, "%p -- Probation at seq %d with %d to go; discarding frame\n",
  3627. rtp, rtp->rtp_source_learn.max_seq, rtp->rtp_source_learn.packets);
  3628. return &ast_null_frame;
  3629. }
  3630. ast_verb(4, "%p -- Probation passed - setting RTP source address to %s\n", rtp, ast_sockaddr_stringify(&addr));
  3631. rtp->strict_rtp_state = STRICT_RTP_CLOSED;
  3632. }
  3633. if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
  3634. if (!ast_sockaddr_cmp(&rtp->strict_rtp_address, &addr)) {
  3635. /* Always reset the alternate learning source */
  3636. rtp_learning_seq_init(&rtp->alt_source_learn, seqno);
  3637. } else {
  3638. /* Start trying to learn from the new address. If we pass a probationary period with
  3639. * it, that means we've stopped getting RTP from the original source and we should
  3640. * switch to it.
  3641. */
  3642. if (rtp_learning_rtp_seq_update(&rtp->alt_source_learn, seqno)) {
  3643. ast_debug(1, "%p -- Received RTP packet from %s, dropping due to strict RTP protection. Will switch to it in %d packets\n",
  3644. rtp, ast_sockaddr_stringify(&addr), rtp->alt_source_learn.packets);
  3645. return &ast_null_frame;
  3646. }
  3647. ast_verb(4, "%p -- Switching RTP source address to %s\n", rtp, ast_sockaddr_stringify(&addr));
  3648. ast_sockaddr_copy(&rtp->strict_rtp_address, &addr);
  3649. }
  3650. }
  3651. /* If symmetric RTP is enabled see if the remote side is not what we expected and change where we are sending audio */
  3652. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
  3653. if (ast_sockaddr_cmp(&remote_address, &addr)) {
  3654. ast_rtp_instance_set_remote_address(instance, &addr);
  3655. ast_sockaddr_copy(&remote_address, &addr);
  3656. if (rtp->rtcp) {
  3657. ast_sockaddr_copy(&rtp->rtcp->them, &addr);
  3658. ast_sockaddr_set_port(&rtp->rtcp->them, ast_sockaddr_port(&addr) + 1);
  3659. }
  3660. rtp->rxseqno = 0;
  3661. ast_set_flag(rtp, FLAG_NAT_ACTIVE);
  3662. if (rtpdebug)
  3663. ast_debug(0, "RTP NAT: Got audio from other end. Now sending to address %s\n",
  3664. ast_sockaddr_stringify(&remote_address));
  3665. }
  3666. }
  3667. /* If we are directly bridged to another instance send the audio directly out */
  3668. if (ast_rtp_instance_get_bridged(instance) && !bridge_p2p_rtp_write(instance, rtpheader, res, hdrlen)) {
  3669. return &ast_null_frame;
  3670. }
  3671. /* If the version is not what we expected by this point then just drop the packet */
  3672. if (version != 2) {
  3673. return &ast_null_frame;
  3674. }
  3675. /* Pull out the various other fields we will need */
  3676. payloadtype = (seqno & 0x7f0000) >> 16;
  3677. padding = seqno & (1 << 29);
  3678. mark = seqno & (1 << 23);
  3679. ext = seqno & (1 << 28);
  3680. cc = (seqno & 0xF000000) >> 24;
  3681. seqno &= 0xffff;
  3682. timestamp = ntohl(rtpheader[1]);
  3683. ssrc = ntohl(rtpheader[2]);
  3684. AST_LIST_HEAD_INIT_NOLOCK(&frames);
  3685. /* Force a marker bit and change SSRC if the SSRC changes */
  3686. if (rtp->rxssrc && rtp->rxssrc != ssrc) {
  3687. struct ast_frame *f, srcupdate = {
  3688. AST_FRAME_CONTROL,
  3689. .subclass.integer = AST_CONTROL_SRCCHANGE,
  3690. };
  3691. if (!mark) {
  3692. if (rtpdebug) {
  3693. ast_debug(1, "Forcing Marker bit, because SSRC has changed\n");
  3694. }
  3695. mark = 1;
  3696. }
  3697. f = ast_frisolate(&srcupdate);
  3698. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  3699. rtp->seedrxseqno = 0;
  3700. rtp->rxcount = 0;
  3701. rtp->cycles = 0;
  3702. rtp->lastrxseqno = 0;
  3703. rtp->last_seqno = 0;
  3704. rtp->last_end_timestamp = 0;
  3705. if (rtp->rtcp) {
  3706. rtp->rtcp->expected_prior = 0;
  3707. rtp->rtcp->received_prior = 0;
  3708. }
  3709. }
  3710. rtp->rxssrc = ssrc;
  3711. /* Remove any padding bytes that may be present */
  3712. if (padding) {
  3713. res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
  3714. }
  3715. /* Skip over any CSRC fields */
  3716. if (cc) {
  3717. hdrlen += cc * 4;
  3718. }
  3719. /* Look for any RTP extensions, currently we do not support any */
  3720. if (ext) {
  3721. hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
  3722. hdrlen += 4;
  3723. if (option_debug) {
  3724. unsigned int profile;
  3725. profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
  3726. if (profile == 0x505a)
  3727. ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
  3728. else
  3729. ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
  3730. }
  3731. }
  3732. /* Make sure after we potentially mucked with the header length that it is once again valid */
  3733. if (res < hdrlen) {
  3734. ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d\n", res, hdrlen);
  3735. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  3736. }
  3737. rtp->rxcount++;
  3738. if (rtp->rxcount == 1) {
  3739. rtp->seedrxseqno = seqno;
  3740. }
  3741. /* Do not schedule RR if RTCP isn't run */
  3742. if (rtp->rtcp && !ast_sockaddr_isnull(&rtp->rtcp->them) && rtp->rtcp->schedid < 1) {
  3743. /* Schedule transmission of Receiver Report */
  3744. ao2_ref(instance, +1);
  3745. rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
  3746. if (rtp->rtcp->schedid < 0) {
  3747. ao2_ref(instance, -1);
  3748. ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
  3749. }
  3750. }
  3751. if ((int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
  3752. rtp->cycles += RTP_SEQ_MOD;
  3753. prev_seqno = rtp->lastrxseqno;
  3754. rtp->lastrxseqno = seqno;
  3755. if (!rtp->themssrc) {
  3756. rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
  3757. }
  3758. if (rtp_debug_test_addr(&addr)) {
  3759. ast_verbose("Got RTP packet from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6d)\n",
  3760. ast_sockaddr_stringify(&addr),
  3761. payloadtype, seqno, timestamp,res - hdrlen);
  3762. }
  3763. payload = ast_rtp_codecs_get_payload(ast_rtp_instance_get_codecs(instance), payloadtype);
  3764. /* If the payload is not actually an Asterisk one but a special one pass it off to the respective handler */
  3765. if (!payload->asterisk_format) {
  3766. struct ast_frame *f = NULL;
  3767. if (payload->rtp_code == AST_RTP_DTMF) {
  3768. /* process_dtmf_rfc2833 may need to return multiple frames. We do this
  3769. * by passing the pointer to the frame list to it so that the method
  3770. * can append frames to the list as needed.
  3771. */
  3772. process_dtmf_rfc2833(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark, &frames);
  3773. } else if (payload->rtp_code == AST_RTP_CISCO_DTMF) {
  3774. f = process_dtmf_cisco(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
  3775. } else if (payload->rtp_code == AST_RTP_CN) {
  3776. f = process_cn_rfc3389(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
  3777. } else {
  3778. ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n",
  3779. payloadtype,
  3780. ast_sockaddr_stringify(&remote_address));
  3781. }
  3782. if (f) {
  3783. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  3784. }
  3785. /* Even if no frame was returned by one of the above methods,
  3786. * we may have a frame to return in our frame list
  3787. */
  3788. if (!AST_LIST_EMPTY(&frames)) {
  3789. return AST_LIST_FIRST(&frames);
  3790. }
  3791. return &ast_null_frame;
  3792. }
  3793. ao2_replace(rtp->lastrxformat, payload->format);
  3794. ao2_replace(rtp->f.subclass.format, payload->format);
  3795. switch (ast_format_get_type(rtp->f.subclass.format)) {
  3796. case AST_MEDIA_TYPE_AUDIO:
  3797. rtp->f.frametype = AST_FRAME_VOICE;
  3798. break;
  3799. case AST_MEDIA_TYPE_VIDEO:
  3800. rtp->f.frametype = AST_FRAME_VIDEO;
  3801. break;
  3802. case AST_MEDIA_TYPE_TEXT:
  3803. rtp->f.frametype = AST_FRAME_TEXT;
  3804. break;
  3805. case AST_MEDIA_TYPE_IMAGE:
  3806. /* Fall through */
  3807. default:
  3808. ast_log(LOG_WARNING, "Unknown or unsupported media type: %s\n",
  3809. ast_codec_media_type2str(ast_format_get_type(rtp->f.subclass.format)));
  3810. return &ast_null_frame;
  3811. }
  3812. rtp->rxseqno = seqno;
  3813. if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
  3814. rtp->dtmf_timeout = 0;
  3815. if (rtp->resp) {
  3816. struct ast_frame *f;
  3817. f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0);
  3818. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.format)), ast_tv(0, 0));
  3819. rtp->resp = 0;
  3820. rtp->dtmf_timeout = rtp->dtmf_duration = 0;
  3821. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  3822. return AST_LIST_FIRST(&frames);
  3823. }
  3824. }
  3825. rtp->lastrxts = timestamp;
  3826. rtp->f.src = "RTP";
  3827. rtp->f.mallocd = 0;
  3828. rtp->f.datalen = res - hdrlen;
  3829. rtp->f.data.ptr = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
  3830. rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
  3831. rtp->f.seqno = seqno;
  3832. if ((ast_format_cmp(rtp->f.subclass.format, ast_format_t140) == AST_FORMAT_CMP_EQUAL)
  3833. && ((int)seqno - (prev_seqno + 1) > 0)
  3834. && ((int)seqno - (prev_seqno + 1) < 10)) {
  3835. unsigned char *data = rtp->f.data.ptr;
  3836. memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
  3837. rtp->f.datalen +=3;
  3838. *data++ = 0xEF;
  3839. *data++ = 0xBF;
  3840. *data = 0xBD;
  3841. }
  3842. if (ast_format_cmp(rtp->f.subclass.format, ast_format_t140_red) == AST_FORMAT_CMP_EQUAL) {
  3843. unsigned char *data = rtp->f.data.ptr;
  3844. unsigned char *header_end;
  3845. int num_generations;
  3846. int header_length;
  3847. int len;
  3848. int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
  3849. int x;
  3850. ao2_replace(rtp->f.subclass.format, ast_format_t140);
  3851. header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
  3852. if (header_end == NULL) {
  3853. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  3854. }
  3855. header_end++;
  3856. header_length = header_end - data;
  3857. num_generations = header_length / 4;
  3858. len = header_length;
  3859. if (!diff) {
  3860. for (x = 0; x < num_generations; x++)
  3861. len += data[x * 4 + 3];
  3862. if (!(rtp->f.datalen - len))
  3863. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  3864. rtp->f.data.ptr += len;
  3865. rtp->f.datalen -= len;
  3866. } else if (diff > num_generations && diff < 10) {
  3867. len -= 3;
  3868. rtp->f.data.ptr += len;
  3869. rtp->f.datalen -= len;
  3870. data = rtp->f.data.ptr;
  3871. *data++ = 0xEF;
  3872. *data++ = 0xBF;
  3873. *data = 0xBD;
  3874. } else {
  3875. for ( x = 0; x < num_generations - diff; x++)
  3876. len += data[x * 4 + 3];
  3877. rtp->f.data.ptr += len;
  3878. rtp->f.datalen -= len;
  3879. }
  3880. }
  3881. if (ast_format_get_type(rtp->f.subclass.format) == AST_MEDIA_TYPE_AUDIO) {
  3882. rtp->f.samples = ast_codec_samples_count(&rtp->f);
  3883. if (ast_format_cache_is_slinear(rtp->f.subclass.format)) {
  3884. ast_frame_byteswap_be(&rtp->f);
  3885. }
  3886. calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
  3887. /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
  3888. ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
  3889. rtp->f.ts = timestamp / (rtp_get_rate(rtp->f.subclass.format) / 1000);
  3890. rtp->f.len = rtp->f.samples / ((ast_format_get_sample_rate(rtp->f.subclass.format) / 1000));
  3891. } else if (ast_format_get_type(rtp->f.subclass.format) == AST_MEDIA_TYPE_VIDEO) {
  3892. /* Video -- samples is # of samples vs. 90000 */
  3893. if (!rtp->lastividtimestamp)
  3894. rtp->lastividtimestamp = timestamp;
  3895. rtp->f.samples = timestamp - rtp->lastividtimestamp;
  3896. rtp->lastividtimestamp = timestamp;
  3897. rtp->f.delivery.tv_sec = 0;
  3898. rtp->f.delivery.tv_usec = 0;
  3899. /* Pass the RTP marker bit as bit */
  3900. rtp->f.subclass.frame_ending = mark;
  3901. } else if (ast_format_get_type(rtp->f.subclass.format) == AST_MEDIA_TYPE_TEXT) {
  3902. /* TEXT -- samples is # of samples vs. 1000 */
  3903. if (!rtp->lastitexttimestamp)
  3904. rtp->lastitexttimestamp = timestamp;
  3905. rtp->f.samples = timestamp - rtp->lastitexttimestamp;
  3906. rtp->lastitexttimestamp = timestamp;
  3907. rtp->f.delivery.tv_sec = 0;
  3908. rtp->f.delivery.tv_usec = 0;
  3909. } else {
  3910. ast_log(LOG_WARNING, "Unknown or unsupported media type: %s\n",
  3911. ast_codec_media_type2str(ast_format_get_type(rtp->f.subclass.format)));
  3912. return &ast_null_frame;;
  3913. }
  3914. AST_LIST_INSERT_TAIL(&frames, &rtp->f, frame_list);
  3915. return AST_LIST_FIRST(&frames);
  3916. }
  3917. static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
  3918. {
  3919. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3920. if (property == AST_RTP_PROPERTY_RTCP) {
  3921. if (value) {
  3922. if (rtp->rtcp) {
  3923. ast_debug(1, "Ignoring duplicate RTCP property on RTP instance '%p'\n", instance);
  3924. return;
  3925. }
  3926. /* Setup RTCP to be activated on the next RTP write */
  3927. if (!(rtp->rtcp = ast_calloc(1, sizeof(*rtp->rtcp)))) {
  3928. return;
  3929. }
  3930. /* Grab the IP address and port we are going to use */
  3931. ast_rtp_instance_get_local_address(instance, &rtp->rtcp->us);
  3932. ast_sockaddr_set_port(&rtp->rtcp->us,
  3933. ast_sockaddr_port(&rtp->rtcp->us) + 1);
  3934. if ((rtp->rtcp->s =
  3935. create_new_socket("RTCP",
  3936. ast_sockaddr_is_ipv4(&rtp->rtcp->us) ?
  3937. AF_INET :
  3938. ast_sockaddr_is_ipv6(&rtp->rtcp->us) ?
  3939. AF_INET6 : -1)) < 0) {
  3940. ast_debug(1, "Failed to create a new socket for RTCP on instance '%p'\n", instance);
  3941. ast_free(rtp->rtcp);
  3942. rtp->rtcp = NULL;
  3943. return;
  3944. }
  3945. /* 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 */
  3946. if (ast_bind(rtp->rtcp->s, &rtp->rtcp->us)) {
  3947. ast_debug(1, "Failed to setup RTCP on RTP instance '%p'\n", instance);
  3948. close(rtp->rtcp->s);
  3949. ast_free(rtp->rtcp);
  3950. rtp->rtcp = NULL;
  3951. return;
  3952. }
  3953. ast_debug(1, "Setup RTCP on RTP instance '%p'\n", instance);
  3954. rtp->rtcp->schedid = -1;
  3955. #ifdef HAVE_PJPROJECT
  3956. if (rtp->ice) {
  3957. rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us, ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP, TRANSPORT_SOCKET_RTCP);
  3958. }
  3959. #endif
  3960. #ifdef HAVE_OPENSSL_SRTP
  3961. dtls_setup_rtcp(instance);
  3962. #endif
  3963. return;
  3964. } else {
  3965. if (rtp->rtcp) {
  3966. if (rtp->rtcp->schedid > 0) {
  3967. if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
  3968. /* Successfully cancelled scheduler entry. */
  3969. ao2_ref(instance, -1);
  3970. } else {
  3971. /* Unable to cancel scheduler entry */
  3972. ast_debug(1, "Failed to tear down RTCP on RTP instance '%p'\n", instance);
  3973. return;
  3974. }
  3975. rtp->rtcp->schedid = -1;
  3976. }
  3977. close(rtp->rtcp->s);
  3978. #ifdef HAVE_OPENSSL_SRTP
  3979. if (rtp->rtcp->dtls.ssl) {
  3980. SSL_free(rtp->rtcp->dtls.ssl);
  3981. }
  3982. #endif
  3983. ast_free(rtp->rtcp);
  3984. rtp->rtcp = NULL;
  3985. }
  3986. return;
  3987. }
  3988. }
  3989. return;
  3990. }
  3991. static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp)
  3992. {
  3993. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3994. return rtcp ? (rtp->rtcp ? rtp->rtcp->s : -1) : rtp->s;
  3995. }
  3996. static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
  3997. {
  3998. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  3999. if (rtp->rtcp) {
  4000. ast_debug(1, "Setting RTCP address on RTP instance '%p'\n", instance);
  4001. ast_sockaddr_copy(&rtp->rtcp->them, addr);
  4002. if (!ast_sockaddr_isnull(addr)) {
  4003. ast_sockaddr_set_port(&rtp->rtcp->them,
  4004. ast_sockaddr_port(addr) + 1);
  4005. }
  4006. }
  4007. rtp->rxseqno = 0;
  4008. if (strictrtp && rtp->strict_rtp_state != STRICT_RTP_OPEN) {
  4009. rtp->strict_rtp_state = STRICT_RTP_LEARN;
  4010. rtp_learning_seq_init(&rtp->rtp_source_learn, rtp->seqno);
  4011. }
  4012. return;
  4013. }
  4014. /*! \brief Write t140 redundacy frame
  4015. * \param data primary data to be buffered
  4016. */
  4017. static int red_write(const void *data)
  4018. {
  4019. struct ast_rtp_instance *instance = (struct ast_rtp_instance*) data;
  4020. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4021. ast_rtp_write(instance, &rtp->red->t140);
  4022. return 1;
  4023. }
  4024. static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
  4025. {
  4026. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4027. int x;
  4028. if (!(rtp->red = ast_calloc(1, sizeof(*rtp->red)))) {
  4029. return -1;
  4030. }
  4031. rtp->red->t140.frametype = AST_FRAME_TEXT;
  4032. ao2_replace(rtp->red->t140.subclass.format, ast_format_t140_red);
  4033. rtp->red->t140.data.ptr = &rtp->red->buf_data;
  4034. rtp->red->t140.ts = 0;
  4035. rtp->red->t140red = rtp->red->t140;
  4036. rtp->red->t140red.data.ptr = &rtp->red->t140red_data;
  4037. rtp->red->t140red.datalen = 0;
  4038. rtp->red->ti = buffer_time;
  4039. rtp->red->num_gen = generations;
  4040. rtp->red->hdrlen = generations * 4 + 1;
  4041. rtp->red->prev_ts = 0;
  4042. for (x = 0; x < generations; x++) {
  4043. rtp->red->pt[x] = payloads[x];
  4044. rtp->red->pt[x] |= 1 << 7; /* mark redundant generations pt */
  4045. rtp->red->t140red_data[x*4] = rtp->red->pt[x];
  4046. }
  4047. rtp->red->t140red_data[x*4] = rtp->red->pt[x] = payloads[x]; /* primary pt */
  4048. rtp->red->schedid = ast_sched_add(rtp->sched, generations, red_write, instance);
  4049. rtp->red->t140.datalen = 0;
  4050. return 0;
  4051. }
  4052. static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
  4053. {
  4054. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4055. if (frame->datalen > -1) {
  4056. struct rtp_red *red = rtp->red;
  4057. memcpy(&red->buf_data[red->t140.datalen], frame->data.ptr, frame->datalen);
  4058. red->t140.datalen += frame->datalen;
  4059. red->t140.ts = frame->ts;
  4060. }
  4061. return 0;
  4062. }
  4063. static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1)
  4064. {
  4065. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance0);
  4066. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  4067. return 0;
  4068. }
  4069. static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
  4070. {
  4071. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4072. if (!rtp->rtcp) {
  4073. return -1;
  4074. }
  4075. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXCOUNT, -1, stats->txcount, rtp->txcount);
  4076. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXCOUNT, -1, stats->rxcount, rtp->rxcount);
  4077. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->txploss, rtp->rtcp->reported_lost);
  4078. 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);
  4079. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_maxrxploss, rtp->rtcp->reported_maxlost);
  4080. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_minrxploss, rtp->rtcp->reported_minlost);
  4081. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_normdevrxploss, rtp->rtcp->reported_normdev_lost);
  4082. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_stdevrxploss, rtp->rtcp->reported_stdev_lost);
  4083. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_maxrxploss, rtp->rtcp->maxrxlost);
  4084. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_minrxploss, rtp->rtcp->minrxlost);
  4085. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_normdevrxploss, rtp->rtcp->normdev_rxlost);
  4086. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_stdevrxploss, rtp->rtcp->stdev_rxlost);
  4087. AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_LOSS);
  4088. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->txjitter, rtp->rxjitter);
  4089. 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);
  4090. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_maxjitter, rtp->rtcp->reported_maxjitter);
  4091. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_minjitter, rtp->rtcp->reported_minjitter);
  4092. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_normdevjitter, rtp->rtcp->reported_normdev_jitter);
  4093. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_stdevjitter, rtp->rtcp->reported_stdev_jitter);
  4094. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_maxjitter, rtp->rtcp->maxrxjitter);
  4095. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_minjitter, rtp->rtcp->minrxjitter);
  4096. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_normdevjitter, rtp->rtcp->normdev_rxjitter);
  4097. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_stdevjitter, rtp->rtcp->stdev_rxjitter);
  4098. AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_JITTER);
  4099. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->rtt, rtp->rtcp->rtt);
  4100. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MAX_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->maxrtt, rtp->rtcp->maxrtt);
  4101. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MIN_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->minrtt, rtp->rtcp->minrtt);
  4102. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_NORMDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->normdevrtt, rtp->rtcp->normdevrtt);
  4103. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_STDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->stdevrtt, rtp->rtcp->stdevrtt);
  4104. AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_RTT);
  4105. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_SSRC, -1, stats->local_ssrc, rtp->ssrc);
  4106. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_SSRC, -1, stats->remote_ssrc, rtp->themssrc);
  4107. AST_RTP_STAT_STRCPY(AST_RTP_INSTANCE_STAT_CHANNEL_UNIQUEID, -1, stats->channel_uniqueid, ast_rtp_instance_get_channel_id(instance));
  4108. return 0;
  4109. }
  4110. static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1)
  4111. {
  4112. /* If both sides are not using the same method of DTMF transmission
  4113. * (ie: one is RFC2833, other is INFO... then we can not do direct media.
  4114. * --------------------------------------------------
  4115. * | DTMF Mode | HAS_DTMF | Accepts Begin Frames |
  4116. * |-----------|------------|-----------------------|
  4117. * | Inband | False | True |
  4118. * | RFC2833 | True | True |
  4119. * | SIP INFO | False | False |
  4120. * --------------------------------------------------
  4121. */
  4122. return (((ast_rtp_instance_get_prop(instance0, AST_RTP_PROPERTY_DTMF) != ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_DTMF)) ||
  4123. (!ast_channel_tech(chan0)->send_digit_begin != !ast_channel_tech(chan1)->send_digit_begin)) ? 0 : 1);
  4124. }
  4125. static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username)
  4126. {
  4127. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4128. struct sockaddr_in suggestion_tmp;
  4129. ast_sockaddr_to_sin(suggestion, &suggestion_tmp);
  4130. ast_stun_request(rtp->s, &suggestion_tmp, username, NULL);
  4131. ast_sockaddr_from_sin(suggestion, &suggestion_tmp);
  4132. }
  4133. static void ast_rtp_stop(struct ast_rtp_instance *instance)
  4134. {
  4135. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4136. struct ast_sockaddr addr = { {0,} };
  4137. #ifdef HAVE_OPENSSL_SRTP
  4138. AST_SCHED_DEL_UNREF(rtp->sched, rtp->rekeyid, ao2_ref(instance, -1));
  4139. ast_mutex_lock(&rtp->dtls_timer_lock);
  4140. AST_SCHED_DEL_UNREF(rtp->sched, rtp->dtlstimerid, ao2_ref(instance, -1));
  4141. ast_mutex_unlock(&rtp->dtls_timer_lock);
  4142. #endif
  4143. if (rtp->rtcp && rtp->rtcp->schedid > 0) {
  4144. if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
  4145. /* successfully cancelled scheduler entry. */
  4146. ao2_ref(instance, -1);
  4147. }
  4148. rtp->rtcp->schedid = -1;
  4149. }
  4150. if (rtp->red) {
  4151. AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
  4152. free(rtp->red);
  4153. rtp->red = NULL;
  4154. }
  4155. ast_rtp_instance_set_remote_address(instance, &addr);
  4156. if (rtp->rtcp) {
  4157. ast_sockaddr_setnull(&rtp->rtcp->them);
  4158. }
  4159. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  4160. }
  4161. static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
  4162. {
  4163. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4164. return ast_set_qos(rtp->s, tos, cos, desc);
  4165. }
  4166. /*! \brief generate comfort noice (CNG) */
  4167. static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level)
  4168. {
  4169. unsigned int *rtpheader;
  4170. int hdrlen = 12;
  4171. int res, payload = 0;
  4172. char data[256];
  4173. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4174. struct ast_sockaddr remote_address = { {0,} };
  4175. int ice;
  4176. ast_rtp_instance_get_remote_address(instance, &remote_address);
  4177. if (ast_sockaddr_isnull(&remote_address)) {
  4178. return -1;
  4179. }
  4180. payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_CN);
  4181. level = 127 - (level & 0x7f);
  4182. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  4183. /* Get a pointer to the header */
  4184. rtpheader = (unsigned int *)data;
  4185. rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
  4186. rtpheader[1] = htonl(rtp->lastts);
  4187. rtpheader[2] = htonl(rtp->ssrc);
  4188. data[12] = level;
  4189. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 1, 0, &remote_address, &ice);
  4190. if (res < 0) {
  4191. ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s: %s\n", ast_sockaddr_stringify(&remote_address), strerror(errno));
  4192. return res;
  4193. }
  4194. if (rtp_debug_test_addr(&remote_address)) {
  4195. ast_verbose("Sent Comfort Noise RTP packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
  4196. ast_sockaddr_stringify(&remote_address),
  4197. ice ? " (via ICE)" : "",
  4198. AST_RTP_CN, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  4199. }
  4200. rtp->seqno++;
  4201. return res;
  4202. }
  4203. #ifdef HAVE_OPENSSL_SRTP
  4204. static int ast_rtp_activate(struct ast_rtp_instance *instance)
  4205. {
  4206. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  4207. /* If ICE negotiation is enabled the DTLS Handshake will be performed upon completion of it */
  4208. #ifdef USE_PJPROJECT
  4209. if (rtp->ice) {
  4210. return 0;
  4211. }
  4212. #endif
  4213. dtls_perform_handshake(instance, &rtp->dtls, 0);
  4214. if (rtp->rtcp) {
  4215. dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
  4216. }
  4217. return 0;
  4218. }
  4219. #endif
  4220. static char *rtp_do_debug_ip(struct ast_cli_args *a)
  4221. {
  4222. char *arg = ast_strdupa(a->argv[4]);
  4223. char *debughost = NULL;
  4224. char *debugport = NULL;
  4225. if (!ast_sockaddr_parse(&rtpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
  4226. ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
  4227. return CLI_FAILURE;
  4228. }
  4229. rtpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
  4230. ast_cli(a->fd, "RTP Debugging Enabled for address: %s\n",
  4231. ast_sockaddr_stringify(&rtpdebugaddr));
  4232. rtpdebug = 1;
  4233. return CLI_SUCCESS;
  4234. }
  4235. static char *rtcp_do_debug_ip(struct ast_cli_args *a)
  4236. {
  4237. char *arg = ast_strdupa(a->argv[4]);
  4238. char *debughost = NULL;
  4239. char *debugport = NULL;
  4240. if (!ast_sockaddr_parse(&rtcpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
  4241. ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
  4242. return CLI_FAILURE;
  4243. }
  4244. rtcpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
  4245. ast_cli(a->fd, "RTCP Debugging Enabled for address: %s\n",
  4246. ast_sockaddr_stringify(&rtcpdebugaddr));
  4247. rtcpdebug = 1;
  4248. return CLI_SUCCESS;
  4249. }
  4250. static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  4251. {
  4252. switch (cmd) {
  4253. case CLI_INIT:
  4254. e->command = "rtp set debug {on|off|ip}";
  4255. e->usage =
  4256. "Usage: rtp set debug {on|off|ip host[:port]}\n"
  4257. " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
  4258. " specified, limit the dumped packets to those to and from\n"
  4259. " the specified 'host' with optional port.\n";
  4260. return NULL;
  4261. case CLI_GENERATE:
  4262. return NULL;
  4263. }
  4264. if (a->argc == e->args) { /* set on or off */
  4265. if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
  4266. rtpdebug = 1;
  4267. memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
  4268. ast_cli(a->fd, "RTP Debugging Enabled\n");
  4269. return CLI_SUCCESS;
  4270. } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
  4271. rtpdebug = 0;
  4272. ast_cli(a->fd, "RTP Debugging Disabled\n");
  4273. return CLI_SUCCESS;
  4274. }
  4275. } else if (a->argc == e->args +1) { /* ip */
  4276. return rtp_do_debug_ip(a);
  4277. }
  4278. return CLI_SHOWUSAGE; /* default, failure */
  4279. }
  4280. static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  4281. {
  4282. switch (cmd) {
  4283. case CLI_INIT:
  4284. e->command = "rtcp set debug {on|off|ip}";
  4285. e->usage =
  4286. "Usage: rtcp set debug {on|off|ip host[:port]}\n"
  4287. " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
  4288. " specified, limit the dumped packets to those to and from\n"
  4289. " the specified 'host' with optional port.\n";
  4290. return NULL;
  4291. case CLI_GENERATE:
  4292. return NULL;
  4293. }
  4294. if (a->argc == e->args) { /* set on or off */
  4295. if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
  4296. rtcpdebug = 1;
  4297. memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
  4298. ast_cli(a->fd, "RTCP Debugging Enabled\n");
  4299. return CLI_SUCCESS;
  4300. } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
  4301. rtcpdebug = 0;
  4302. ast_cli(a->fd, "RTCP Debugging Disabled\n");
  4303. return CLI_SUCCESS;
  4304. }
  4305. } else if (a->argc == e->args +1) { /* ip */
  4306. return rtcp_do_debug_ip(a);
  4307. }
  4308. return CLI_SHOWUSAGE; /* default, failure */
  4309. }
  4310. static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  4311. {
  4312. switch (cmd) {
  4313. case CLI_INIT:
  4314. e->command = "rtcp set stats {on|off}";
  4315. e->usage =
  4316. "Usage: rtcp set stats {on|off}\n"
  4317. " Enable/Disable dumping of RTCP stats.\n";
  4318. return NULL;
  4319. case CLI_GENERATE:
  4320. return NULL;
  4321. }
  4322. if (a->argc != e->args)
  4323. return CLI_SHOWUSAGE;
  4324. if (!strncasecmp(a->argv[e->args-1], "on", 2))
  4325. rtcpstats = 1;
  4326. else if (!strncasecmp(a->argv[e->args-1], "off", 3))
  4327. rtcpstats = 0;
  4328. else
  4329. return CLI_SHOWUSAGE;
  4330. ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
  4331. return CLI_SUCCESS;
  4332. }
  4333. static struct ast_cli_entry cli_rtp[] = {
  4334. AST_CLI_DEFINE(handle_cli_rtp_set_debug, "Enable/Disable RTP debugging"),
  4335. AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging"),
  4336. AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats"),
  4337. };
  4338. static int rtp_reload(int reload)
  4339. {
  4340. struct ast_config *cfg;
  4341. const char *s;
  4342. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  4343. cfg = ast_config_load2("rtp.conf", "rtp", config_flags);
  4344. if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
  4345. return 0;
  4346. }
  4347. rtpstart = DEFAULT_RTP_START;
  4348. rtpend = DEFAULT_RTP_END;
  4349. dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  4350. strictrtp = DEFAULT_STRICT_RTP;
  4351. learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL;
  4352. /** This resource is not "reloaded" so much as unloaded and loaded again.
  4353. * In the case of the TURN related variables, the memory referenced by a
  4354. * previously loaded instance *should* have been released when the
  4355. * corresponding pool was destroyed. If at some point in the future this
  4356. * resource were to support ACTUAL live reconfiguration and did NOT release
  4357. * the pool this will cause a small memory leak.
  4358. */
  4359. #ifdef HAVE_PJPROJECT
  4360. icesupport = DEFAULT_ICESUPPORT;
  4361. turnport = DEFAULT_TURN_PORT;
  4362. memset(&stunaddr, 0, sizeof(stunaddr));
  4363. turnaddr = pj_str(NULL);
  4364. turnusername = pj_str(NULL);
  4365. turnpassword = pj_str(NULL);
  4366. #endif
  4367. if (cfg) {
  4368. if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
  4369. rtpstart = atoi(s);
  4370. if (rtpstart < MINIMUM_RTP_PORT)
  4371. rtpstart = MINIMUM_RTP_PORT;
  4372. if (rtpstart > MAXIMUM_RTP_PORT)
  4373. rtpstart = MAXIMUM_RTP_PORT;
  4374. }
  4375. if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
  4376. rtpend = atoi(s);
  4377. if (rtpend < MINIMUM_RTP_PORT)
  4378. rtpend = MINIMUM_RTP_PORT;
  4379. if (rtpend > MAXIMUM_RTP_PORT)
  4380. rtpend = MAXIMUM_RTP_PORT;
  4381. }
  4382. if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
  4383. rtcpinterval = atoi(s);
  4384. if (rtcpinterval == 0)
  4385. rtcpinterval = 0; /* Just so we're clear... it's zero */
  4386. if (rtcpinterval < RTCP_MIN_INTERVALMS)
  4387. rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
  4388. if (rtcpinterval > RTCP_MAX_INTERVALMS)
  4389. rtcpinterval = RTCP_MAX_INTERVALMS;
  4390. }
  4391. if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
  4392. #ifdef SO_NO_CHECK
  4393. nochecksums = ast_false(s) ? 1 : 0;
  4394. #else
  4395. if (ast_false(s))
  4396. ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
  4397. #endif
  4398. }
  4399. if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
  4400. dtmftimeout = atoi(s);
  4401. if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
  4402. ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
  4403. dtmftimeout, DEFAULT_DTMF_TIMEOUT);
  4404. dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  4405. };
  4406. }
  4407. if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
  4408. strictrtp = ast_true(s);
  4409. }
  4410. if ((s = ast_variable_retrieve(cfg, "general", "probation"))) {
  4411. if ((sscanf(s, "%d", &learning_min_sequential) <= 0) || learning_min_sequential <= 0) {
  4412. ast_log(LOG_WARNING, "Value for 'probation' could not be read, using default of '%d' instead\n",
  4413. DEFAULT_LEARNING_MIN_SEQUENTIAL);
  4414. }
  4415. }
  4416. #ifdef HAVE_PJPROJECT
  4417. if ((s = ast_variable_retrieve(cfg, "general", "icesupport"))) {
  4418. icesupport = ast_true(s);
  4419. }
  4420. if ((s = ast_variable_retrieve(cfg, "general", "stunaddr"))) {
  4421. stunaddr.sin_port = htons(STANDARD_STUN_PORT);
  4422. if (ast_parse_arg(s, PARSE_INADDR, &stunaddr)) {
  4423. ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", s);
  4424. }
  4425. }
  4426. if ((s = ast_variable_retrieve(cfg, "general", "turnaddr"))) {
  4427. struct sockaddr_in addr;
  4428. addr.sin_port = htons(DEFAULT_TURN_PORT);
  4429. if (ast_parse_arg(s, PARSE_INADDR, &addr)) {
  4430. ast_log(LOG_WARNING, "Invalid TURN server address: %s\n", s);
  4431. } else {
  4432. pj_strdup2_with_null(pool, &turnaddr, ast_inet_ntoa(addr.sin_addr));
  4433. /* ntohs() is not a bug here. The port number is used in host byte order with
  4434. * a pjnat API. */
  4435. turnport = ntohs(addr.sin_port);
  4436. }
  4437. }
  4438. if ((s = ast_variable_retrieve(cfg, "general", "turnusername"))) {
  4439. pj_strdup2_with_null(pool, &turnusername, s);
  4440. }
  4441. if ((s = ast_variable_retrieve(cfg, "general", "turnpassword"))) {
  4442. pj_strdup2_with_null(pool, &turnpassword, s);
  4443. }
  4444. #endif
  4445. ast_config_destroy(cfg);
  4446. }
  4447. if (rtpstart >= rtpend) {
  4448. ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
  4449. rtpstart = DEFAULT_RTP_START;
  4450. rtpend = DEFAULT_RTP_END;
  4451. }
  4452. ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
  4453. return 0;
  4454. }
  4455. static int reload_module(void)
  4456. {
  4457. rtp_reload(1);
  4458. return 0;
  4459. }
  4460. #ifdef HAVE_PJPROJECT
  4461. static void rtp_terminate_pjproject(void)
  4462. {
  4463. pj_thread_register_check();
  4464. if (timer_thread) {
  4465. timer_terminate = 1;
  4466. pj_thread_join(timer_thread);
  4467. pj_thread_destroy(timer_thread);
  4468. }
  4469. pj_caching_pool_destroy(&cachingpool);
  4470. pj_shutdown();
  4471. }
  4472. #endif
  4473. static int load_module(void)
  4474. {
  4475. #ifdef HAVE_PJPROJECT
  4476. pj_lock_t *lock;
  4477. if (pj_init() != PJ_SUCCESS) {
  4478. return AST_MODULE_LOAD_DECLINE;
  4479. }
  4480. if (pjlib_util_init() != PJ_SUCCESS) {
  4481. rtp_terminate_pjproject();
  4482. return AST_MODULE_LOAD_DECLINE;
  4483. }
  4484. if (pjnath_init() != PJ_SUCCESS) {
  4485. rtp_terminate_pjproject();
  4486. return AST_MODULE_LOAD_DECLINE;
  4487. }
  4488. pj_caching_pool_init(&cachingpool, &pj_pool_factory_default_policy, 0);
  4489. pool = pj_pool_create(&cachingpool.factory, "timer", 512, 512, NULL);
  4490. if (pj_timer_heap_create(pool, 100, &timer_heap) != PJ_SUCCESS) {
  4491. rtp_terminate_pjproject();
  4492. return AST_MODULE_LOAD_DECLINE;
  4493. }
  4494. if (pj_lock_create_recursive_mutex(pool, "rtp%p", &lock) != PJ_SUCCESS) {
  4495. rtp_terminate_pjproject();
  4496. return AST_MODULE_LOAD_DECLINE;
  4497. }
  4498. pj_timer_heap_set_lock(timer_heap, lock, PJ_TRUE);
  4499. if (pj_thread_create(pool, "timer", &timer_worker_thread, NULL, 0, 0, &timer_thread) != PJ_SUCCESS) {
  4500. rtp_terminate_pjproject();
  4501. return AST_MODULE_LOAD_DECLINE;
  4502. }
  4503. #endif
  4504. if (ast_rtp_engine_register(&asterisk_rtp_engine)) {
  4505. #ifdef HAVE_PJPROJECT
  4506. rtp_terminate_pjproject();
  4507. #endif
  4508. return AST_MODULE_LOAD_DECLINE;
  4509. }
  4510. if (ast_cli_register_multiple(cli_rtp, ARRAY_LEN(cli_rtp))) {
  4511. #ifdef HAVE_PJPROJECT
  4512. ast_rtp_engine_unregister(&asterisk_rtp_engine);
  4513. rtp_terminate_pjproject();
  4514. #endif
  4515. return AST_MODULE_LOAD_DECLINE;
  4516. }
  4517. rtp_reload(0);
  4518. return AST_MODULE_LOAD_SUCCESS;
  4519. }
  4520. static int unload_module(void)
  4521. {
  4522. ast_rtp_engine_unregister(&asterisk_rtp_engine);
  4523. ast_cli_unregister_multiple(cli_rtp, ARRAY_LEN(cli_rtp));
  4524. #ifdef HAVE_PJPROJECT
  4525. pj_thread_register_check();
  4526. rtp_terminate_pjproject();
  4527. #endif
  4528. return 0;
  4529. }
  4530. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk RTP Stack",
  4531. .support_level = AST_MODULE_SUPPORT_CORE,
  4532. .load = load_module,
  4533. .unload = unload_module,
  4534. .reload = reload_module,
  4535. .load_pri = AST_MODPRI_CHANNEL_DEPEND,
  4536. );