chan_sip.c 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2012, 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. * \brief Implementation of Session Initiation Protocol
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. *
  24. * See Also:
  25. * \arg \ref AstCREDITS
  26. *
  27. * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
  28. * Configuration file \link Config_sip sip.conf \endlink
  29. *
  30. * ********** IMPORTANT *
  31. * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
  32. * settings, dialplan commands and dialplans apps/functions
  33. * See \ref sip_tcp_tls
  34. *
  35. *
  36. * ******** General TODO:s
  37. * \todo Better support of forking
  38. * \todo VIA branch tag transaction checking
  39. * \todo Transaction support
  40. *
  41. * ******** Wishlist: Improvements
  42. * - Support of SIP domains for devices, so that we match on username\@domain in the From: header
  43. * - Connect registrations with a specific device on the incoming call. It's not done
  44. * automatically in Asterisk
  45. *
  46. * \ingroup channel_drivers
  47. *
  48. * \par Overview of the handling of SIP sessions
  49. * The SIP channel handles several types of SIP sessions, or dialogs,
  50. * not all of them being "telephone calls".
  51. * - Incoming calls that will be sent to the PBX core
  52. * - Outgoing calls, generated by the PBX
  53. * - SIP subscriptions and notifications of states and voicemail messages
  54. * - SIP registrations, both inbound and outbound
  55. * - SIP peer management (peerpoke, OPTIONS)
  56. * - SIP text messages
  57. *
  58. * In the SIP channel, there's a list of active SIP dialogs, which includes
  59. * all of these when they are active. "sip show channels" in the CLI will
  60. * show most of these, excluding subscriptions which are shown by
  61. * "sip show subscriptions"
  62. *
  63. * \par incoming packets
  64. * Incoming packets are received in the monitoring thread, then handled by
  65. * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
  66. * sipsock_read() function parses the packet and matches an existing
  67. * dialog or starts a new SIP dialog.
  68. *
  69. * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
  70. * If it is a response to an outbound request, the packet is sent to handle_response().
  71. * If it is a request, handle_incoming() sends it to one of a list of functions
  72. * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
  73. * sipsock_read locks the ast_channel if it exists (an active call) and
  74. * unlocks it after we have processed the SIP message.
  75. *
  76. * A new INVITE is sent to handle_request_invite(), that will end up
  77. * starting a new channel in the PBX, the new channel after that executing
  78. * in a separate channel thread. This is an incoming "call".
  79. * When the call is answered, either by a bridged channel or the PBX itself
  80. * the sip_answer() function is called.
  81. *
  82. * The actual media - Video or Audio - is mostly handled by the RTP subsystem
  83. * in rtp.c
  84. *
  85. * \par Outbound calls
  86. * Outbound calls are set up by the PBX through the sip_request_call()
  87. * function. After that, they are activated by sip_call().
  88. *
  89. * \par Hanging up
  90. * The PBX issues a hangup on both incoming and outgoing calls through
  91. * the sip_hangup() function
  92. */
  93. /*! \li \ref chan_sip.c uses configuration files \ref sip.conf and \ref sip_notify.conf
  94. * \addtogroup configuration_file
  95. */
  96. /*! \page sip.conf sip.conf
  97. * \verbinclude sip.conf.sample
  98. */
  99. /*! \page sip_notify.conf sip_notify.conf
  100. * \verbinclude sip_notify.conf.sample
  101. */
  102. /*!
  103. * \page sip_tcp_tls SIP TCP and TLS support
  104. *
  105. * \par tcpfixes TCP implementation changes needed
  106. * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
  107. * \todo Save TCP/TLS sessions in registry
  108. * If someone registers a SIPS uri, this forces us to set up a TLS connection back.
  109. * \todo Add TCP/TLS information to function SIPPEER and CHANNEL function
  110. * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
  111. * The tcpbindaddr config option should only be used to open ADDITIONAL ports
  112. * So we should propably go back to
  113. * bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
  114. * if tlsenable=yes, open TLS port (provided we also have cert)
  115. * tcpbindaddr = extra address for additional TCP connections
  116. * tlsbindaddr = extra address for additional TCP/TLS connections
  117. * udpbindaddr = extra address for additional UDP connections
  118. * These three options should take multiple IP/port pairs
  119. * Note: Since opening additional listen sockets is a *new* feature we do not have today
  120. * the XXXbindaddr options needs to be disabled until we have support for it
  121. *
  122. * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
  123. * thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
  124. * even if udp is the configured first transport.
  125. *
  126. * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
  127. * specially to communication with other peers (proxies).
  128. * \todo We need to test TCP sessions with SIP proxies and in regards
  129. * to the SIP outbound specs.
  130. * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
  131. *
  132. * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
  133. * message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
  134. * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
  135. * multiple domains in our TLS implementation, meaning one socket and one cert per domain
  136. * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
  137. * also considering outbound proxy options.
  138. * First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port: DNS naptr, srv, AAA)
  139. * Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
  140. * DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
  141. * Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
  142. * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
  143. * devices directly from the dialplan. UDP is only a fallback if no other method works,
  144. * in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
  145. * MTU (like INIVTE with video, audio and RTT) TCP should be preferred.
  146. *
  147. * When dialling unconfigured peers (with no port number) or devices in external domains
  148. * NAPTR records MUST be consulted to find configured transport. If they are not found,
  149. * SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
  150. * If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
  151. * \note this only applies if there's no outbound proxy configured for the session. If an outbound
  152. * proxy is configured, these procedures might apply for locating the proxy and determining
  153. * the transport to use for communication with the proxy.
  154. * \par Other bugs to fix ----
  155. * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
  156. * - sets TLS port as default for all TCP connections, unless other port is given in contact.
  157. * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
  158. * - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
  159. * a bad guess.
  160. * - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
  161. * get_destination(struct sip_pvt *p, struct sip_request *oreq)
  162. * - Doesn't store the information that we got an incoming SIPS request in the channel, so that
  163. * we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
  164. * fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
  165. * channel variable in the dialplan.
  166. * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
  167. * - As above, if we have a SIPS: uri in the refer-to header
  168. * - Does not check transport in refer_to uri.
  169. */
  170. /*** MODULEINFO
  171. <use type="module">res_crypto</use>
  172. <use type="module">res_http_websocket</use>
  173. <support_level>extended</support_level>
  174. ***/
  175. /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
  176. The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
  177. refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
  178. request at a negotiated interval. If a session refresh fails then all the entities that support Session-
  179. Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
  180. the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
  181. that do not support Session-Timers).
  182. The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
  183. per-peer settings override the global settings. The following new parameters have been
  184. added to the sip.conf file.
  185. session-timers=["accept", "originate", "refuse"]
  186. session-expires=[integer]
  187. session-minse=[integer]
  188. session-refresher=["uas", "uac"]
  189. The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
  190. Asterisk. The Asterisk can be configured in one of the following three modes:
  191. 1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
  192. made by remote end-points. A remote end-point can request Asterisk to engage
  193. session-timers by either sending it an INVITE request with a "Supported: timer"
  194. header in it or by responding to Asterisk's INVITE with a 200 OK that contains
  195. Session-Expires: header in it. In this mode, the Asterisk server does not
  196. request session-timers from remote end-points. This is the default mode.
  197. 2. Originate :: In the "originate" mode, the Asterisk server requests the remote
  198. end-points to activate session-timers in addition to honoring such requests
  199. made by the remote end-pints. In order to get as much protection as possible
  200. against hanging SIP channels due to network or end-point failures, Asterisk
  201. resends periodic re-INVITEs even if a remote end-point does not support
  202. the session-timers feature.
  203. 3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
  204. timers for inbound or outbound requests. If a remote end-point requests
  205. session-timers in a dialog, then Asterisk ignores that request unless it's
  206. noted as a requirement (Require: header), in which case the INVITE is
  207. rejected with a 420 Bad Extension response.
  208. */
  209. #include "asterisk.h"
  210. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  211. #include <signal.h>
  212. #include <sys/signal.h>
  213. #include <regex.h>
  214. #include <inttypes.h>
  215. #include "asterisk/network.h"
  216. #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
  217. #include "asterisk/lock.h"
  218. #include "asterisk/config.h"
  219. #include "asterisk/module.h"
  220. #include "asterisk/pbx.h"
  221. #include "asterisk/sched.h"
  222. #include "asterisk/io.h"
  223. #include "asterisk/rtp_engine.h"
  224. #include "asterisk/udptl.h"
  225. #include "asterisk/acl.h"
  226. #include "asterisk/manager.h"
  227. #include "asterisk/callerid.h"
  228. #include "asterisk/cli.h"
  229. #include "asterisk/musiconhold.h"
  230. #include "asterisk/dsp.h"
  231. #include "asterisk/pickup.h"
  232. #include "asterisk/parking.h"
  233. #include "asterisk/srv.h"
  234. #include "asterisk/astdb.h"
  235. #include "asterisk/causes.h"
  236. #include "asterisk/utils.h"
  237. #include "asterisk/file.h"
  238. #include "asterisk/astobj2.h"
  239. #include "asterisk/dnsmgr.h"
  240. #include "asterisk/devicestate.h"
  241. #include "asterisk/monitor.h"
  242. #include "asterisk/netsock2.h"
  243. #include "asterisk/localtime.h"
  244. #include "asterisk/abstract_jb.h"
  245. #include "asterisk/threadstorage.h"
  246. #include "asterisk/translate.h"
  247. #include "asterisk/ast_version.h"
  248. #include "asterisk/data.h"
  249. #include "asterisk/aoc.h"
  250. #include "asterisk/message.h"
  251. #include "sip/include/sip.h"
  252. #include "sip/include/globals.h"
  253. #include "sip/include/config_parser.h"
  254. #include "sip/include/reqresp_parser.h"
  255. #include "sip/include/sip_utils.h"
  256. #include "asterisk/sdp_srtp.h"
  257. #include "asterisk/ccss.h"
  258. #include "asterisk/xml.h"
  259. #include "sip/include/dialog.h"
  260. #include "sip/include/dialplan_functions.h"
  261. #include "sip/include/security_events.h"
  262. #include "sip/include/route.h"
  263. #include "asterisk/sip_api.h"
  264. #include "asterisk/app.h"
  265. #include "asterisk/bridge.h"
  266. #include "asterisk/stasis.h"
  267. #include "asterisk/stasis_endpoints.h"
  268. #include "asterisk/stasis_system.h"
  269. #include "asterisk/stasis_channels.h"
  270. #include "asterisk/features_config.h"
  271. #include "asterisk/http_websocket.h"
  272. #include "asterisk/format_cache.h"
  273. /*** DOCUMENTATION
  274. <application name="SIPDtmfMode" language="en_US">
  275. <synopsis>
  276. Change the dtmfmode for a SIP call.
  277. </synopsis>
  278. <syntax>
  279. <parameter name="mode" required="true">
  280. <enumlist>
  281. <enum name="inband" />
  282. <enum name="info" />
  283. <enum name="rfc2833" />
  284. </enumlist>
  285. </parameter>
  286. </syntax>
  287. <description>
  288. <para>Changes the dtmfmode for a SIP call.</para>
  289. </description>
  290. </application>
  291. <application name="SIPAddHeader" language="en_US">
  292. <synopsis>
  293. Add a SIP header to the outbound call.
  294. </synopsis>
  295. <syntax argsep=":">
  296. <parameter name="Header" required="true" />
  297. <parameter name="Content" required="true" />
  298. </syntax>
  299. <description>
  300. <para>Adds a header to a SIP call placed with DIAL.</para>
  301. <para>Remember to use the X-header if you are adding non-standard SIP
  302. headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
  303. Adding the wrong headers may jeopardize the SIP dialog.</para>
  304. <para>Always returns <literal>0</literal>.</para>
  305. </description>
  306. </application>
  307. <application name="SIPRemoveHeader" language="en_US">
  308. <synopsis>
  309. Remove SIP headers previously added with SIPAddHeader
  310. </synopsis>
  311. <syntax>
  312. <parameter name="Header" required="false" />
  313. </syntax>
  314. <description>
  315. <para>SIPRemoveHeader() allows you to remove headers which were previously
  316. added with SIPAddHeader(). If no parameter is supplied, all previously added
  317. headers will be removed. If a parameter is supplied, only the matching headers
  318. will be removed.</para>
  319. <para>For example you have added these 2 headers:</para>
  320. <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
  321. <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
  322. <para></para>
  323. <para>// remove all headers</para>
  324. <para>SIPRemoveHeader();</para>
  325. <para>// remove all P- headers</para>
  326. <para>SIPRemoveHeader(P-);</para>
  327. <para>// remove only the PAI header (note the : at the end)</para>
  328. <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
  329. <para></para>
  330. <para>Always returns <literal>0</literal>.</para>
  331. </description>
  332. </application>
  333. <application name="SIPSendCustomINFO" language="en_US">
  334. <synopsis>
  335. Send a custom INFO frame on specified channels.
  336. </synopsis>
  337. <syntax>
  338. <parameter name="Data" required="true" />
  339. <parameter name="UserAgent" required="false" />
  340. </syntax>
  341. <description>
  342. <para>SIPSendCustomINFO() allows you to send a custom INFO message on all
  343. active SIP channels or on channels with the specified User Agent. This
  344. application is only available if TEST_FRAMEWORK is defined.</para>
  345. </description>
  346. </application>
  347. <function name="SIP_HEADER" language="en_US">
  348. <synopsis>
  349. Gets the specified SIP header from an incoming INVITE message.
  350. </synopsis>
  351. <syntax>
  352. <parameter name="name" required="true" />
  353. <parameter name="number">
  354. <para>If not specified, defaults to <literal>1</literal>.</para>
  355. </parameter>
  356. </syntax>
  357. <description>
  358. <para>Since there are several headers (such as Via) which can occur multiple
  359. times, SIP_HEADER takes an optional second argument to specify which header with
  360. that name to retrieve. Headers start at offset <literal>1</literal>.</para>
  361. <para>Please observe that contents of the SDP (an attachment to the
  362. SIP request) can't be accessed with this function.</para>
  363. </description>
  364. </function>
  365. <function name="SIPPEER" language="en_US">
  366. <synopsis>
  367. Gets SIP peer information.
  368. </synopsis>
  369. <syntax>
  370. <parameter name="peername" required="true" />
  371. <parameter name="item">
  372. <enumlist>
  373. <enum name="ip">
  374. <para>(default) The IP address.</para>
  375. </enum>
  376. <enum name="port">
  377. <para>The port number.</para>
  378. </enum>
  379. <enum name="mailbox">
  380. <para>The configured mailbox.</para>
  381. </enum>
  382. <enum name="context">
  383. <para>The configured context.</para>
  384. </enum>
  385. <enum name="expire">
  386. <para>The epoch time of the next expire.</para>
  387. </enum>
  388. <enum name="dynamic">
  389. <para>Is it dynamic? (yes/no).</para>
  390. </enum>
  391. <enum name="callerid_name">
  392. <para>The configured Caller ID name.</para>
  393. </enum>
  394. <enum name="callerid_num">
  395. <para>The configured Caller ID number.</para>
  396. </enum>
  397. <enum name="callgroup">
  398. <para>The configured Callgroup.</para>
  399. </enum>
  400. <enum name="pickupgroup">
  401. <para>The configured Pickupgroup.</para>
  402. </enum>
  403. <enum name="namedcallgroup">
  404. <para>The configured Named Callgroup.</para>
  405. </enum>
  406. <enum name="namedpickupgroup">
  407. <para>The configured Named Pickupgroup.</para>
  408. </enum>
  409. <enum name="codecs">
  410. <para>The configured codecs.</para>
  411. </enum>
  412. <enum name="status">
  413. <para>Status (if qualify=yes).</para>
  414. </enum>
  415. <enum name="regexten">
  416. <para>Extension activated at registration.</para>
  417. </enum>
  418. <enum name="limit">
  419. <para>Call limit (call-limit).</para>
  420. </enum>
  421. <enum name="busylevel">
  422. <para>Configured call level for signalling busy.</para>
  423. </enum>
  424. <enum name="curcalls">
  425. <para>Current amount of calls. Only available if call-limit is set.</para>
  426. </enum>
  427. <enum name="language">
  428. <para>Default language for peer.</para>
  429. </enum>
  430. <enum name="accountcode">
  431. <para>Account code for this peer.</para>
  432. </enum>
  433. <enum name="useragent">
  434. <para>Current user agent header used by peer.</para>
  435. </enum>
  436. <enum name="maxforwards">
  437. <para>The value used for SIP loop prevention in outbound requests</para>
  438. </enum>
  439. <enum name="chanvar[name]">
  440. <para>A channel variable configured with setvar for this peer.</para>
  441. </enum>
  442. <enum name="codec[x]">
  443. <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
  444. </enum>
  445. </enumlist>
  446. </parameter>
  447. </syntax>
  448. <description></description>
  449. </function>
  450. <function name="CHECKSIPDOMAIN" language="en_US">
  451. <synopsis>
  452. Checks if domain is a local domain.
  453. </synopsis>
  454. <syntax>
  455. <parameter name="domain" required="true" />
  456. </syntax>
  457. <description>
  458. <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
  459. as a local SIP domain that this Asterisk server is configured to handle.
  460. Returns the domain name if it is locally handled, otherwise an empty string.
  461. Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
  462. </description>
  463. </function>
  464. <manager name="SIPpeers" language="en_US">
  465. <synopsis>
  466. List SIP peers (text format).
  467. </synopsis>
  468. <syntax>
  469. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  470. </syntax>
  471. <description>
  472. <para>Lists SIP peers in text format with details on current status.
  473. <literal>Peerlist</literal> will follow as separate events, followed by a final event called
  474. <literal>PeerlistComplete</literal>.</para>
  475. </description>
  476. </manager>
  477. <manager name="SIPshowpeer" language="en_US">
  478. <synopsis>
  479. show SIP peer (text format).
  480. </synopsis>
  481. <syntax>
  482. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  483. <parameter name="Peer" required="true">
  484. <para>The peer name you want to check.</para>
  485. </parameter>
  486. </syntax>
  487. <description>
  488. <para>Show one SIP peer with details on current status.</para>
  489. </description>
  490. </manager>
  491. <manager name="SIPqualifypeer" language="en_US">
  492. <synopsis>
  493. Qualify SIP peers.
  494. </synopsis>
  495. <syntax>
  496. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  497. <parameter name="Peer" required="true">
  498. <para>The peer name you want to qualify.</para>
  499. </parameter>
  500. </syntax>
  501. <description>
  502. <para>Qualify a SIP peer.</para>
  503. </description>
  504. <see-also>
  505. <ref type="managerEvent">SIPQualifyPeerDone</ref>
  506. </see-also>
  507. </manager>
  508. <manager name="SIPshowregistry" language="en_US">
  509. <synopsis>
  510. Show SIP registrations (text format).
  511. </synopsis>
  512. <syntax>
  513. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  514. </syntax>
  515. <description>
  516. <para>Lists all registration requests and status. Registrations will follow as separate
  517. events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
  518. </description>
  519. </manager>
  520. <manager name="SIPnotify" language="en_US">
  521. <synopsis>
  522. Send a SIP notify.
  523. </synopsis>
  524. <syntax>
  525. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  526. <parameter name="Channel" required="true">
  527. <para>Peer to receive the notify.</para>
  528. </parameter>
  529. <parameter name="Variable" required="true">
  530. <para>At least one variable pair must be specified.
  531. <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
  532. </parameter>
  533. </syntax>
  534. <description>
  535. <para>Sends a SIP Notify event.</para>
  536. <para>All parameters for this event must be specified in the body of this request
  537. via multiple <literal>Variable: name=value</literal> sequences.</para>
  538. </description>
  539. </manager>
  540. <manager name="SIPpeerstatus" language="en_US">
  541. <synopsis>
  542. Show the status of one or all of the sip peers.
  543. </synopsis>
  544. <syntax>
  545. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  546. <parameter name="Peer" required="false">
  547. <para>The peer name you want to check.</para>
  548. </parameter>
  549. </syntax>
  550. <description>
  551. <para>Retrieves the status of one or all of the sip peers. If no peer name is specified, status
  552. for all of the sip peers will be retrieved.</para>
  553. </description>
  554. </manager>
  555. <info name="SIPMessageFromInfo" language="en_US" tech="SIP">
  556. <para>The <literal>from</literal> parameter can be a configured peer name
  557. or in the form of "display-name" &lt;URI&gt;.</para>
  558. </info>
  559. <info name="SIPMessageToInfo" language="en_US" tech="SIP">
  560. <para>Specifying a prefix of <literal>sip:</literal> will send the
  561. message as a SIP MESSAGE request.</para>
  562. </info>
  563. <managerEvent language="en_US" name="SIPQualifyPeerDone">
  564. <managerEventInstance class="EVENT_FLAG_CALL">
  565. <synopsis>Raised when SIPQualifyPeer has finished qualifying the specified peer.</synopsis>
  566. <syntax>
  567. <parameter name="Peer">
  568. <para>The name of the peer.</para>
  569. </parameter>
  570. <parameter name="ActionID">
  571. <para>This is only included if an ActionID Header was sent with the action request, in which case it will be that ActionID.</para>
  572. </parameter>
  573. </syntax>
  574. <see-also>
  575. <ref type="manager">SIPqualifypeer</ref>
  576. </see-also>
  577. </managerEventInstance>
  578. </managerEvent>
  579. <managerEvent language="en_US" name="SessionTimeout">
  580. <managerEventInstance class="EVENT_FLAG_CALL">
  581. <synopsis>Raised when a SIP session times out.</synopsis>
  582. <syntax>
  583. <channel_snapshot/>
  584. <parameter name="Source">
  585. <para>The source of the session timeout.</para>
  586. <enumlist>
  587. <enum name="RTPTimeout" />
  588. <enum name="SIPSessionTimer" />
  589. </enumlist>
  590. </parameter>
  591. </syntax>
  592. </managerEventInstance>
  593. </managerEvent>
  594. ***/
  595. static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
  596. static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
  597. static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
  598. static int min_subexpiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted subscription time */
  599. static int max_subexpiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted subscription time */
  600. static int mwi_expiry = DEFAULT_MWI_EXPIRY;
  601. static int unauth_sessions = 0;
  602. static int authlimit = DEFAULT_AUTHLIMIT;
  603. static int authtimeout = DEFAULT_AUTHTIMEOUT;
  604. /*! \brief Global jitterbuffer configuration - by default, jb is disabled
  605. * \note Values shown here match the defaults shown in sip.conf.sample */
  606. static struct ast_jb_conf default_jbconf =
  607. {
  608. .flags = 0,
  609. .max_size = 200,
  610. .resync_threshold = 1000,
  611. .impl = "fixed",
  612. .target_extra = 40,
  613. };
  614. static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
  615. static const char config[] = "sip.conf"; /*!< Main configuration file */
  616. static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
  617. /*! \brief Readable descriptions of device states.
  618. * \note Should be aligned to above table as index */
  619. static const struct invstate2stringtable {
  620. const enum invitestates state;
  621. const char *desc;
  622. } invitestate2string[] = {
  623. {INV_NONE, "None" },
  624. {INV_CALLING, "Calling (Trying)"},
  625. {INV_PROCEEDING, "Proceeding "},
  626. {INV_EARLY_MEDIA, "Early media"},
  627. {INV_COMPLETED, "Completed (done)"},
  628. {INV_CONFIRMED, "Confirmed (up)"},
  629. {INV_TERMINATED, "Done"},
  630. {INV_CANCELLED, "Cancelled"}
  631. };
  632. /*! \brief Subscription types that we support. We support
  633. * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
  634. * - SIMPLE presence used for device status
  635. * - Voicemail notification subscriptions
  636. */
  637. static const struct cfsubscription_types {
  638. enum subscriptiontype type;
  639. const char * const event;
  640. const char * const mediatype;
  641. const char * const text;
  642. } subscription_types[] = {
  643. { NONE, "-", "unknown", "unknown" },
  644. /* RFC 4235: SIP Dialog event package */
  645. { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
  646. { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
  647. { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
  648. { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
  649. { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
  650. };
  651. /*! \brief The core structure to setup dialogs. We parse incoming messages by using
  652. * structure and then route the messages according to the type.
  653. *
  654. * \note Note that sip_methods[i].id == i must hold or the code breaks
  655. */
  656. static const struct cfsip_methods {
  657. enum sipmethod id;
  658. int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
  659. char * const text;
  660. enum can_create_dialog can_create;
  661. } sip_methods[] = {
  662. { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
  663. { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
  664. { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
  665. { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
  666. { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
  667. { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
  668. { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
  669. { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
  670. { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
  671. { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
  672. { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
  673. { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
  674. { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
  675. { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
  676. { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
  677. { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
  678. { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
  679. };
  680. /*! \brief Diversion header reasons
  681. *
  682. * The core defines a bunch of constants used to define
  683. * redirecting reasons. This provides a translation table
  684. * between those and the strings which may be present in
  685. * a SIP Diversion header
  686. */
  687. static const struct sip_reasons {
  688. enum AST_REDIRECTING_REASON code;
  689. char * const text;
  690. } sip_reason_table[] = {
  691. { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
  692. { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
  693. { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
  694. { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
  695. { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
  696. { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
  697. { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
  698. { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
  699. { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
  700. { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
  701. { AST_REDIRECTING_REASON_AWAY, "away" },
  702. { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},
  703. { AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
  704. };
  705. /*! \name DefaultSettings
  706. Default setttings are used as a channel setting and as a default when
  707. configuring devices
  708. */
  709. static char default_language[MAX_LANGUAGE]; /*!< Default language setting for new channels */
  710. static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
  711. static char default_mwi_from[80]; /*!< Default caller ID for MWI updates */
  712. static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
  713. static int default_fromdomainport; /*!< Default domain port on outbound messages */
  714. static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
  715. static char default_vmexten[AST_MAX_EXTENSION]; /*!< Default From Username on MWI updates */
  716. static int default_qualify; /*!< Default Qualify= setting */
  717. static int default_keepalive; /*!< Default keepalive= setting */
  718. static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
  719. static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
  720. * a bridged channel on hold */
  721. static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
  722. static char default_engine[256]; /*!< Default RTP engine */
  723. static int default_maxcallbitrate; /*!< Maximum bitrate for call */
  724. static char default_zone[MAX_TONEZONE_COUNTRY]; /*!< Default tone zone for channels created from the SIP driver */
  725. static unsigned int default_transports; /*!< Default Transports (enum ast_transport) that are acceptable */
  726. static unsigned int default_primary_transport; /*!< Default primary Transport (enum ast_transport) for outbound connections to devices */
  727. static struct sip_settings sip_cfg; /*!< SIP configuration data.
  728. \note in the future we could have multiple of these (per domain, per device group etc) */
  729. /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
  730. #define SIP_PEDANTIC_DECODE(str) \
  731. if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
  732. ast_uri_decode(str, ast_uri_sip_user); \
  733. } \
  734. static unsigned int chan_idx; /*!< used in naming sip channel */
  735. static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
  736. static int global_relaxdtmf; /*!< Relax DTMF */
  737. static int global_prematuremediafilter; /*!< Enable/disable premature frames in a call (causing 183 early media) */
  738. static int global_rtptimeout; /*!< Time out call if no RTP */
  739. static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
  740. static int global_rtpkeepalive; /*!< Send RTP keepalives */
  741. static int global_reg_timeout; /*!< Global time between attempts for outbound registrations */
  742. static int global_regattempts_max; /*!< Registration attempts before giving up */
  743. static int global_reg_retry_403; /*!< Treat 403 responses to registrations as 401 responses */
  744. static int global_shrinkcallerid; /*!< enable or disable shrinking of caller id */
  745. static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
  746. * call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
  747. * with just a boolean flag in the device structure */
  748. static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
  749. static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
  750. static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
  751. static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
  752. static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
  753. static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
  754. static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
  755. static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
  756. static unsigned int recordhistory; /*!< Record SIP history. Off by default */
  757. static unsigned int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
  758. static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
  759. static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
  760. static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
  761. static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
  762. static int global_t1; /*!< T1 time */
  763. static int global_t1min; /*!< T1 roundtrip time minimum */
  764. static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
  765. static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
  766. static int global_qualifyfreq; /*!< Qualify frequency */
  767. static int global_qualify_gap; /*!< Time between our group of peer pokes */
  768. static int global_qualify_peers; /*!< Number of peers to poke at a given time */
  769. static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
  770. static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher */
  771. static int global_min_se; /*!< Lowest threshold for session refresh interval */
  772. static int global_max_se; /*!< Highest threshold for session refresh interval */
  773. static int global_store_sip_cause; /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
  774. static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
  775. static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
  776. /*@}*/
  777. /*!
  778. * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
  779. * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
  780. * event package. This variable is set at module load time and may be checked at runtime to determine
  781. * if XML parsing support was found.
  782. */
  783. static int can_parse_xml;
  784. /*! \name Object counters @{
  785. *
  786. * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
  787. * should be used to modify these values.
  788. */
  789. static int speerobjs = 0; /*!< Static peers */
  790. static int rpeerobjs = 0; /*!< Realtime peers */
  791. static int apeerobjs = 0; /*!< Autocreated peer objects */
  792. /*! @} */
  793. static struct ast_flags global_flags[3] = {{0}}; /*!< global SIP_ flags */
  794. static unsigned int global_t38_maxdatagram; /*!< global T.38 FaxMaxDatagram override */
  795. static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
  796. static struct stasis_subscription *acl_change_sub; /*!< subscription id for named ACL system change events */
  797. static int network_change_sched_id = -1;
  798. static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
  799. AST_MUTEX_DEFINE_STATIC(netlock);
  800. /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
  801. when it's doing something critical. */
  802. AST_MUTEX_DEFINE_STATIC(monlock);
  803. AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
  804. /*! \brief This is the thread for the monitor which checks for input on the channels
  805. which are not currently in use. */
  806. static pthread_t monitor_thread = AST_PTHREADT_NULL;
  807. static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
  808. static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
  809. struct ast_sched_context *sched; /*!< The scheduling context */
  810. static struct io_context *io; /*!< The IO context */
  811. static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
  812. struct sip_pkt;
  813. static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
  814. AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
  815. static enum sip_debug_e sipdebug;
  816. /*! \brief extra debugging for 'text' related events.
  817. * At the moment this is set together with sip_debug_console.
  818. * \note It should either go away or be implemented properly.
  819. */
  820. static int sipdebug_text;
  821. static const struct _map_x_s referstatusstrings[] = {
  822. { REFER_IDLE, "<none>" },
  823. { REFER_SENT, "Request sent" },
  824. { REFER_RECEIVED, "Request received" },
  825. { REFER_CONFIRMED, "Confirmed" },
  826. { REFER_ACCEPTED, "Accepted" },
  827. { REFER_RINGING, "Target ringing" },
  828. { REFER_200OK, "Done" },
  829. { REFER_FAILED, "Failed" },
  830. { REFER_NOAUTH, "Failed - auth failure" },
  831. { -1, NULL} /* terminator */
  832. };
  833. /* --- Hash tables of various objects --------*/
  834. #ifdef LOW_MEMORY
  835. static const int HASH_PEER_SIZE = 17;
  836. static const int HASH_DIALOG_SIZE = 17;
  837. static const int HASH_REGISTRY_SIZE = 17;
  838. #else
  839. static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
  840. static const int HASH_DIALOG_SIZE = 563;
  841. static const int HASH_REGISTRY_SIZE = 563;
  842. #endif
  843. static const struct {
  844. enum ast_cc_service_type service;
  845. const char *service_string;
  846. } sip_cc_service_map [] = {
  847. [AST_CC_NONE] = { AST_CC_NONE, "" },
  848. [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
  849. [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
  850. [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
  851. };
  852. static const struct {
  853. enum sip_cc_notify_state state;
  854. const char *state_string;
  855. } sip_cc_notify_state_map [] = {
  856. [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
  857. [CC_READY] = {CC_READY, "cc-state: ready"},
  858. };
  859. AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
  860. /*!
  861. * Used to create new entity IDs by ESCs.
  862. */
  863. static int esc_etag_counter;
  864. static const int DEFAULT_PUBLISH_EXPIRES = 3600;
  865. #ifdef HAVE_LIBXML2
  866. static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
  867. static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
  868. .initial_handler = cc_esc_publish_handler,
  869. .modify_handler = cc_esc_publish_handler,
  870. };
  871. #endif
  872. /*!
  873. * \brief The Event State Compositors
  874. *
  875. * An Event State Compositor is an entity which
  876. * accepts PUBLISH requests and acts appropriately
  877. * based on these requests.
  878. *
  879. * The actual event_state_compositor structure is simply
  880. * an ao2_container of sip_esc_entrys. When an incoming
  881. * PUBLISH is received, we can match the appropriate sip_esc_entry
  882. * using the entity ID of the incoming PUBLISH.
  883. */
  884. static struct event_state_compositor {
  885. enum subscriptiontype event;
  886. const char * name;
  887. const struct sip_esc_publish_callbacks *callbacks;
  888. struct ao2_container *compositor;
  889. } event_state_compositors [] = {
  890. #ifdef HAVE_LIBXML2
  891. {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
  892. #endif
  893. };
  894. struct state_notify_data {
  895. int state;
  896. struct ao2_container *device_state_info;
  897. int presence_state;
  898. const char *presence_subtype;
  899. const char *presence_message;
  900. };
  901. static const int ESC_MAX_BUCKETS = 37;
  902. /*!
  903. * \details
  904. * Here we implement the container for dialogs which are in the
  905. * dialog_needdestroy state to iterate only through the dialogs
  906. * unlink them instead of iterate through all dialogs
  907. */
  908. struct ao2_container *dialogs_needdestroy;
  909. /*!
  910. * \details
  911. * Here we implement the container for dialogs which have rtp
  912. * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
  913. * set. We use this container instead the whole dialog list.
  914. */
  915. struct ao2_container *dialogs_rtpcheck;
  916. /*!
  917. * \details
  918. * Here we implement the container for dialogs (sip_pvt), defining
  919. * generic wrapper functions to ease the transition from the current
  920. * implementation (a single linked list) to a different container.
  921. * In addition to a reference to the container, we need functions to lock/unlock
  922. * the container and individual items, and functions to add/remove
  923. * references to the individual items.
  924. */
  925. static struct ao2_container *dialogs;
  926. #define sip_pvt_lock(x) ao2_lock(x)
  927. #define sip_pvt_trylock(x) ao2_trylock(x)
  928. #define sip_pvt_unlock(x) ao2_unlock(x)
  929. /*! \brief The table of TCP threads */
  930. static struct ao2_container *threadt;
  931. /*! \brief The peer list: Users, Peers and Friends */
  932. static struct ao2_container *peers;
  933. static struct ao2_container *peers_by_ip;
  934. /*! \brief A bogus peer, to be used when authentication should fail */
  935. static struct sip_peer *bogus_peer;
  936. /*! \brief We can recognise the bogus peer by this invalid MD5 hash */
  937. #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
  938. /*! \brief The register list: Other SIP proxies we register with and receive calls from */
  939. static struct ao2_container *registry_list;
  940. /*! \brief The MWI subscription list */
  941. static struct ao2_container *subscription_mwi_list;
  942. static int temp_pvt_init(void *);
  943. static void temp_pvt_cleanup(void *);
  944. /*! \brief A per-thread temporary pvt structure */
  945. AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
  946. /*! \brief A per-thread buffer for transport to string conversion */
  947. AST_THREADSTORAGE(sip_transport_str_buf);
  948. /*! \brief Size of the SIP transport buffer */
  949. #define SIP_TRANSPORT_STR_BUFSIZE 128
  950. /*! \brief Authentication container for realm authentication */
  951. static struct sip_auth_container *authl = NULL;
  952. /*! \brief Global authentication container protection while adjusting the references. */
  953. AST_MUTEX_DEFINE_STATIC(authl_lock);
  954. static struct ast_manager_event_blob *session_timeout_to_ami(struct stasis_message *msg);
  955. STASIS_MESSAGE_TYPE_DEFN_LOCAL(session_timeout_type,
  956. .to_ami = session_timeout_to_ami,
  957. );
  958. /* --- Sockets and networking --------------*/
  959. /*! \brief Main socket for UDP SIP communication.
  960. *
  961. * sipsock is shared between the SIP manager thread (which handles reload
  962. * requests), the udp io handler (sipsock_read()) and the user routines that
  963. * issue udp writes (using __sip_xmit()).
  964. * The socket is -1 only when opening fails (this is a permanent condition),
  965. * or when we are handling a reload() that changes its address (this is
  966. * a transient situation during which we might have a harmless race, see
  967. * below). Because the conditions for the race to be possible are extremely
  968. * rare, we don't want to pay the cost of locking on every I/O.
  969. * Rather, we remember that when the race may occur, communication is
  970. * bound to fail anyways, so we just live with this event and let
  971. * the protocol handle this above us.
  972. */
  973. static int sipsock = -1;
  974. struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
  975. /*! \brief our (internal) default address/port to put in SIP/SDP messages
  976. * internip is initialized picking a suitable address from one of the
  977. * interfaces, and the same port number we bind to. It is used as the
  978. * default address/port in SIP messages, and as the default address
  979. * (but not port) in SDP messages.
  980. */
  981. static struct ast_sockaddr internip;
  982. /*! \brief our external IP address/port for SIP sessions.
  983. * externaddr.sin_addr is only set when we know we might be behind
  984. * a NAT, and this is done using a variety of (mutually exclusive)
  985. * ways from the config file:
  986. *
  987. * + with "externaddr = host[:port]" we specify the address/port explicitly.
  988. * The address is looked up only once when (re)loading the config file;
  989. *
  990. * + with "externhost = host[:port]" we do a similar thing, but the
  991. * hostname is stored in externhost, and the hostname->IP mapping
  992. * is refreshed every 'externrefresh' seconds;
  993. *
  994. * Other variables (externhost, externexpire, externrefresh) are used
  995. * to support the above functions.
  996. */
  997. static struct ast_sockaddr externaddr; /*!< External IP address if we are behind NAT */
  998. static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
  999. static struct ast_sockaddr rtpbindaddr; /*!< RTP: The address we bind to */
  1000. static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
  1001. static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
  1002. static int externrefresh = 10; /*!< Refresh timer for DNS-based external address (dyndns) */
  1003. static uint16_t externtcpport; /*!< external tcp port */
  1004. static uint16_t externtlsport; /*!< external tls port */
  1005. /*! \brief List of local networks
  1006. * We store "localnet" addresses from the config file into an access list,
  1007. * marked as 'DENY', so the call to ast_apply_ha() will return
  1008. * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
  1009. * (i.e. presumably public) addresses.
  1010. */
  1011. static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
  1012. static int ourport_tcp; /*!< The port used for TCP connections */
  1013. static int ourport_tls; /*!< The port used for TCP/TLS connections */
  1014. static struct ast_sockaddr debugaddr;
  1015. static struct ast_config *notify_types = NULL; /*!< The list of manual NOTIFY types we know how to send */
  1016. /*! some list management macros. */
  1017. #define UNLINK(element, head, prev) do { \
  1018. if (prev) \
  1019. (prev)->next = (element)->next; \
  1020. else \
  1021. (head) = (element)->next; \
  1022. } while (0)
  1023. struct ao2_container *sip_monitor_instances;
  1024. struct show_peers_context;
  1025. /*---------------------------- Forward declarations of functions in chan_sip.c */
  1026. /* Note: This is added to help splitting up chan_sip.c into several files
  1027. in coming releases. */
  1028. /*--- PBX interface functions */
  1029. static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest, int *cause);
  1030. static int sip_devicestate(const char *data);
  1031. static int sip_sendtext(struct ast_channel *ast, const char *text);
  1032. static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
  1033. static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
  1034. static int sip_hangup(struct ast_channel *ast);
  1035. static int sip_answer(struct ast_channel *ast);
  1036. static struct ast_frame *sip_read(struct ast_channel *ast);
  1037. static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
  1038. static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
  1039. static int sip_transfer(struct ast_channel *ast, const char *dest);
  1040. static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
  1041. static int sip_senddigit_begin(struct ast_channel *ast, char digit);
  1042. static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
  1043. static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
  1044. static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
  1045. static const char *sip_get_callid(struct ast_channel *chan);
  1046. static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
  1047. static int sip_standard_port(enum ast_transport type, int port);
  1048. static int sip_prepare_socket(struct sip_pvt *p);
  1049. static int get_address_family_filter(unsigned int transport);
  1050. /*--- Transmitting responses and requests */
  1051. static int sipsock_read(int *id, int fd, short events, void *ignore);
  1052. static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
  1053. static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
  1054. static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
  1055. static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
  1056. static int retrans_pkt(const void *data);
  1057. static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
  1058. static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1059. static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1060. static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1061. static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid);
  1062. static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
  1063. static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
  1064. static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
  1065. static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
  1066. static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
  1067. static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
  1068. static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
  1069. static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
  1070. static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
  1071. static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
  1072. static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
  1073. static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
  1074. static int transmit_info_with_vidupdate(struct sip_pvt *p);
  1075. static int transmit_message(struct sip_pvt *p, int init, int auth);
  1076. static int transmit_refer(struct sip_pvt *p, const char *dest);
  1077. static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
  1078. static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
  1079. static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
  1080. static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
  1081. static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
  1082. static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
  1083. static void copy_request(struct sip_request *dst, const struct sip_request *src);
  1084. static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
  1085. static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
  1086. static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
  1087. /* Misc dialog routines */
  1088. static int __sip_autodestruct(const void *data);
  1089. static int update_call_counter(struct sip_pvt *fup, int event);
  1090. static int auto_congest(const void *arg);
  1091. static struct sip_pvt *__find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method,
  1092. const char *file, int line, const char *func);
  1093. #define find_call(req, addr, intended_method) \
  1094. __find_call(req, addr, intended_method, __FILE__, __LINE__, __PRETTY_FUNCTION__)
  1095. static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
  1096. static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, const char *pathbuf);
  1097. static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
  1098. struct sip_request *req, const char *uri);
  1099. static int get_sip_pvt_from_replaces(const char *callid, const char *totag, const char *fromtag,
  1100. struct sip_pvt **out_pvt, struct ast_channel **out_chan);
  1101. static void check_pendings(struct sip_pvt *p);
  1102. static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan);
  1103. static void *sip_pickup_thread(void *stuff);
  1104. static int sip_pickup(struct ast_channel *chan);
  1105. static int sip_sipredirect(struct sip_pvt *p, const char *dest);
  1106. static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
  1107. /*--- Codec handling / SDP */
  1108. static void try_suggested_sip_codec(struct sip_pvt *p);
  1109. static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
  1110. static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
  1111. static int find_sdp(struct sip_request *req);
  1112. static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
  1113. static int process_sdp_o(const char *o, struct sip_pvt *p);
  1114. static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
  1115. static int process_sdp_a_sendonly(const char *a, int *sendonly);
  1116. static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
  1117. static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
  1118. static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
  1119. static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
  1120. static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
  1121. static int process_sdp_a_image(const char *a, struct sip_pvt *p);
  1122. static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
  1123. static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
  1124. static void start_ice(struct ast_rtp_instance *instance, int offer);
  1125. static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
  1126. struct ast_str **m_buf, struct ast_str **a_buf,
  1127. int debug, int *min_packet_size, int *max_packet_size);
  1128. static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
  1129. struct ast_str **m_buf, struct ast_str **a_buf,
  1130. int debug);
  1131. static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
  1132. static void do_setnat(struct sip_pvt *p);
  1133. static void stop_media_flows(struct sip_pvt *p);
  1134. /*--- Authentication stuff */
  1135. static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
  1136. static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
  1137. static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
  1138. const char *secret, const char *md5secret, int sipmethod,
  1139. const char *uri, enum xmittype reliable);
  1140. static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
  1141. int sipmethod, const char *uri, enum xmittype reliable,
  1142. struct ast_sockaddr *addr, struct sip_peer **authpeer);
  1143. static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
  1144. /*--- Domain handling */
  1145. static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
  1146. static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
  1147. static void clear_sip_domains(void);
  1148. /*--- SIP realm authentication */
  1149. static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
  1150. static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
  1151. /*--- Misc functions */
  1152. static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
  1153. static int reload_config(enum channelreloadreason reason);
  1154. static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
  1155. static int expire_register(const void *data);
  1156. static void *do_monitor(void *data);
  1157. static int restart_monitor(void);
  1158. static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
  1159. static struct ast_variable *copy_vars(struct ast_variable *src);
  1160. static int dialog_find_multiple(void *obj, void *arg, int flags);
  1161. static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
  1162. /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
  1163. static int sip_refer_alloc(struct sip_pvt *p);
  1164. static void sip_refer_destroy(struct sip_pvt *p);
  1165. static int sip_notify_alloc(struct sip_pvt *p);
  1166. static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
  1167. static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
  1168. static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
  1169. /*--- Device monitoring and Device/extension state/event handling */
  1170. static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
  1171. static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
  1172. static int sip_poke_noanswer(const void *data);
  1173. static int sip_poke_peer(struct sip_peer *peer, int force);
  1174. static void sip_poke_all_peers(void);
  1175. static void sip_peer_hold(struct sip_pvt *p, int hold);
  1176. static void mwi_event_cb(void *, struct stasis_subscription *, struct stasis_message *);
  1177. static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
  1178. static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
  1179. static void sip_keepalive_all_peers(void);
  1180. /*--- Applications, functions, CLI and manager command helpers */
  1181. static const char *sip_nat_mode(const struct sip_pvt *p);
  1182. static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1183. static char *transfermode2str(enum transfermodes mode) attribute_const;
  1184. static int peer_status(struct sip_peer *peer, char *status, int statuslen);
  1185. static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1186. static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
  1187. static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
  1188. static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1189. static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1190. static void print_group(int fd, ast_group_t group, int crlf);
  1191. static void print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
  1192. static const char *dtmfmode2str(int mode) attribute_const;
  1193. static int str2dtmfmode(const char *str) attribute_unused;
  1194. static const char *insecure2str(int mode) attribute_const;
  1195. static const char *allowoverlap2str(int mode) attribute_const;
  1196. static void cleanup_stale_contexts(char *new, char *old);
  1197. static const char *domain_mode_to_text(const enum domain_mode mode);
  1198. static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1199. static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
  1200. static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1201. static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
  1202. static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1203. static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1204. static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1205. static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1206. static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1207. static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
  1208. static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
  1209. static char *complete_sip_peer(const char *word, int state, int flags2);
  1210. static char *complete_sip_registered_peer(const char *word, int state, int flags2);
  1211. static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
  1212. static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
  1213. static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
  1214. static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
  1215. static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1216. static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1217. static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1218. static char *sip_do_debug_ip(int fd, const char *arg);
  1219. static char *sip_do_debug_peer(int fd, const char *arg);
  1220. static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1221. static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1222. static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1223. static int sip_dtmfmode(struct ast_channel *chan, const char *data);
  1224. static int sip_addheader(struct ast_channel *chan, const char *data);
  1225. static int sip_do_reload(enum channelreloadreason reason);
  1226. static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1227. static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
  1228. const char *name, int flag, int family);
  1229. static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
  1230. const char *name, int flag);
  1231. static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
  1232. const char *name, int flag, unsigned int transport);
  1233. /*--- Debugging
  1234. Functions for enabling debug per IP or fully, or enabling history logging for
  1235. a SIP dialog
  1236. */
  1237. static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
  1238. static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
  1239. static inline int sip_debug_test_pvt(struct sip_pvt *p);
  1240. static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
  1241. static void sip_dump_history(struct sip_pvt *dialog);
  1242. /*--- Device object handling */
  1243. static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
  1244. static int update_call_counter(struct sip_pvt *fup, int event);
  1245. static void sip_destroy_peer(struct sip_peer *peer);
  1246. static void sip_destroy_peer_fn(void *peer);
  1247. static void set_peer_defaults(struct sip_peer *peer);
  1248. static struct sip_peer *temp_peer(const char *name);
  1249. static void register_peer_exten(struct sip_peer *peer, int onoff);
  1250. static int sip_poke_peer_s(const void *data);
  1251. static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
  1252. static void reg_source_db(struct sip_peer *peer);
  1253. static void destroy_association(struct sip_peer *peer);
  1254. static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
  1255. static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
  1256. static void set_socket_transport(struct sip_socket *socket, int transport);
  1257. static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
  1258. /* Realtime device support */
  1259. static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms, const char *path);
  1260. static void update_peer(struct sip_peer *p, int expire);
  1261. static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
  1262. static const char *get_name_from_variable(const struct ast_variable *var);
  1263. static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
  1264. static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1265. /*--- Internal UA client handling (outbound registrations) */
  1266. static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
  1267. static void sip_registry_destroy(void *reg);
  1268. static int sip_register(const char *value, int lineno);
  1269. static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
  1270. static int sip_reregister(const void *data);
  1271. static int __sip_do_register(struct sip_registry *r);
  1272. static int sip_reg_timeout(const void *data);
  1273. static void sip_send_all_registers(void);
  1274. static int sip_reinvite_retry(const void *data);
  1275. /*--- Parsing SIP requests and responses */
  1276. static int determine_firstline_parts(struct sip_request *req);
  1277. static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
  1278. static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
  1279. static int find_sip_method(const char *msg);
  1280. static unsigned int parse_allowed_methods(struct sip_request *req);
  1281. static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
  1282. static int parse_request(struct sip_request *req);
  1283. static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
  1284. static int method_match(enum sipmethod id, const char *name);
  1285. static void parse_copy(struct sip_request *dst, const struct sip_request *src);
  1286. static void parse_oli(struct sip_request *req, struct ast_channel *chan);
  1287. static const char *find_alias(const char *name, const char *_default);
  1288. static const char *__get_header(const struct sip_request *req, const char *name, int *start);
  1289. static void lws2sws(struct ast_str *msgbuf);
  1290. static void extract_uri(struct sip_pvt *p, struct sip_request *req);
  1291. static char *remove_uri_parameters(char *uri);
  1292. static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
  1293. static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
  1294. static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
  1295. static int set_address_from_contact(struct sip_pvt *pvt);
  1296. static void check_via(struct sip_pvt *p, const struct sip_request *req);
  1297. static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
  1298. static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason, char **reason_str);
  1299. static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
  1300. static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
  1301. static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
  1302. static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
  1303. static int get_domain(const char *str, char *domain, int len);
  1304. static void get_realm(struct sip_pvt *p, const struct sip_request *req);
  1305. static char *get_content(struct sip_request *req);
  1306. /*-- TCP connection handling ---*/
  1307. static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
  1308. static void *sip_tcp_worker_fn(void *);
  1309. /*--- Constructing requests and responses */
  1310. static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
  1311. static int init_req(struct sip_request *req, int sipmethod, const char *recip);
  1312. static void deinit_req(struct sip_request *req);
  1313. static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
  1314. static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
  1315. static int init_resp(struct sip_request *resp, const char *msg);
  1316. static inline int resp_needs_contact(const char *msg, enum sipmethod method);
  1317. static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1318. static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
  1319. static void build_via(struct sip_pvt *p);
  1320. static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
  1321. static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
  1322. static char *generate_random_string(char *buf, size_t size);
  1323. static void build_callid_pvt(struct sip_pvt *pvt);
  1324. static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
  1325. static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
  1326. static void build_localtag_registry(struct sip_registry *reg);
  1327. static void make_our_tag(struct sip_pvt *pvt);
  1328. static int add_header(struct sip_request *req, const char *var, const char *value);
  1329. static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
  1330. static int add_content(struct sip_request *req, const char *line);
  1331. static int finalize_content(struct sip_request *req);
  1332. static void destroy_msg_headers(struct sip_pvt *pvt);
  1333. static int add_text(struct sip_request *req, struct sip_pvt *p);
  1334. static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
  1335. static int add_rpid(struct sip_request *req, struct sip_pvt *p);
  1336. static int add_vidupdate(struct sip_request *req);
  1337. static void add_route(struct sip_request *req, struct sip_route *route, int skip);
  1338. static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
  1339. static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
  1340. static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
  1341. static void set_destination(struct sip_pvt *p, const char *uri);
  1342. static void add_date(struct sip_request *req);
  1343. static void add_expires(struct sip_request *req, int expires);
  1344. static void build_contact(struct sip_pvt *p, struct sip_request *req, int incoming);
  1345. /*------Request handling functions */
  1346. static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
  1347. static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
  1348. static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *recount, const char *e, int *nounlock);
  1349. static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
  1350. static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
  1351. static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
  1352. static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
  1353. static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
  1354. static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
  1355. static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
  1356. static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
  1357. static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req,
  1358. int *nounlock, struct sip_pvt *replaces_pvt, struct ast_channel *replaces_chan);
  1359. static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
  1360. static int local_attended_transfer(struct sip_pvt *transferer, struct ast_channel *transferer_chan, uint32_t seqno, int *nounlock);
  1361. /*------Response handling functions */
  1362. static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1363. static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1364. static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1365. static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1366. static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1367. static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1368. static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1369. /*------ SRTP Support -------- */
  1370. static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp, const char *a);
  1371. /*------ T38 Support --------- */
  1372. static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
  1373. static void change_t38_state(struct sip_pvt *p, int state);
  1374. /*------ Session-Timers functions --------- */
  1375. static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
  1376. static int proc_session_timer(const void *vp);
  1377. static void stop_session_timer(struct sip_pvt *p);
  1378. static void start_session_timer(struct sip_pvt *p);
  1379. static void restart_session_timer(struct sip_pvt *p);
  1380. static const char *strefresherparam2str(enum st_refresher_param r);
  1381. static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
  1382. static int parse_minse(const char *p_hdrval, int *const p_interval);
  1383. static int st_get_se(struct sip_pvt *, int max);
  1384. static enum st_refresher st_get_refresher(struct sip_pvt *);
  1385. static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
  1386. static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
  1387. /*------- RTP Glue functions -------- */
  1388. static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active);
  1389. /*!--- SIP MWI Subscription support */
  1390. static int sip_subscribe_mwi(const char *value, int lineno);
  1391. static void sip_subscribe_mwi_destroy(void *data);
  1392. static void sip_send_all_mwi_subscriptions(void);
  1393. static int sip_subscribe_mwi_do(const void *data);
  1394. static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
  1395. /*! \brief Definition of this channel for PBX channel registration */
  1396. struct ast_channel_tech sip_tech = {
  1397. .type = "SIP",
  1398. .description = "Session Initiation Protocol (SIP)",
  1399. .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
  1400. .requester = sip_request_call, /* called with chan unlocked */
  1401. .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
  1402. .call = sip_call, /* called with chan locked */
  1403. .send_html = sip_sendhtml,
  1404. .hangup = sip_hangup, /* called with chan locked */
  1405. .answer = sip_answer, /* called with chan locked */
  1406. .read = sip_read, /* called with chan locked */
  1407. .write = sip_write, /* called with chan locked */
  1408. .write_video = sip_write, /* called with chan locked */
  1409. .write_text = sip_write,
  1410. .indicate = sip_indicate, /* called with chan locked */
  1411. .transfer = sip_transfer, /* called with chan locked */
  1412. .fixup = sip_fixup, /* called with chan locked */
  1413. .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
  1414. .send_digit_end = sip_senddigit_end,
  1415. .early_bridge = ast_rtp_instance_early_bridge,
  1416. .send_text = sip_sendtext, /* called with chan locked */
  1417. .func_channel_read = sip_acf_channel_read,
  1418. .setoption = sip_setoption,
  1419. .queryoption = sip_queryoption,
  1420. .get_pvt_uniqueid = sip_get_callid,
  1421. };
  1422. /*! \brief This version of the sip channel tech has no send_digit_begin
  1423. * callback so that the core knows that the channel does not want
  1424. * DTMF BEGIN frames.
  1425. * The struct is initialized just before registering the channel driver,
  1426. * and is for use with channels using SIP INFO DTMF.
  1427. */
  1428. struct ast_channel_tech sip_tech_info;
  1429. /*------- CC Support -------- */
  1430. static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
  1431. static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
  1432. static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
  1433. static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
  1434. static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
  1435. static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
  1436. static int sip_cc_agent_recall(struct ast_cc_agent *agent);
  1437. static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
  1438. static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
  1439. .type = "SIP",
  1440. .init = sip_cc_agent_init,
  1441. .start_offer_timer = sip_cc_agent_start_offer_timer,
  1442. .stop_offer_timer = sip_cc_agent_stop_offer_timer,
  1443. .respond = sip_cc_agent_respond,
  1444. .status_request = sip_cc_agent_status_request,
  1445. .start_monitoring = sip_cc_agent_start_monitoring,
  1446. .callee_available = sip_cc_agent_recall,
  1447. .destructor = sip_cc_agent_destructor,
  1448. };
  1449. /* -------- End of declarations of structures, constants and forward declarations of functions
  1450. Below starts actual code
  1451. ------------------------
  1452. */
  1453. static int sip_epa_register(const struct epa_static_data *static_data)
  1454. {
  1455. struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
  1456. if (!backend) {
  1457. return -1;
  1458. }
  1459. backend->static_data = static_data;
  1460. AST_LIST_LOCK(&epa_static_data_list);
  1461. AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
  1462. AST_LIST_UNLOCK(&epa_static_data_list);
  1463. return 0;
  1464. }
  1465. static void sip_epa_unregister_all(void)
  1466. {
  1467. struct epa_backend *backend;
  1468. AST_LIST_LOCK(&epa_static_data_list);
  1469. while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
  1470. ast_free(backend);
  1471. }
  1472. AST_LIST_UNLOCK(&epa_static_data_list);
  1473. }
  1474. static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
  1475. static void cc_epa_destructor(void *data)
  1476. {
  1477. struct sip_epa_entry *epa_entry = data;
  1478. struct cc_epa_entry *cc_entry = epa_entry->instance_data;
  1479. ast_free(cc_entry);
  1480. }
  1481. static const struct epa_static_data cc_epa_static_data = {
  1482. .event = CALL_COMPLETION,
  1483. .name = "call-completion",
  1484. .handle_error = cc_handle_publish_error,
  1485. .destructor = cc_epa_destructor,
  1486. };
  1487. static const struct epa_static_data *find_static_data(const char * const event_package)
  1488. {
  1489. const struct epa_backend *backend = NULL;
  1490. AST_LIST_LOCK(&epa_static_data_list);
  1491. AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
  1492. if (!strcmp(backend->static_data->name, event_package)) {
  1493. break;
  1494. }
  1495. }
  1496. AST_LIST_UNLOCK(&epa_static_data_list);
  1497. return backend ? backend->static_data : NULL;
  1498. }
  1499. static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
  1500. {
  1501. struct sip_epa_entry *epa_entry;
  1502. const struct epa_static_data *static_data;
  1503. if (!(static_data = find_static_data(event_package))) {
  1504. return NULL;
  1505. }
  1506. if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
  1507. return NULL;
  1508. }
  1509. epa_entry->static_data = static_data;
  1510. ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
  1511. return epa_entry;
  1512. }
  1513. static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
  1514. {
  1515. enum ast_cc_service_type service;
  1516. for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
  1517. if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
  1518. return service;
  1519. }
  1520. }
  1521. return AST_CC_NONE;
  1522. }
  1523. /* Even state compositors code */
  1524. static void esc_entry_destructor(void *obj)
  1525. {
  1526. struct sip_esc_entry *esc_entry = obj;
  1527. if (esc_entry->sched_id > -1) {
  1528. AST_SCHED_DEL(sched, esc_entry->sched_id);
  1529. }
  1530. }
  1531. static int esc_hash_fn(const void *obj, const int flags)
  1532. {
  1533. const struct sip_esc_entry *entry = obj;
  1534. return ast_str_hash(entry->entity_tag);
  1535. }
  1536. static int esc_cmp_fn(void *obj, void *arg, int flags)
  1537. {
  1538. struct sip_esc_entry *entry1 = obj;
  1539. struct sip_esc_entry *entry2 = arg;
  1540. return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
  1541. }
  1542. static struct event_state_compositor *get_esc(const char * const event_package) {
  1543. int i;
  1544. for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
  1545. if (!strcasecmp(event_package, event_state_compositors[i].name)) {
  1546. return &event_state_compositors[i];
  1547. }
  1548. }
  1549. return NULL;
  1550. }
  1551. static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
  1552. struct sip_esc_entry *entry;
  1553. struct sip_esc_entry finder;
  1554. ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
  1555. entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
  1556. return entry;
  1557. }
  1558. static int publish_expire(const void *data)
  1559. {
  1560. struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
  1561. struct event_state_compositor *esc = get_esc(esc_entry->event);
  1562. ast_assert(esc != NULL);
  1563. ao2_unlink(esc->compositor, esc_entry);
  1564. ao2_ref(esc_entry, -1);
  1565. return 0;
  1566. }
  1567. static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
  1568. {
  1569. int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
  1570. struct event_state_compositor *esc = get_esc(esc_entry->event);
  1571. ast_assert(esc != NULL);
  1572. if (is_linked) {
  1573. ao2_unlink(esc->compositor, esc_entry);
  1574. }
  1575. snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
  1576. ao2_link(esc->compositor, esc_entry);
  1577. }
  1578. static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
  1579. {
  1580. struct sip_esc_entry *esc_entry;
  1581. int expires_ms;
  1582. if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
  1583. return NULL;
  1584. }
  1585. esc_entry->event = esc->name;
  1586. expires_ms = expires * 1000;
  1587. /* Bump refcount for scheduler */
  1588. ao2_ref(esc_entry, +1);
  1589. esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
  1590. /* Note: This links the esc_entry into the ESC properly */
  1591. create_new_sip_etag(esc_entry, 0);
  1592. return esc_entry;
  1593. }
  1594. static int initialize_escs(void)
  1595. {
  1596. int i, res = 0;
  1597. for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
  1598. if (!((event_state_compositors[i].compositor) =
  1599. ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
  1600. res = -1;
  1601. }
  1602. }
  1603. return res;
  1604. }
  1605. static void destroy_escs(void)
  1606. {
  1607. int i;
  1608. for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
  1609. ao2_cleanup(event_state_compositors[i].compositor);
  1610. }
  1611. }
  1612. static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
  1613. {
  1614. struct ast_cc_agent *agent = obj;
  1615. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1616. const char *uri = arg;
  1617. return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
  1618. }
  1619. static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
  1620. {
  1621. struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
  1622. return agent;
  1623. }
  1624. static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
  1625. {
  1626. struct ast_cc_agent *agent = obj;
  1627. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1628. const char *uri = arg;
  1629. return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
  1630. }
  1631. static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
  1632. {
  1633. struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
  1634. return agent;
  1635. }
  1636. static int find_by_callid_helper(void *obj, void *arg, int flags)
  1637. {
  1638. struct ast_cc_agent *agent = obj;
  1639. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1640. struct sip_pvt *call_pvt = arg;
  1641. return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
  1642. }
  1643. static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
  1644. {
  1645. struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
  1646. return agent;
  1647. }
  1648. static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
  1649. {
  1650. struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
  1651. struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
  1652. if (!agent_pvt) {
  1653. return -1;
  1654. }
  1655. ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
  1656. ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
  1657. ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
  1658. agent_pvt->offer_timer_id = -1;
  1659. agent->private_data = agent_pvt;
  1660. sip_pvt_lock(call_pvt);
  1661. ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
  1662. sip_pvt_unlock(call_pvt);
  1663. return 0;
  1664. }
  1665. static int sip_offer_timer_expire(const void *data)
  1666. {
  1667. struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
  1668. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1669. agent_pvt->offer_timer_id = -1;
  1670. return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
  1671. }
  1672. static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
  1673. {
  1674. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1675. int when;
  1676. when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
  1677. agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
  1678. return 0;
  1679. }
  1680. static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
  1681. {
  1682. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1683. AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
  1684. return 0;
  1685. }
  1686. static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
  1687. {
  1688. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1689. sip_pvt_lock(agent_pvt->subscribe_pvt);
  1690. ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  1691. if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
  1692. /* The second half of this if statement may be a bit hard to grasp,
  1693. * so here's an explanation. When a subscription comes into
  1694. * chan_sip, as long as it is not malformed, it will be passed
  1695. * to the CC core. If the core senses an out-of-order state transition,
  1696. * then the core will call this callback with the "reason" set to a
  1697. * failure condition.
  1698. * However, an out-of-order state transition will occur during a resubscription
  1699. * for CC. In such a case, we can see that we have already generated a notify_uri
  1700. * and so we can detect that this isn't a *real* failure. Rather, it is just
  1701. * something the core doesn't recognize as a legitimate SIP state transition.
  1702. * Thus we respond with happiness and flowers.
  1703. */
  1704. transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
  1705. transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
  1706. } else {
  1707. transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
  1708. }
  1709. sip_pvt_unlock(agent_pvt->subscribe_pvt);
  1710. agent_pvt->is_available = TRUE;
  1711. }
  1712. static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
  1713. {
  1714. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1715. enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
  1716. return ast_cc_agent_status_response(agent->core_id, state);
  1717. }
  1718. static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
  1719. {
  1720. /* To start monitoring just means to wait for an incoming PUBLISH
  1721. * to tell us that the caller has become available again. No special
  1722. * action is needed
  1723. */
  1724. return 0;
  1725. }
  1726. static int sip_cc_agent_recall(struct ast_cc_agent *agent)
  1727. {
  1728. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1729. /* If we have received a PUBLISH beforehand stating that the caller in question
  1730. * is not available, we can save ourself a bit of effort here and just report
  1731. * the caller as busy
  1732. */
  1733. if (!agent_pvt->is_available) {
  1734. return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
  1735. agent->device_name);
  1736. }
  1737. /* Otherwise, we transmit a NOTIFY to the caller and await either
  1738. * a PUBLISH or an INVITE
  1739. */
  1740. sip_pvt_lock(agent_pvt->subscribe_pvt);
  1741. transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
  1742. sip_pvt_unlock(agent_pvt->subscribe_pvt);
  1743. return 0;
  1744. }
  1745. static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
  1746. {
  1747. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1748. if (!agent_pvt) {
  1749. /* The agent constructor probably failed. */
  1750. return;
  1751. }
  1752. sip_cc_agent_stop_offer_timer(agent);
  1753. if (agent_pvt->subscribe_pvt) {
  1754. sip_pvt_lock(agent_pvt->subscribe_pvt);
  1755. if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  1756. /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
  1757. * the subscriber know something went wrong
  1758. */
  1759. transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
  1760. }
  1761. sip_pvt_unlock(agent_pvt->subscribe_pvt);
  1762. agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
  1763. }
  1764. ast_free(agent_pvt);
  1765. }
  1766. static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
  1767. {
  1768. const struct sip_monitor_instance *monitor_instance = obj;
  1769. return monitor_instance->core_id;
  1770. }
  1771. static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
  1772. {
  1773. struct sip_monitor_instance *monitor_instance1 = obj;
  1774. struct sip_monitor_instance *monitor_instance2 = arg;
  1775. return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
  1776. }
  1777. static void sip_monitor_instance_destructor(void *data)
  1778. {
  1779. struct sip_monitor_instance *monitor_instance = data;
  1780. if (monitor_instance->subscription_pvt) {
  1781. sip_pvt_lock(monitor_instance->subscription_pvt);
  1782. monitor_instance->subscription_pvt->expiry = 0;
  1783. transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
  1784. sip_pvt_unlock(monitor_instance->subscription_pvt);
  1785. dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
  1786. }
  1787. if (monitor_instance->suspension_entry) {
  1788. monitor_instance->suspension_entry->body[0] = '\0';
  1789. transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
  1790. ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
  1791. }
  1792. ast_string_field_free_memory(monitor_instance);
  1793. }
  1794. static struct sip_monitor_instance *sip_monitor_instance_init(int core_id, const char * const subscribe_uri, const char * const peername, const char * const device_name)
  1795. {
  1796. struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
  1797. if (!monitor_instance) {
  1798. return NULL;
  1799. }
  1800. if (ast_string_field_init(monitor_instance, 256)) {
  1801. ao2_ref(monitor_instance, -1);
  1802. return NULL;
  1803. }
  1804. ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
  1805. ast_string_field_set(monitor_instance, peername, peername);
  1806. ast_string_field_set(monitor_instance, device_name, device_name);
  1807. monitor_instance->core_id = core_id;
  1808. ao2_link(sip_monitor_instances, monitor_instance);
  1809. return monitor_instance;
  1810. }
  1811. static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
  1812. {
  1813. struct sip_monitor_instance *monitor_instance = obj;
  1814. return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
  1815. }
  1816. static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
  1817. {
  1818. struct sip_monitor_instance *monitor_instance = obj;
  1819. return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
  1820. }
  1821. static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
  1822. static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
  1823. static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
  1824. static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
  1825. static void sip_cc_monitor_destructor(void *private_data);
  1826. static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
  1827. .type = "SIP",
  1828. .request_cc = sip_cc_monitor_request_cc,
  1829. .suspend = sip_cc_monitor_suspend,
  1830. .unsuspend = sip_cc_monitor_unsuspend,
  1831. .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
  1832. .destructor = sip_cc_monitor_destructor,
  1833. };
  1834. static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
  1835. {
  1836. struct sip_monitor_instance *monitor_instance = monitor->private_data;
  1837. enum ast_cc_service_type service = monitor->service_offered;
  1838. int when;
  1839. if (!monitor_instance) {
  1840. return -1;
  1841. }
  1842. if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, 0))) {
  1843. return -1;
  1844. }
  1845. when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
  1846. ast_get_ccnr_available_timer(monitor->interface->config_params);
  1847. sip_pvt_lock(monitor_instance->subscription_pvt);
  1848. ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
  1849. create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
  1850. ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
  1851. monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
  1852. monitor_instance->subscription_pvt->expiry = when;
  1853. transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
  1854. sip_pvt_unlock(monitor_instance->subscription_pvt);
  1855. ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
  1856. *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
  1857. return 0;
  1858. }
  1859. static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
  1860. {
  1861. struct ast_str *body = ast_str_alloca(size);
  1862. char tuple_id[32];
  1863. generate_random_string(tuple_id, sizeof(tuple_id));
  1864. /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
  1865. * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
  1866. */
  1867. ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  1868. /* XXX The entity attribute is currently set to the peer name associated with the
  1869. * dialog. This is because we currently only call this function for call-completion
  1870. * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
  1871. * event packages, it may be crucial to have a proper URI as the presentity so this
  1872. * should be revisited as support is expanded.
  1873. */
  1874. ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
  1875. ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
  1876. ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
  1877. ast_str_append(&body, 0, "</tuple>\n");
  1878. ast_str_append(&body, 0, "</presence>\n");
  1879. ast_copy_string(pidf_body, ast_str_buffer(body), size);
  1880. return 0;
  1881. }
  1882. static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
  1883. {
  1884. struct sip_monitor_instance *monitor_instance = monitor->private_data;
  1885. enum sip_publish_type publish_type;
  1886. struct cc_epa_entry *cc_entry;
  1887. if (!monitor_instance) {
  1888. return -1;
  1889. }
  1890. if (!monitor_instance->suspension_entry) {
  1891. /* We haven't yet allocated the suspension entry, so let's give it a shot */
  1892. if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
  1893. ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
  1894. ao2_ref(monitor_instance, -1);
  1895. return -1;
  1896. }
  1897. if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
  1898. ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
  1899. ao2_ref(monitor_instance, -1);
  1900. return -1;
  1901. }
  1902. cc_entry->core_id = monitor->core_id;
  1903. monitor_instance->suspension_entry->instance_data = cc_entry;
  1904. publish_type = SIP_PUBLISH_INITIAL;
  1905. } else {
  1906. publish_type = SIP_PUBLISH_MODIFY;
  1907. cc_entry = monitor_instance->suspension_entry->instance_data;
  1908. }
  1909. cc_entry->current_state = CC_CLOSED;
  1910. if (ast_strlen_zero(monitor_instance->notify_uri)) {
  1911. /* If we have no set notify_uri, then what this means is that we have
  1912. * not received a NOTIFY from this destination stating that he is
  1913. * currently available.
  1914. *
  1915. * This situation can arise when the core calls the suspend callbacks
  1916. * of multiple destinations. If one of the other destinations aside
  1917. * from this one notified Asterisk that he is available, then there
  1918. * is no reason to take any suspension action on this device. Rather,
  1919. * we should return now and if we receive a NOTIFY while monitoring
  1920. * is still "suspended" then we can immediately respond with the
  1921. * proper PUBLISH to let this endpoint know what is going on.
  1922. */
  1923. return 0;
  1924. }
  1925. construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
  1926. return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
  1927. }
  1928. static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
  1929. {
  1930. struct sip_monitor_instance *monitor_instance = monitor->private_data;
  1931. struct cc_epa_entry *cc_entry;
  1932. if (!monitor_instance) {
  1933. return -1;
  1934. }
  1935. ast_assert(monitor_instance->suspension_entry != NULL);
  1936. cc_entry = monitor_instance->suspension_entry->instance_data;
  1937. cc_entry->current_state = CC_OPEN;
  1938. if (ast_strlen_zero(monitor_instance->notify_uri)) {
  1939. /* This means we are being asked to unsuspend a call leg we never
  1940. * sent a PUBLISH on. As such, there is no reason to send another
  1941. * PUBLISH at this point either. We can just return instead.
  1942. */
  1943. return 0;
  1944. }
  1945. construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
  1946. return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
  1947. }
  1948. static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
  1949. {
  1950. if (*sched_id != -1) {
  1951. AST_SCHED_DEL(sched, *sched_id);
  1952. ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
  1953. }
  1954. return 0;
  1955. }
  1956. static void sip_cc_monitor_destructor(void *private_data)
  1957. {
  1958. struct sip_monitor_instance *monitor_instance = private_data;
  1959. ao2_unlink(sip_monitor_instances, monitor_instance);
  1960. ast_module_unref(ast_module_info->self);
  1961. }
  1962. static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
  1963. {
  1964. char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
  1965. char *uri;
  1966. char *purpose;
  1967. char *service_str;
  1968. static const char cc_purpose[] = "purpose=call-completion";
  1969. static const int cc_purpose_len = sizeof(cc_purpose) - 1;
  1970. if (ast_strlen_zero(call_info)) {
  1971. /* No Call-Info present. Definitely no CC offer */
  1972. return -1;
  1973. }
  1974. uri = strsep(&call_info, ";");
  1975. while ((purpose = strsep(&call_info, ";"))) {
  1976. if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
  1977. break;
  1978. }
  1979. }
  1980. if (!purpose) {
  1981. /* We didn't find the appropriate purpose= parameter. Oh well */
  1982. return -1;
  1983. }
  1984. /* Okay, call-completion has been offered. Let's figure out what type of service this is */
  1985. while ((service_str = strsep(&call_info, ";"))) {
  1986. if (!strncmp(service_str, "m=", 2)) {
  1987. break;
  1988. }
  1989. }
  1990. if (!service_str) {
  1991. /* So they didn't offer a particular service, We'll just go with CCBS since it really
  1992. * doesn't matter anyway
  1993. */
  1994. service_str = "BS";
  1995. } else {
  1996. /* We already determined that there is an "m=" so no need to check
  1997. * the result of this strsep
  1998. */
  1999. strsep(&service_str, "=");
  2000. }
  2001. if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
  2002. /* Invalid service offered */
  2003. return -1;
  2004. }
  2005. ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
  2006. return 0;
  2007. }
  2008. /*
  2009. * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
  2010. *
  2011. * After taking care of some formalities to be sure that this call is eligible for CC,
  2012. * we first try to see if we can make use of native CC. We grab the information from
  2013. * the passed-in sip_request (which is always a response to an INVITE). If we can
  2014. * use native CC monitoring for the call, then so be it.
  2015. *
  2016. * If native cc monitoring is not possible or not supported, then we will instead attempt
  2017. * to use generic monitoring. Falling back to generic from a failed attempt at using native
  2018. * monitoring will only work if the monitor policy of the endpoint is "always"
  2019. *
  2020. * \param pvt The current dialog. Contains CC parameters for the endpoint
  2021. * \param req The response to the INVITE we want to inspect
  2022. * \param service The service to use if generic monitoring is to be used. For native
  2023. * monitoring, we get the service from the SIP response itself
  2024. */
  2025. static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
  2026. {
  2027. enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
  2028. int core_id;
  2029. char interface_name[AST_CHANNEL_NAME];
  2030. if (monitor_policy == AST_CC_MONITOR_NEVER) {
  2031. /* Don't bother, just return */
  2032. return;
  2033. }
  2034. if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
  2035. /* For some reason, CC is invalid, so don't try it! */
  2036. return;
  2037. }
  2038. ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
  2039. if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
  2040. char subscribe_uri[SIPBUFSIZE];
  2041. char device_name[AST_CHANNEL_NAME];
  2042. enum ast_cc_service_type offered_service;
  2043. struct sip_monitor_instance *monitor_instance;
  2044. if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
  2045. /* If CC isn't being offered to us, or for some reason the CC offer is
  2046. * not formatted correctly, then it may still be possible to use generic
  2047. * call completion since the monitor policy may be "always"
  2048. */
  2049. goto generic;
  2050. }
  2051. ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
  2052. if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
  2053. /* Same deal. We can try using generic still */
  2054. goto generic;
  2055. }
  2056. /* We bump the refcount of chan_sip because once we queue this frame, the CC core
  2057. * will have a reference to callbacks in this module. We decrement the module
  2058. * refcount once the monitor destructor is called
  2059. */
  2060. ast_module_ref(ast_module_info->self);
  2061. ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
  2062. ao2_ref(monitor_instance, -1);
  2063. return;
  2064. }
  2065. generic:
  2066. if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
  2067. ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
  2068. }
  2069. }
  2070. /*! \brief Working TLS connection configuration */
  2071. static struct ast_tls_config sip_tls_cfg;
  2072. /*! \brief Default TLS connection configuration */
  2073. static struct ast_tls_config default_tls_cfg;
  2074. /*! \brief Default DTLS connection configuration */
  2075. static struct ast_rtp_dtls_cfg default_dtls_cfg;
  2076. /*! \brief The TCP server definition */
  2077. static struct ast_tcptls_session_args sip_tcp_desc = {
  2078. .accept_fd = -1,
  2079. .master = AST_PTHREADT_NULL,
  2080. .tls_cfg = NULL,
  2081. .poll_timeout = -1,
  2082. .name = "SIP TCP server",
  2083. .accept_fn = ast_tcptls_server_root,
  2084. .worker_fn = sip_tcp_worker_fn,
  2085. };
  2086. /*! \brief The TCP/TLS server definition */
  2087. static struct ast_tcptls_session_args sip_tls_desc = {
  2088. .accept_fd = -1,
  2089. .master = AST_PTHREADT_NULL,
  2090. .tls_cfg = &sip_tls_cfg,
  2091. .poll_timeout = -1,
  2092. .name = "SIP TLS server",
  2093. .accept_fn = ast_tcptls_server_root,
  2094. .worker_fn = sip_tcp_worker_fn,
  2095. };
  2096. /*! \brief Append to SIP dialog history
  2097. \return Always returns 0 */
  2098. #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
  2099. /*! \brief map from an integer value to a string.
  2100. * If no match is found, return errorstring
  2101. */
  2102. static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
  2103. {
  2104. const struct _map_x_s *cur;
  2105. for (cur = table; cur->s; cur++) {
  2106. if (cur->x == x) {
  2107. return cur->s;
  2108. }
  2109. }
  2110. return errorstring;
  2111. }
  2112. /*! \brief map from a string to an integer value, case insensitive.
  2113. * If no match is found, return errorvalue.
  2114. */
  2115. static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
  2116. {
  2117. const struct _map_x_s *cur;
  2118. for (cur = table; cur->s; cur++) {
  2119. if (!strcasecmp(cur->s, s)) {
  2120. return cur->x;
  2121. }
  2122. }
  2123. return errorvalue;
  2124. }
  2125. static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
  2126. {
  2127. enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
  2128. int i;
  2129. for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
  2130. if (!strcasecmp(text, sip_reason_table[i].text)) {
  2131. ast = sip_reason_table[i].code;
  2132. break;
  2133. }
  2134. }
  2135. return ast;
  2136. }
  2137. static const char *sip_reason_code_to_str(struct ast_party_redirecting_reason *reason, int *table_lookup)
  2138. {
  2139. int code = reason->code;
  2140. /* If there's a specific string set, then we just
  2141. * use it.
  2142. */
  2143. if (!ast_strlen_zero(reason->str)) {
  2144. /* If we care about whether this can be found in
  2145. * the table, then we need to check about that.
  2146. */
  2147. if (table_lookup) {
  2148. /* If the string is literally "unknown" then don't bother with the lookup
  2149. * because it can lead to a false negative.
  2150. */
  2151. if (!strcasecmp(reason->str, "unknown") ||
  2152. sip_reason_str_to_code(reason->str) != AST_REDIRECTING_REASON_UNKNOWN) {
  2153. *table_lookup = TRUE;
  2154. } else {
  2155. *table_lookup = FALSE;
  2156. }
  2157. }
  2158. return reason->str;
  2159. }
  2160. if (table_lookup) {
  2161. *table_lookup = TRUE;
  2162. }
  2163. if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
  2164. return sip_reason_table[code].text;
  2165. }
  2166. return "unknown";
  2167. }
  2168. /*!
  2169. * \brief generic function for determining if a correct transport is being
  2170. * used to contact a peer
  2171. *
  2172. * this is done as a macro so that the "tmpl" var can be passed either a
  2173. * sip_request or a sip_peer
  2174. */
  2175. #define check_request_transport(peer, tmpl) ({ \
  2176. int ret = 0; \
  2177. if (peer->socket.type == tmpl->socket.type) \
  2178. ; \
  2179. else if (!(peer->transports & tmpl->socket.type)) {\
  2180. ast_log(LOG_ERROR, \
  2181. "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
  2182. sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
  2183. ); \
  2184. ret = 1; \
  2185. } else if (peer->socket.type & AST_TRANSPORT_TLS) { \
  2186. ast_log(LOG_WARNING, \
  2187. "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
  2188. peer->name, sip_get_transport(tmpl->socket.type) \
  2189. ); \
  2190. } else { \
  2191. ast_debug(1, \
  2192. "peer '%s' has contacted us over %s even though we prefer %s.\n", \
  2193. peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
  2194. ); \
  2195. }\
  2196. (ret); \
  2197. })
  2198. /*! \brief
  2199. * duplicate a list of channel variables, \return the copy.
  2200. */
  2201. static struct ast_variable *copy_vars(struct ast_variable *src)
  2202. {
  2203. struct ast_variable *res = NULL, *tmp, *v = NULL;
  2204. for (v = src ; v ; v = v->next) {
  2205. if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
  2206. tmp->next = res;
  2207. res = tmp;
  2208. }
  2209. }
  2210. return res;
  2211. }
  2212. static void tcptls_packet_destructor(void *obj)
  2213. {
  2214. struct tcptls_packet *packet = obj;
  2215. ast_free(packet->data);
  2216. }
  2217. static void sip_tcptls_client_args_destructor(void *obj)
  2218. {
  2219. struct ast_tcptls_session_args *args = obj;
  2220. if (args->tls_cfg) {
  2221. ast_free(args->tls_cfg->certfile);
  2222. ast_free(args->tls_cfg->pvtfile);
  2223. ast_free(args->tls_cfg->cipher);
  2224. ast_free(args->tls_cfg->cafile);
  2225. ast_free(args->tls_cfg->capath);
  2226. ast_ssl_teardown(args->tls_cfg);
  2227. }
  2228. ast_free(args->tls_cfg);
  2229. ast_free((char *) args->name);
  2230. }
  2231. static void sip_threadinfo_destructor(void *obj)
  2232. {
  2233. struct sip_threadinfo *th = obj;
  2234. struct tcptls_packet *packet;
  2235. if (th->alert_pipe[1] > -1) {
  2236. close(th->alert_pipe[0]);
  2237. }
  2238. if (th->alert_pipe[1] > -1) {
  2239. close(th->alert_pipe[1]);
  2240. }
  2241. th->alert_pipe[0] = th->alert_pipe[1] = -1;
  2242. while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
  2243. ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
  2244. }
  2245. if (th->tcptls_session) {
  2246. ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
  2247. }
  2248. }
  2249. /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
  2250. static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
  2251. {
  2252. struct sip_threadinfo *th;
  2253. if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
  2254. return NULL;
  2255. }
  2256. th->alert_pipe[0] = th->alert_pipe[1] = -1;
  2257. if (pipe(th->alert_pipe) == -1) {
  2258. ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
  2259. ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
  2260. return NULL;
  2261. }
  2262. ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
  2263. th->tcptls_session = tcptls_session;
  2264. th->type = transport ? transport : (tcptls_session->ssl ? AST_TRANSPORT_TLS: AST_TRANSPORT_TCP);
  2265. ao2_t_link(threadt, th, "Adding new tcptls helper thread");
  2266. ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
  2267. return th;
  2268. }
  2269. /*! \brief used to indicate to a tcptls thread that data is ready to be written */
  2270. static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
  2271. {
  2272. int res = len;
  2273. struct sip_threadinfo *th = NULL;
  2274. struct tcptls_packet *packet = NULL;
  2275. struct sip_threadinfo tmp = {
  2276. .tcptls_session = tcptls_session,
  2277. };
  2278. enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
  2279. if (!tcptls_session) {
  2280. return XMIT_ERROR;
  2281. }
  2282. ao2_lock(tcptls_session);
  2283. if ((tcptls_session->fd == -1) ||
  2284. !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
  2285. !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
  2286. !(packet->data = ast_str_create(len))) {
  2287. goto tcptls_write_setup_error;
  2288. }
  2289. /* goto tcptls_write_error should _NOT_ be used beyond this point */
  2290. ast_str_set(&packet->data, 0, "%s", (char *) buf);
  2291. packet->len = len;
  2292. /* alert tcptls thread handler that there is a packet to be sent.
  2293. * must lock the thread info object to guarantee control of the
  2294. * packet queue */
  2295. ao2_lock(th);
  2296. if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
  2297. ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
  2298. ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
  2299. packet = NULL;
  2300. res = XMIT_ERROR;
  2301. } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
  2302. AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
  2303. }
  2304. ao2_unlock(th);
  2305. ao2_unlock(tcptls_session);
  2306. ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
  2307. return res;
  2308. tcptls_write_setup_error:
  2309. if (th) {
  2310. ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
  2311. }
  2312. if (packet) {
  2313. ao2_t_ref(packet, -1, "could not allocate packet's data");
  2314. }
  2315. ao2_unlock(tcptls_session);
  2316. return XMIT_ERROR;
  2317. }
  2318. /*! \brief SIP TCP connection handler */
  2319. static void *sip_tcp_worker_fn(void *data)
  2320. {
  2321. struct ast_tcptls_session_instance *tcptls_session = data;
  2322. return _sip_tcp_helper_thread(tcptls_session);
  2323. }
  2324. /*! \brief SIP WebSocket connection handler */
  2325. static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
  2326. {
  2327. int res;
  2328. if (ast_websocket_set_nonblock(session)) {
  2329. goto end;
  2330. }
  2331. if (ast_websocket_set_timeout(session, sip_cfg.websocket_write_timeout)) {
  2332. goto end;
  2333. }
  2334. while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
  2335. char *payload;
  2336. uint64_t payload_len;
  2337. enum ast_websocket_opcode opcode;
  2338. int fragmented;
  2339. if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
  2340. /* We err on the side of caution and terminate the session if any error occurs */
  2341. break;
  2342. }
  2343. if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
  2344. struct sip_request req = { 0, };
  2345. char data[payload_len + 1];
  2346. if (!(req.data = ast_str_create(payload_len + 1))) {
  2347. goto end;
  2348. }
  2349. strncpy(data, payload, payload_len);
  2350. data[payload_len] = '\0';
  2351. if (ast_str_set(&req.data, -1, "%s", data) == AST_DYNSTR_BUILD_FAILED) {
  2352. deinit_req(&req);
  2353. goto end;
  2354. }
  2355. req.socket.fd = ast_websocket_fd(session);
  2356. set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? AST_TRANSPORT_WSS : AST_TRANSPORT_WS);
  2357. req.socket.ws_session = session;
  2358. handle_request_do(&req, ast_websocket_remote_address(session));
  2359. deinit_req(&req);
  2360. } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
  2361. break;
  2362. }
  2363. }
  2364. end:
  2365. ast_websocket_unref(session);
  2366. }
  2367. /*! \brief Check if the authtimeout has expired.
  2368. * \param start the time when the session started
  2369. *
  2370. * \retval 0 the timeout has expired
  2371. * \retval -1 error
  2372. * \return the number of milliseconds until the timeout will expire
  2373. */
  2374. static int sip_check_authtimeout(time_t start)
  2375. {
  2376. int timeout;
  2377. time_t now;
  2378. if(time(&now) == -1) {
  2379. ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
  2380. return -1;
  2381. }
  2382. timeout = (authtimeout - (now - start)) * 1000;
  2383. if (timeout < 0) {
  2384. /* we have timed out */
  2385. return 0;
  2386. }
  2387. return timeout;
  2388. }
  2389. /*!
  2390. * \brief Indication of a TCP message's integrity
  2391. */
  2392. enum message_integrity {
  2393. /*!
  2394. * The message has an error in it with
  2395. * regards to its Content-Length header
  2396. */
  2397. MESSAGE_INVALID,
  2398. /*!
  2399. * The message is incomplete
  2400. */
  2401. MESSAGE_FRAGMENT,
  2402. /*!
  2403. * The data contains a complete message
  2404. * plus a fragment of another.
  2405. */
  2406. MESSAGE_FRAGMENT_COMPLETE,
  2407. /*!
  2408. * The message is complete
  2409. */
  2410. MESSAGE_COMPLETE,
  2411. };
  2412. /*!
  2413. * \brief
  2414. * Get the content length from an unparsed SIP message
  2415. *
  2416. * \param message The unparsed SIP message headers
  2417. * \return The value of the Content-Length header or -1 if message is invalid
  2418. */
  2419. static int read_raw_content_length(const char *message)
  2420. {
  2421. char *content_length_str;
  2422. int content_length = -1;
  2423. struct ast_str *msg_copy;
  2424. char *msg;
  2425. /* Using a ast_str because lws2sws takes one of those */
  2426. if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
  2427. return -1;
  2428. }
  2429. ast_str_set(&msg_copy, 0, "%s", message);
  2430. if (sip_cfg.pedanticsipchecking) {
  2431. lws2sws(msg_copy);
  2432. }
  2433. msg = ast_str_buffer(msg_copy);
  2434. /* Let's find a Content-Length header */
  2435. if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
  2436. content_length_str += sizeof("\nContent-Length:") - 1;
  2437. } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
  2438. content_length_str += sizeof("\nl:") - 1;
  2439. } else {
  2440. /* RFC 3261 18.3
  2441. * "In the case of stream-oriented transports such as TCP, the Content-
  2442. * Length header field indicates the size of the body. The Content-
  2443. * Length header field MUST be used with stream oriented transports."
  2444. */
  2445. goto done;
  2446. }
  2447. /* Double-check that this is a complete header */
  2448. if (!strchr(content_length_str, '\n')) {
  2449. goto done;
  2450. }
  2451. if (sscanf(content_length_str, "%30d", &content_length) != 1) {
  2452. content_length = -1;
  2453. }
  2454. done:
  2455. ast_free(msg_copy);
  2456. return content_length;
  2457. }
  2458. /*!
  2459. * \brief Check that a message received over TCP is a full message
  2460. *
  2461. * This will take the information read in and then determine if
  2462. * 1) The message is a full SIP request
  2463. * 2) The message is a partial SIP request
  2464. * 3) The message contains a full SIP request along with another partial request
  2465. * \param data The unparsed incoming SIP message.
  2466. * \param request The resulting request with extra fragments removed.
  2467. * \param overflow If the message contains more than a full request, this is the remainder of the message
  2468. * \return The resulting integrity of the message
  2469. */
  2470. static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
  2471. {
  2472. char *message = ast_str_buffer(*request);
  2473. char *body;
  2474. int content_length;
  2475. int message_len = ast_str_strlen(*request);
  2476. int body_len;
  2477. /* Important pieces to search for in a SIP request are \r\n\r\n. This
  2478. * marks either
  2479. * 1) The division between the headers and body
  2480. * 2) The end of the SIP request
  2481. */
  2482. body = strstr(message, "\r\n\r\n");
  2483. if (!body) {
  2484. /* This is clearly a partial message since we haven't reached an end
  2485. * yet.
  2486. */
  2487. return MESSAGE_FRAGMENT;
  2488. }
  2489. body += sizeof("\r\n\r\n") - 1;
  2490. body_len = message_len - (body - message);
  2491. body[-1] = '\0';
  2492. content_length = read_raw_content_length(message);
  2493. body[-1] = '\n';
  2494. if (content_length < 0) {
  2495. return MESSAGE_INVALID;
  2496. } else if (content_length == 0) {
  2497. /* We've definitely received an entire message. We need
  2498. * to check if there's also a fragment of another message
  2499. * in addition.
  2500. */
  2501. if (body_len == 0) {
  2502. return MESSAGE_COMPLETE;
  2503. } else {
  2504. ast_str_append(overflow, 0, "%s", body);
  2505. ast_str_truncate(*request, message_len - body_len);
  2506. return MESSAGE_FRAGMENT_COMPLETE;
  2507. }
  2508. }
  2509. /* Positive content length. Let's see what sort of
  2510. * message body we're dealing with.
  2511. */
  2512. if (body_len < content_length) {
  2513. /* We don't have the full message body yet */
  2514. return MESSAGE_FRAGMENT;
  2515. } else if (body_len > content_length) {
  2516. /* We have the full message plus a fragment of a further
  2517. * message
  2518. */
  2519. ast_str_append(overflow, 0, "%s", body + content_length);
  2520. ast_str_truncate(*request, message_len - (body_len - content_length));
  2521. return MESSAGE_FRAGMENT_COMPLETE;
  2522. } else {
  2523. /* Yay! Full message with no extra content */
  2524. return MESSAGE_COMPLETE;
  2525. }
  2526. }
  2527. /*!
  2528. * \brief Read SIP request or response from a TCP/TLS connection
  2529. *
  2530. * \param req The request structure to be filled in
  2531. * \param tcptls_session The TCP/TLS connection from which to read
  2532. * \retval -1 Failed to read data
  2533. * \retval 0 Successfully read data
  2534. */
  2535. static int sip_tcptls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
  2536. int authenticated, time_t start)
  2537. {
  2538. enum message_integrity message_integrity = MESSAGE_FRAGMENT;
  2539. while (message_integrity == MESSAGE_FRAGMENT) {
  2540. size_t datalen;
  2541. if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
  2542. char readbuf[4097];
  2543. int timeout;
  2544. int res;
  2545. if (!tcptls_session->client && !authenticated) {
  2546. if ((timeout = sip_check_authtimeout(start)) < 0) {
  2547. return -1;
  2548. }
  2549. if (timeout == 0) {
  2550. ast_debug(2, "SIP TCP/TLS server timed out\n");
  2551. return -1;
  2552. }
  2553. } else {
  2554. timeout = -1;
  2555. }
  2556. res = ast_wait_for_input(tcptls_session->fd, timeout);
  2557. if (res < 0) {
  2558. ast_debug(2, "SIP TCP/TLS server :: ast_wait_for_input returned %d\n", res);
  2559. return -1;
  2560. } else if (res == 0) {
  2561. ast_debug(2, "SIP TCP/TLS server timed out\n");
  2562. return -1;
  2563. }
  2564. res = ast_tcptls_server_read(tcptls_session, readbuf, sizeof(readbuf) - 1);
  2565. if (res < 0) {
  2566. if (errno == EAGAIN || errno == EINTR) {
  2567. continue;
  2568. }
  2569. ast_debug(2, "SIP TCP/TLS server error when receiving data\n");
  2570. return -1;
  2571. } else if (res == 0) {
  2572. ast_debug(2, "SIP TCP/TLS server has shut down\n");
  2573. return -1;
  2574. }
  2575. readbuf[res] = '\0';
  2576. ast_str_append(&req->data, 0, "%s", readbuf);
  2577. } else {
  2578. ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
  2579. ast_str_reset(tcptls_session->overflow_buf);
  2580. }
  2581. datalen = ast_str_strlen(req->data);
  2582. if (datalen > SIP_MAX_PACKET_SIZE) {
  2583. ast_log(LOG_WARNING, "Rejecting TCP/TLS packet from '%s' because way too large: %zu\n",
  2584. ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
  2585. return -1;
  2586. }
  2587. message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
  2588. }
  2589. return 0;
  2590. }
  2591. /*! \brief SIP TCP thread management function
  2592. This function reads from the socket, parses the packet into a request
  2593. */
  2594. static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
  2595. {
  2596. int res, timeout = -1, authenticated = 0, flags;
  2597. time_t start;
  2598. struct sip_request req = { 0, } , reqcpy = { 0, };
  2599. struct sip_threadinfo *me = NULL;
  2600. char buf[1024] = "";
  2601. struct pollfd fds[2] = { { 0 }, { 0 }, };
  2602. struct ast_tcptls_session_args *ca = NULL;
  2603. /* If this is a server session, then the connection has already been
  2604. * setup. Check if the authlimit has been reached and if not create the
  2605. * threadinfo object so we can access this thread for writing.
  2606. *
  2607. * if this is a client connection more work must be done.
  2608. * 1. We own the parent session args for a client connection. This pointer needs
  2609. * to be held on to so we can decrement it's ref count on thread destruction.
  2610. * 2. The threadinfo object was created before this thread was launched, however
  2611. * it must be found within the threadt table.
  2612. * 3. Last, the tcptls_session must be started.
  2613. */
  2614. if (!tcptls_session->client) {
  2615. if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
  2616. /* unauth_sessions is decremented in the cleanup code */
  2617. goto cleanup;
  2618. }
  2619. if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
  2620. ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
  2621. goto cleanup;
  2622. }
  2623. flags |= O_NONBLOCK;
  2624. if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
  2625. ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
  2626. goto cleanup;
  2627. }
  2628. if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? AST_TRANSPORT_TLS : AST_TRANSPORT_TCP))) {
  2629. goto cleanup;
  2630. }
  2631. ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
  2632. } else {
  2633. struct sip_threadinfo tmp = {
  2634. .tcptls_session = tcptls_session,
  2635. };
  2636. if ((!(ca = tcptls_session->parent)) ||
  2637. (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
  2638. (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
  2639. goto cleanup;
  2640. }
  2641. }
  2642. flags = 1;
  2643. if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
  2644. ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
  2645. goto cleanup;
  2646. }
  2647. me->threadid = pthread_self();
  2648. ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
  2649. /* set up pollfd to watch for reads on both the socket and the alert_pipe */
  2650. fds[0].fd = tcptls_session->fd;
  2651. fds[1].fd = me->alert_pipe[0];
  2652. fds[0].events = fds[1].events = POLLIN | POLLPRI;
  2653. if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
  2654. goto cleanup;
  2655. }
  2656. if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
  2657. goto cleanup;
  2658. }
  2659. if(time(&start) == -1) {
  2660. ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
  2661. goto cleanup;
  2662. }
  2663. /*
  2664. * We cannot let the stream exclusively wait for data to arrive.
  2665. * We have to wake up the task to send outgoing messages.
  2666. */
  2667. ast_tcptls_stream_set_exclusive_input(tcptls_session->stream_cookie, 0);
  2668. ast_tcptls_stream_set_timeout_sequence(tcptls_session->stream_cookie, ast_tvnow(),
  2669. tcptls_session->client ? -1 : (authtimeout * 1000));
  2670. for (;;) {
  2671. struct ast_str *str_save;
  2672. if (!tcptls_session->client && req.authenticated && !authenticated) {
  2673. authenticated = 1;
  2674. ast_tcptls_stream_set_timeout_disable(tcptls_session->stream_cookie);
  2675. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  2676. }
  2677. /* calculate the timeout for unauthenticated server sessions */
  2678. if (!tcptls_session->client && !authenticated ) {
  2679. if ((timeout = sip_check_authtimeout(start)) < 0) {
  2680. goto cleanup;
  2681. }
  2682. if (timeout == 0) {
  2683. ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
  2684. goto cleanup;
  2685. }
  2686. } else {
  2687. timeout = -1;
  2688. }
  2689. if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
  2690. res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
  2691. if (res < 0) {
  2692. ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
  2693. goto cleanup;
  2694. } else if (res == 0) {
  2695. /* timeout */
  2696. ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
  2697. goto cleanup;
  2698. }
  2699. }
  2700. /*
  2701. * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
  2702. * and writes from alert_pipe fd.
  2703. */
  2704. if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
  2705. fds[0].revents = 0;
  2706. /* clear request structure */
  2707. str_save = req.data;
  2708. memset(&req, 0, sizeof(req));
  2709. req.data = str_save;
  2710. ast_str_reset(req.data);
  2711. str_save = reqcpy.data;
  2712. memset(&reqcpy, 0, sizeof(reqcpy));
  2713. reqcpy.data = str_save;
  2714. ast_str_reset(reqcpy.data);
  2715. memset(buf, 0, sizeof(buf));
  2716. if (tcptls_session->ssl) {
  2717. set_socket_transport(&req.socket, AST_TRANSPORT_TLS);
  2718. req.socket.port = htons(ourport_tls);
  2719. } else {
  2720. set_socket_transport(&req.socket, AST_TRANSPORT_TCP);
  2721. req.socket.port = htons(ourport_tcp);
  2722. }
  2723. req.socket.fd = tcptls_session->fd;
  2724. res = sip_tcptls_read(&req, tcptls_session, authenticated, start);
  2725. if (res < 0) {
  2726. goto cleanup;
  2727. }
  2728. req.socket.tcptls_session = tcptls_session;
  2729. req.socket.ws_session = NULL;
  2730. handle_request_do(&req, &tcptls_session->remote_address);
  2731. }
  2732. if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
  2733. enum sip_tcptls_alert alert;
  2734. struct tcptls_packet *packet;
  2735. fds[1].revents = 0;
  2736. if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
  2737. ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
  2738. continue;
  2739. }
  2740. switch (alert) {
  2741. case TCPTLS_ALERT_STOP:
  2742. goto cleanup;
  2743. case TCPTLS_ALERT_DATA:
  2744. ao2_lock(me);
  2745. if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
  2746. ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
  2747. }
  2748. ao2_unlock(me);
  2749. if (packet) {
  2750. if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
  2751. ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
  2752. }
  2753. ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
  2754. }
  2755. break;
  2756. default:
  2757. ast_log(LOG_ERROR, "Unknown tcptls thread alert '%u'\n", alert);
  2758. }
  2759. }
  2760. }
  2761. ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
  2762. cleanup:
  2763. if (tcptls_session && !tcptls_session->client && !authenticated) {
  2764. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  2765. }
  2766. if (me) {
  2767. ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
  2768. ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
  2769. }
  2770. deinit_req(&reqcpy);
  2771. deinit_req(&req);
  2772. /* if client, we own the parent session arguments and must decrement ref */
  2773. if (ca) {
  2774. ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
  2775. }
  2776. if (tcptls_session) {
  2777. ao2_lock(tcptls_session);
  2778. ast_tcptls_close_session_file(tcptls_session);
  2779. tcptls_session->parent = NULL;
  2780. ao2_unlock(tcptls_session);
  2781. ao2_ref(tcptls_session, -1);
  2782. tcptls_session = NULL;
  2783. }
  2784. return NULL;
  2785. }
  2786. static void peer_sched_cleanup(struct sip_peer *peer)
  2787. {
  2788. if (peer->pokeexpire != -1) {
  2789. AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
  2790. sip_unref_peer(peer, "removing poke peer ref"));
  2791. }
  2792. if (peer->expire != -1) {
  2793. AST_SCHED_DEL_UNREF(sched, peer->expire,
  2794. sip_unref_peer(peer, "remove register expire ref"));
  2795. }
  2796. if (peer->keepalivesend != -1) {
  2797. AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
  2798. sip_unref_peer(peer, "remove keepalive peer ref"));
  2799. }
  2800. }
  2801. typedef enum {
  2802. SIP_PEERS_MARKED,
  2803. SIP_PEERS_ALL,
  2804. } peer_unlink_flag_t;
  2805. /* this func is used with ao2_callback to unlink/delete all marked or linked
  2806. peers, depending on arg */
  2807. static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
  2808. {
  2809. struct sip_peer *peer = peerobj;
  2810. peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
  2811. if (which == SIP_PEERS_ALL || peer->the_mark) {
  2812. peer_sched_cleanup(peer);
  2813. if (peer->dnsmgr) {
  2814. ast_dnsmgr_release(peer->dnsmgr);
  2815. peer->dnsmgr = NULL;
  2816. sip_unref_peer(peer, "Release peer from dnsmgr");
  2817. }
  2818. return CMP_MATCH;
  2819. }
  2820. return 0;
  2821. }
  2822. static void unlink_peers_from_tables(peer_unlink_flag_t flag)
  2823. {
  2824. ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
  2825. match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
  2826. ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
  2827. match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers_by_ip");
  2828. }
  2829. /* \brief Unlink all marked peers from ao2 containers */
  2830. static void unlink_marked_peers_from_tables(void)
  2831. {
  2832. unlink_peers_from_tables(SIP_PEERS_MARKED);
  2833. }
  2834. static void unlink_all_peers_from_tables(void)
  2835. {
  2836. unlink_peers_from_tables(SIP_PEERS_ALL);
  2837. }
  2838. /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
  2839. *
  2840. * This function sets pvt's outboundproxy pointer to the one referenced
  2841. * by the proxy parameter. Because proxy may be a refcounted object, and
  2842. * because pvt's old outboundproxy may also be a refcounted object, we need
  2843. * to maintain the proper refcounts.
  2844. *
  2845. * \param pvt The sip_pvt for which we wish to set the outboundproxy
  2846. * \param proxy The sip_proxy which we will point pvt towards.
  2847. * \return Returns void
  2848. */
  2849. static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
  2850. {
  2851. struct sip_proxy *old_obproxy = pvt->outboundproxy;
  2852. /* The sip_cfg.outboundproxy is statically allocated, and so
  2853. * we don't ever need to adjust refcounts for it
  2854. */
  2855. if (proxy && proxy != &sip_cfg.outboundproxy) {
  2856. ao2_ref(proxy, +1);
  2857. }
  2858. pvt->outboundproxy = proxy;
  2859. if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
  2860. ao2_ref(old_obproxy, -1);
  2861. }
  2862. }
  2863. /*!
  2864. * \brief Unlink a dialog from the dialogs container, as well as any other places
  2865. * that it may be currently stored.
  2866. *
  2867. * \note A reference to the dialog must be held before calling this function, and this
  2868. * function does not release that reference.
  2869. */
  2870. void dialog_unlink_all(struct sip_pvt *dialog)
  2871. {
  2872. struct sip_pkt *cp;
  2873. struct ast_channel *owner;
  2874. dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
  2875. ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
  2876. ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
  2877. ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
  2878. /* Unlink us from the owner (channel) if we have one */
  2879. owner = sip_pvt_lock_full(dialog);
  2880. if (owner) {
  2881. ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
  2882. ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
  2883. ast_channel_unlock(owner);
  2884. ast_channel_unref(owner);
  2885. sip_set_owner(dialog, NULL);
  2886. }
  2887. sip_pvt_unlock(dialog);
  2888. if (dialog->registry) {
  2889. if (dialog->registry->call == dialog) {
  2890. dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
  2891. }
  2892. ao2_t_replace(dialog->registry, NULL, "delete dialog->registry");
  2893. }
  2894. if (dialog->stateid != -1) {
  2895. ast_extension_state_del(dialog->stateid, cb_extensionstate);
  2896. dialog->stateid = -1;
  2897. }
  2898. /* Remove link from peer to subscription of MWI */
  2899. if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
  2900. dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
  2901. }
  2902. if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
  2903. dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
  2904. }
  2905. /* remove all current packets in this dialog */
  2906. while((cp = dialog->packets)) {
  2907. dialog->packets = dialog->packets->next;
  2908. AST_SCHED_DEL(sched, cp->retransid);
  2909. dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
  2910. if (cp->data) {
  2911. ast_free(cp->data);
  2912. }
  2913. ast_free(cp);
  2914. }
  2915. AST_SCHED_DEL_UNREF(sched, dialog->waitid, dialog_unref(dialog, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
  2916. AST_SCHED_DEL_UNREF(sched, dialog->initid, dialog_unref(dialog, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
  2917. if (dialog->reinviteid > -1) {
  2918. AST_SCHED_DEL_UNREF(sched, dialog->reinviteid, dialog_unref(dialog, "clear ref for reinvite_timeout"));
  2919. }
  2920. if (dialog->autokillid > -1) {
  2921. AST_SCHED_DEL_UNREF(sched, dialog->autokillid, dialog_unref(dialog, "when you delete the autokillid sched, you should dec the refcount for the stored dialog ptr"));
  2922. }
  2923. if (dialog->request_queue_sched_id > -1) {
  2924. AST_SCHED_DEL_UNREF(sched, dialog->request_queue_sched_id, dialog_unref(dialog, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
  2925. }
  2926. AST_SCHED_DEL_UNREF(sched, dialog->provisional_keepalive_sched_id, dialog_unref(dialog, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
  2927. if (dialog->t38id > -1) {
  2928. AST_SCHED_DEL_UNREF(sched, dialog->t38id, dialog_unref(dialog, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
  2929. }
  2930. if (dialog->stimer) {
  2931. stop_session_timer(dialog);
  2932. }
  2933. dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
  2934. }
  2935. static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
  2936. __attribute__((format(printf, 2, 3)));
  2937. /*! \brief Convert transfer status to string */
  2938. static const char *referstatus2str(enum referstatus rstatus)
  2939. {
  2940. return map_x_s(referstatusstrings, rstatus, "");
  2941. }
  2942. static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
  2943. {
  2944. if (pvt->final_destruction_scheduled) {
  2945. return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
  2946. }
  2947. append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
  2948. if (!pvt->needdestroy) {
  2949. pvt->needdestroy = 1;
  2950. ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
  2951. }
  2952. }
  2953. /*! \brief Initialize the initital request packet in the pvt structure.
  2954. This packet is used for creating replies and future requests in
  2955. a dialog */
  2956. static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
  2957. {
  2958. if (p->initreq.headers) {
  2959. ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
  2960. } else {
  2961. ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  2962. }
  2963. /* Use this as the basis */
  2964. copy_request(&p->initreq, req);
  2965. parse_request(&p->initreq);
  2966. if (req->debug) {
  2967. ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  2968. }
  2969. }
  2970. /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
  2971. static void sip_alreadygone(struct sip_pvt *dialog)
  2972. {
  2973. ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
  2974. dialog->alreadygone = 1;
  2975. }
  2976. /*! Resolve DNS srv name or host name in a sip_proxy structure */
  2977. static int proxy_update(struct sip_proxy *proxy)
  2978. {
  2979. /* if it's actually an IP address and not a name,
  2980. there's no need for a managed lookup */
  2981. if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
  2982. /* Ok, not an IP address, then let's check if it's a domain or host */
  2983. /* XXX Todo - if we have proxy port, don't do SRV */
  2984. proxy->ip.ss.ss_family = get_address_family_filter(AST_TRANSPORT_UDP); /* Filter address family */
  2985. if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
  2986. ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
  2987. return FALSE;
  2988. }
  2989. }
  2990. ast_sockaddr_set_port(&proxy->ip, proxy->port);
  2991. proxy->last_dnsupdate = time(NULL);
  2992. return TRUE;
  2993. }
  2994. /*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is
  2995. * non-NULL, no allocation is performed and dest is used instead.
  2996. * On error NULL is returned. */
  2997. static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
  2998. {
  2999. char *mutable_proxy, *sep, *name;
  3000. int allocated = 0;
  3001. if (!dest) {
  3002. dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
  3003. if (!dest) {
  3004. ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
  3005. return NULL;
  3006. }
  3007. allocated = 1;
  3008. }
  3009. /* Format is: [transport://]name[:port][,force] */
  3010. mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
  3011. sep = strchr(mutable_proxy, ',');
  3012. if (sep) {
  3013. *sep++ = '\0';
  3014. dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
  3015. } else {
  3016. dest->force = FALSE;
  3017. }
  3018. sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
  3019. /* Check that there is a name at all */
  3020. if (ast_strlen_zero(name)) {
  3021. if (allocated) {
  3022. ao2_ref(dest, -1);
  3023. } else {
  3024. dest->name[0] = '\0';
  3025. }
  3026. return NULL;
  3027. }
  3028. ast_copy_string(dest->name, name, sizeof(dest->name));
  3029. /* Resolve host immediately */
  3030. proxy_update(dest);
  3031. return dest;
  3032. }
  3033. /*! \brief converts ascii port to int representation. If no
  3034. * pt buffer is provided or the pt has errors when being converted
  3035. * to an int value, the port provided as the standard is used.
  3036. */
  3037. unsigned int port_str2int(const char *pt, unsigned int standard)
  3038. {
  3039. int port = standard;
  3040. if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
  3041. port = standard;
  3042. }
  3043. return port;
  3044. }
  3045. /*! \brief Get default outbound proxy or global proxy */
  3046. static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
  3047. {
  3048. if (dialog && dialog->options && dialog->options->outboundproxy) {
  3049. if (sipdebug) {
  3050. ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
  3051. }
  3052. append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
  3053. return dialog->options->outboundproxy;
  3054. }
  3055. if (peer && peer->outboundproxy) {
  3056. if (sipdebug) {
  3057. ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
  3058. }
  3059. append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
  3060. return peer->outboundproxy;
  3061. }
  3062. if (sip_cfg.outboundproxy.name[0]) {
  3063. if (sipdebug) {
  3064. ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
  3065. }
  3066. append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
  3067. return &sip_cfg.outboundproxy;
  3068. }
  3069. if (sipdebug) {
  3070. ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
  3071. }
  3072. return NULL;
  3073. }
  3074. /*! \brief returns true if 'name' (with optional trailing whitespace)
  3075. * matches the sip method 'id'.
  3076. * Strictly speaking, SIP methods are case SENSITIVE, but we do
  3077. * a case-insensitive comparison to be more tolerant.
  3078. * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
  3079. */
  3080. static int method_match(enum sipmethod id, const char *name)
  3081. {
  3082. int len = strlen(sip_methods[id].text);
  3083. int l_name = name ? strlen(name) : 0;
  3084. /* true if the string is long enough, and ends with whitespace, and matches */
  3085. return (l_name >= len && name && name[len] < 33 &&
  3086. !strncasecmp(sip_methods[id].text, name, len));
  3087. }
  3088. /*! \brief find_sip_method: Find SIP method from header */
  3089. static int find_sip_method(const char *msg)
  3090. {
  3091. int i, res = 0;
  3092. if (ast_strlen_zero(msg)) {
  3093. return 0;
  3094. }
  3095. for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
  3096. if (method_match(i, msg)) {
  3097. res = sip_methods[i].id;
  3098. }
  3099. }
  3100. return res;
  3101. }
  3102. /*! \brief See if we pass debug IP filter */
  3103. static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
  3104. {
  3105. /* Can't debug if sipdebug is not enabled */
  3106. if (!sipdebug) {
  3107. return 0;
  3108. }
  3109. /* A null debug_addr means we'll debug any address */
  3110. if (ast_sockaddr_isnull(&debugaddr)) {
  3111. return 1;
  3112. }
  3113. /* If no port was specified for a debug address, just compare the
  3114. * addresses, otherwise compare the address and port
  3115. */
  3116. if (ast_sockaddr_port(&debugaddr)) {
  3117. return !ast_sockaddr_cmp(&debugaddr, addr);
  3118. } else {
  3119. return !ast_sockaddr_cmp_addr(&debugaddr, addr);
  3120. }
  3121. }
  3122. /*! \brief The real destination address for a write */
  3123. static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
  3124. {
  3125. if (p->outboundproxy) {
  3126. return &p->outboundproxy->ip;
  3127. }
  3128. return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT) ? &p->recv : &p->sa;
  3129. }
  3130. /*! \brief Display SIP nat mode */
  3131. static const char *sip_nat_mode(const struct sip_pvt *p)
  3132. {
  3133. return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
  3134. }
  3135. /*! \brief Test PVT for debugging output */
  3136. static inline int sip_debug_test_pvt(struct sip_pvt *p)
  3137. {
  3138. if (!sipdebug) {
  3139. return 0;
  3140. }
  3141. return sip_debug_test_addr(sip_real_dst(p));
  3142. }
  3143. /*! \brief Return int representing a bit field of transport types found in const char *transport */
  3144. static int get_transport_str2enum(const char *transport)
  3145. {
  3146. int res = 0;
  3147. if (ast_strlen_zero(transport)) {
  3148. return res;
  3149. }
  3150. if (!strcasecmp(transport, "udp")) {
  3151. res |= AST_TRANSPORT_UDP;
  3152. }
  3153. if (!strcasecmp(transport, "tcp")) {
  3154. res |= AST_TRANSPORT_TCP;
  3155. }
  3156. if (!strcasecmp(transport, "tls")) {
  3157. res |= AST_TRANSPORT_TLS;
  3158. }
  3159. if (!strcasecmp(transport, "ws")) {
  3160. res |= AST_TRANSPORT_WS;
  3161. }
  3162. if (!strcasecmp(transport, "wss")) {
  3163. res |= AST_TRANSPORT_WSS;
  3164. }
  3165. return res;
  3166. }
  3167. /*! \brief Return configuration of transports for a device */
  3168. static inline const char *get_transport_list(unsigned int transports)
  3169. {
  3170. char *buf;
  3171. if (!transports) {
  3172. return "UNKNOWN";
  3173. }
  3174. if (!(buf = ast_threadstorage_get(&sip_transport_str_buf, SIP_TRANSPORT_STR_BUFSIZE))) {
  3175. return "";
  3176. }
  3177. memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
  3178. if (transports & AST_TRANSPORT_UDP) {
  3179. strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
  3180. }
  3181. if (transports & AST_TRANSPORT_TCP) {
  3182. strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
  3183. }
  3184. if (transports & AST_TRANSPORT_TLS) {
  3185. strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
  3186. }
  3187. if (transports & AST_TRANSPORT_WS) {
  3188. strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
  3189. }
  3190. if (transports & AST_TRANSPORT_WSS) {
  3191. strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
  3192. }
  3193. /* Remove the trailing ',' if present */
  3194. if (strlen(buf)) {
  3195. buf[strlen(buf) - 1] = 0;
  3196. }
  3197. return buf;
  3198. }
  3199. /*! \brief Return transport as string */
  3200. const char *sip_get_transport(enum ast_transport t)
  3201. {
  3202. switch (t) {
  3203. case AST_TRANSPORT_UDP:
  3204. return "UDP";
  3205. case AST_TRANSPORT_TCP:
  3206. return "TCP";
  3207. case AST_TRANSPORT_TLS:
  3208. return "TLS";
  3209. case AST_TRANSPORT_WS:
  3210. case AST_TRANSPORT_WSS:
  3211. return "WS";
  3212. }
  3213. return "UNKNOWN";
  3214. }
  3215. /*! \brief Return protocol string for srv dns query */
  3216. static inline const char *get_srv_protocol(enum ast_transport t)
  3217. {
  3218. switch (t) {
  3219. case AST_TRANSPORT_UDP:
  3220. return "udp";
  3221. case AST_TRANSPORT_WS:
  3222. return "ws";
  3223. case AST_TRANSPORT_TLS:
  3224. case AST_TRANSPORT_TCP:
  3225. return "tcp";
  3226. case AST_TRANSPORT_WSS:
  3227. return "wss";
  3228. }
  3229. return "udp";
  3230. }
  3231. /*! \brief Return service string for srv dns query */
  3232. static inline const char *get_srv_service(enum ast_transport t)
  3233. {
  3234. switch (t) {
  3235. case AST_TRANSPORT_TCP:
  3236. case AST_TRANSPORT_UDP:
  3237. case AST_TRANSPORT_WS:
  3238. return "sip";
  3239. case AST_TRANSPORT_TLS:
  3240. case AST_TRANSPORT_WSS:
  3241. return "sips";
  3242. }
  3243. return "sip";
  3244. }
  3245. /*! \brief Return transport of dialog.
  3246. \note this is based on a false assumption. We don't always use the
  3247. outbound proxy for all requests in a dialog. It depends on the
  3248. "force" parameter. The FIRST request is always sent to the ob proxy.
  3249. \todo Fix this function to work correctly
  3250. */
  3251. static inline const char *get_transport_pvt(struct sip_pvt *p)
  3252. {
  3253. if (p->outboundproxy && p->outboundproxy->transport) {
  3254. set_socket_transport(&p->socket, p->outboundproxy->transport);
  3255. }
  3256. return sip_get_transport(p->socket.type);
  3257. }
  3258. /*!
  3259. * \internal
  3260. * \brief Transmit SIP message
  3261. *
  3262. * \details
  3263. * Sends a SIP request or response on a given socket (in the pvt)
  3264. * \note
  3265. * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
  3266. *
  3267. * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
  3268. */
  3269. static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
  3270. {
  3271. int res = 0;
  3272. const struct ast_sockaddr *dst = sip_real_dst(p);
  3273. ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", ast_str_buffer(data), get_transport_pvt(p), ast_sockaddr_stringify(dst));
  3274. if (sip_prepare_socket(p) < 0) {
  3275. return XMIT_ERROR;
  3276. }
  3277. if (p->socket.type == AST_TRANSPORT_UDP) {
  3278. res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
  3279. } else if (p->socket.tcptls_session) {
  3280. res = sip_tcptls_write(p->socket.tcptls_session, ast_str_buffer(data), ast_str_strlen(data));
  3281. } else if (p->socket.ws_session) {
  3282. if (!(res = ast_websocket_write(p->socket.ws_session, AST_WEBSOCKET_OPCODE_TEXT, ast_str_buffer(data), ast_str_strlen(data)))) {
  3283. /* The WebSocket API just returns 0 on success and -1 on failure, while this code expects the payload length to be returned */
  3284. res = ast_str_strlen(data);
  3285. }
  3286. } else {
  3287. ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
  3288. return XMIT_ERROR;
  3289. }
  3290. if (res == -1) {
  3291. switch (errno) {
  3292. case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
  3293. case EHOSTUNREACH: /* Host can't be reached */
  3294. case ENETDOWN: /* Interface down */
  3295. case ENETUNREACH: /* Network failure */
  3296. case ECONNREFUSED: /* ICMP port unreachable */
  3297. res = XMIT_ERROR; /* Don't bother with trying to transmit again */
  3298. }
  3299. }
  3300. if (res != ast_str_strlen(data)) {
  3301. ast_log(LOG_WARNING, "sip_xmit of %p (len %zu) to %s returned %d: %s\n", data, ast_str_strlen(data), ast_sockaddr_stringify(dst), res, strerror(errno));
  3302. }
  3303. return res;
  3304. }
  3305. /*! \brief Build a Via header for a request */
  3306. static void build_via(struct sip_pvt *p)
  3307. {
  3308. /* Work around buggy UNIDEN UIP200 firmware */
  3309. const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
  3310. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  3311. snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
  3312. get_transport_pvt(p),
  3313. ast_sockaddr_stringify_remote(&p->ourip),
  3314. (unsigned)p->branch, rport);
  3315. }
  3316. /*! \brief NAT fix - decide which IP address to use for Asterisk server?
  3317. *
  3318. * Using the localaddr structure built up with localnet statements in sip.conf
  3319. * apply it to their address to see if we need to substitute our
  3320. * externaddr or can get away with our internal bindaddr
  3321. * 'us' is always overwritten.
  3322. */
  3323. static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
  3324. {
  3325. struct ast_sockaddr theirs;
  3326. /* Set want_remap to non-zero if we want to remap 'us' to an externally
  3327. * reachable IP address and port. This is done if:
  3328. * 1. we have a localaddr list (containing 'internal' addresses marked
  3329. * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
  3330. * and AST_SENSE_ALLOW on 'external' ones);
  3331. * 2. externaddr is set, so we know what to use as the
  3332. * externally visible address;
  3333. * 3. the remote address, 'them', is external;
  3334. * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
  3335. * when passed to ast_apply_ha() so it does need to be remapped.
  3336. * This fourth condition is checked later.
  3337. */
  3338. int want_remap = 0;
  3339. ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
  3340. /* now ask the system what would it use to talk to 'them' */
  3341. ast_ouraddrfor(them, us);
  3342. ast_sockaddr_copy(&theirs, them);
  3343. if (ast_sockaddr_is_ipv6(&theirs) && !ast_sockaddr_is_ipv4_mapped(&theirs)) {
  3344. if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
  3345. ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
  3346. "but we're using IPv6, which doesn't need it. Please "
  3347. "remove \"localnet\" and/or \"externaddr\" settings.\n");
  3348. }
  3349. } else {
  3350. want_remap = localaddr &&
  3351. !ast_sockaddr_isnull(&externaddr) &&
  3352. ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
  3353. }
  3354. if (want_remap &&
  3355. (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
  3356. /* if we used externhost, see if it is time to refresh the info */
  3357. if (externexpire && time(NULL) >= externexpire) {
  3358. if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
  3359. ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
  3360. }
  3361. externexpire = time(NULL) + externrefresh;
  3362. }
  3363. if (!ast_sockaddr_isnull(&externaddr)) {
  3364. ast_sockaddr_copy(us, &externaddr);
  3365. switch (p->socket.type) {
  3366. case AST_TRANSPORT_TCP:
  3367. if (!externtcpport && ast_sockaddr_port(&externaddr)) {
  3368. /* for consistency, default to the externaddr port */
  3369. externtcpport = ast_sockaddr_port(&externaddr);
  3370. }
  3371. ast_sockaddr_set_port(us, externtcpport);
  3372. break;
  3373. case AST_TRANSPORT_TLS:
  3374. ast_sockaddr_set_port(us, externtlsport);
  3375. break;
  3376. case AST_TRANSPORT_UDP:
  3377. if (!ast_sockaddr_port(&externaddr)) {
  3378. ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
  3379. }
  3380. break;
  3381. default:
  3382. break;
  3383. }
  3384. }
  3385. ast_debug(1, "Target address %s is not local, substituting externaddr\n",
  3386. ast_sockaddr_stringify(them));
  3387. } else {
  3388. /* no remapping, but we bind to a specific address, so use it. */
  3389. switch (p->socket.type) {
  3390. case AST_TRANSPORT_TCP:
  3391. if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
  3392. ast_sockaddr_copy(us,
  3393. &sip_tcp_desc.local_address);
  3394. } else {
  3395. ast_sockaddr_set_port(us,
  3396. ast_sockaddr_port(&sip_tcp_desc.local_address));
  3397. }
  3398. break;
  3399. case AST_TRANSPORT_TLS:
  3400. if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
  3401. ast_sockaddr_copy(us,
  3402. &sip_tls_desc.local_address);
  3403. } else {
  3404. ast_sockaddr_set_port(us,
  3405. ast_sockaddr_port(&sip_tls_desc.local_address));
  3406. }
  3407. break;
  3408. case AST_TRANSPORT_UDP:
  3409. /* fall through on purpose */
  3410. default:
  3411. if (!ast_sockaddr_is_any(&bindaddr)) {
  3412. ast_sockaddr_copy(us, &bindaddr);
  3413. }
  3414. if (!ast_sockaddr_port(us)) {
  3415. ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
  3416. }
  3417. }
  3418. }
  3419. ast_debug(3, "Setting AST_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
  3420. }
  3421. /*! \brief Append to SIP dialog history with arg list */
  3422. static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
  3423. {
  3424. char buf[80], *c = buf; /* max history length */
  3425. struct sip_history *hist;
  3426. int l;
  3427. vsnprintf(buf, sizeof(buf), fmt, ap);
  3428. strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
  3429. l = strlen(buf) + 1;
  3430. if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
  3431. return;
  3432. }
  3433. if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
  3434. ast_free(hist);
  3435. return;
  3436. }
  3437. memcpy(hist->event, buf, l);
  3438. if (p->history_entries == MAX_HISTORY_ENTRIES) {
  3439. struct sip_history *oldest;
  3440. oldest = AST_LIST_REMOVE_HEAD(p->history, list);
  3441. p->history_entries--;
  3442. ast_free(oldest);
  3443. }
  3444. AST_LIST_INSERT_TAIL(p->history, hist, list);
  3445. p->history_entries++;
  3446. }
  3447. /*! \brief Append to SIP dialog history with arg list */
  3448. static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
  3449. {
  3450. va_list ap;
  3451. if (!p) {
  3452. return;
  3453. }
  3454. if (!p->do_history && !recordhistory && !dumphistory) {
  3455. return;
  3456. }
  3457. va_start(ap, fmt);
  3458. append_history_va(p, fmt, ap);
  3459. va_end(ap);
  3460. return;
  3461. }
  3462. /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
  3463. static int retrans_pkt(const void *data)
  3464. {
  3465. struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
  3466. int reschedule = DEFAULT_RETRANS;
  3467. int xmitres = 0;
  3468. /* how many ms until retrans timeout is reached */
  3469. int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
  3470. /* Do not retransmit if time out is reached. This will be negative if the time between
  3471. * the first transmission and now is larger than our timeout period. This is a fail safe
  3472. * check in case the scheduler gets behind or the clock is changed. */
  3473. if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
  3474. pkt->retrans_stop = 1;
  3475. }
  3476. /* Lock channel PVT */
  3477. sip_pvt_lock(pkt->owner);
  3478. if (!pkt->retrans_stop) {
  3479. pkt->retrans++;
  3480. if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
  3481. if (sipdebug) {
  3482. ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
  3483. pkt->retransid,
  3484. sip_methods[pkt->method].text,
  3485. pkt->method);
  3486. }
  3487. } else {
  3488. int siptimer_a;
  3489. if (sipdebug) {
  3490. ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
  3491. pkt->retransid,
  3492. pkt->retrans,
  3493. sip_methods[pkt->method].text,
  3494. pkt->method);
  3495. }
  3496. if (!pkt->timer_a) {
  3497. pkt->timer_a = 2 ;
  3498. } else {
  3499. pkt->timer_a = 2 * pkt->timer_a;
  3500. }
  3501. /* For non-invites, a maximum of 4 secs */
  3502. siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
  3503. if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
  3504. siptimer_a = 4000;
  3505. }
  3506. /* Reschedule re-transmit */
  3507. reschedule = siptimer_a;
  3508. ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
  3509. pkt->retrans + 1,
  3510. siptimer_a,
  3511. pkt->timer_t1,
  3512. pkt->retransid);
  3513. }
  3514. if (sip_debug_test_pvt(pkt->owner)) {
  3515. const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
  3516. ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
  3517. pkt->retrans, sip_nat_mode(pkt->owner),
  3518. ast_sockaddr_stringify(dst),
  3519. ast_str_buffer(pkt->data));
  3520. }
  3521. append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
  3522. xmitres = __sip_xmit(pkt->owner, pkt->data);
  3523. /* If there was no error during the network transmission, schedule the next retransmission,
  3524. * but if the next retransmission is going to be beyond our timeout period, mark the packet's
  3525. * stop_retrans value and set the next retransmit to be the exact time of timeout. This will
  3526. * allow any responses to the packet to be processed before the packet is destroyed on the next
  3527. * call to this function by the scheduler. */
  3528. if (xmitres != XMIT_ERROR) {
  3529. if (reschedule >= diff) {
  3530. pkt->retrans_stop = 1;
  3531. reschedule = diff;
  3532. }
  3533. sip_pvt_unlock(pkt->owner);
  3534. return reschedule;
  3535. }
  3536. }
  3537. /* At this point, either the packet's retransmission timed out, or there was a
  3538. * transmission error, either way destroy the scheduler item and this packet. */
  3539. pkt->retransid = -1; /* Kill this scheduler item */
  3540. if (pkt->method != SIP_OPTIONS && xmitres == 0) {
  3541. if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
  3542. ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %u (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
  3543. "Packet timed out after %dms with no response\n",
  3544. pkt->owner->callid,
  3545. pkt->seqno,
  3546. pkt->is_fatal ? "Critical" : "Non-critical",
  3547. pkt->is_resp ? "Response" : "Request",
  3548. (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
  3549. }
  3550. } else if (pkt->method == SIP_OPTIONS && sipdebug) {
  3551. ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n", pkt->owner->callid);
  3552. }
  3553. if (xmitres == XMIT_ERROR) {
  3554. ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
  3555. append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
  3556. } else {
  3557. append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
  3558. }
  3559. if (pkt->is_fatal) {
  3560. while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
  3561. sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
  3562. usleep(1);
  3563. sip_pvt_lock(pkt->owner);
  3564. }
  3565. if (pkt->owner->owner && !ast_channel_hangupcause(pkt->owner->owner)) {
  3566. ast_channel_hangupcause_set(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
  3567. }
  3568. if (pkt->owner->owner) {
  3569. ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions).\n", pkt->owner->callid);
  3570. if (pkt->is_resp &&
  3571. (pkt->response_code >= 200) &&
  3572. (pkt->response_code < 300) &&
  3573. pkt->owner->pendinginvite &&
  3574. ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  3575. /* This is a timeout of the 2XX response to a pending INVITE. In this case terminate the INVITE
  3576. * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
  3577. * will send the BYE as long as the dialog is not set as "alreadygone")
  3578. * RFC 3261 section 13.3.1.4.
  3579. * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
  3580. * an ACK, the dialog is confirmed, but the session SHOULD be terminated. This is
  3581. * accomplished with a BYE, as described in Section 15." */
  3582. pkt->owner->invitestate = INV_TERMINATED;
  3583. pkt->owner->pendinginvite = 0;
  3584. } else {
  3585. /* there is nothing left to do, mark the dialog as gone */
  3586. sip_alreadygone(pkt->owner);
  3587. }
  3588. ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
  3589. ast_channel_unlock(pkt->owner->owner);
  3590. } else {
  3591. /* If no channel owner, destroy now */
  3592. /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
  3593. if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
  3594. pvt_set_needdestroy(pkt->owner, "no response to critical packet");
  3595. sip_alreadygone(pkt->owner);
  3596. append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
  3597. }
  3598. }
  3599. } else if (pkt->owner->pendinginvite == pkt->seqno) {
  3600. ast_log(LOG_WARNING, "Timeout on %s on non-critical invite transaction.\n", pkt->owner->callid);
  3601. pkt->owner->invitestate = INV_TERMINATED;
  3602. pkt->owner->pendinginvite = 0;
  3603. check_pendings(pkt->owner);
  3604. }
  3605. if (pkt->method == SIP_BYE) {
  3606. /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
  3607. sip_alreadygone(pkt->owner);
  3608. if (pkt->owner->owner) {
  3609. ast_channel_unlock(pkt->owner->owner);
  3610. }
  3611. append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
  3612. pvt_set_needdestroy(pkt->owner, "no response to BYE");
  3613. }
  3614. /* Remove the packet */
  3615. for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
  3616. if (cur == pkt) {
  3617. UNLINK(cur, pkt->owner->packets, prev);
  3618. sip_pvt_unlock(pkt->owner);
  3619. if (pkt->owner) {
  3620. pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
  3621. }
  3622. if (pkt->data) {
  3623. ast_free(pkt->data);
  3624. }
  3625. pkt->data = NULL;
  3626. ast_free(pkt);
  3627. return 0;
  3628. }
  3629. }
  3630. /* error case */
  3631. ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
  3632. sip_pvt_unlock(pkt->owner);
  3633. return 0;
  3634. }
  3635. /*!
  3636. * \internal
  3637. * \brief Transmit packet with retransmits
  3638. * \return 0 on success, -1 on failure to allocate packet
  3639. */
  3640. static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
  3641. {
  3642. struct sip_pkt *pkt = NULL;
  3643. int siptimer_a = DEFAULT_RETRANS;
  3644. int xmitres = 0;
  3645. unsigned respid;
  3646. if (sipmethod == SIP_INVITE) {
  3647. /* Note this is a pending invite */
  3648. p->pendinginvite = seqno;
  3649. }
  3650. /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
  3651. /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
  3652. /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
  3653. if (!(p->socket.type & AST_TRANSPORT_UDP)) {
  3654. xmitres = __sip_xmit(p, data); /* Send packet */
  3655. if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
  3656. append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
  3657. return AST_FAILURE;
  3658. } else {
  3659. return AST_SUCCESS;
  3660. }
  3661. }
  3662. if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
  3663. return AST_FAILURE;
  3664. }
  3665. /* copy data, add a terminator and save length */
  3666. if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
  3667. ast_free(pkt);
  3668. return AST_FAILURE;
  3669. }
  3670. ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
  3671. /* copy other parameters from the caller */
  3672. pkt->method = sipmethod;
  3673. pkt->seqno = seqno;
  3674. pkt->is_resp = resp;
  3675. pkt->is_fatal = fatal;
  3676. pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
  3677. pkt->next = p->packets;
  3678. p->packets = pkt; /* Add it to the queue */
  3679. if (resp) {
  3680. /* Parse out the response code */
  3681. if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
  3682. pkt->response_code = respid;
  3683. }
  3684. }
  3685. pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
  3686. pkt->retransid = -1;
  3687. if (pkt->timer_t1) {
  3688. siptimer_a = pkt->timer_t1;
  3689. }
  3690. pkt->time_sent = ast_tvnow(); /* time packet was sent */
  3691. pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
  3692. /* Schedule retransmission */
  3693. AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
  3694. if (sipdebug) {
  3695. ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
  3696. }
  3697. xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
  3698. if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
  3699. append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
  3700. ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
  3701. AST_SCHED_DEL(sched, pkt->retransid);
  3702. p->packets = pkt->next;
  3703. pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
  3704. ast_free(pkt->data);
  3705. ast_free(pkt);
  3706. return AST_FAILURE;
  3707. } else {
  3708. /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
  3709. * only wakes up every 1000ms by default, we have to poke the thread here to make
  3710. * sure it successfully detects this must be retransmitted in less time than
  3711. * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
  3712. if (monitor_thread != AST_PTHREADT_NULL) {
  3713. pthread_kill(monitor_thread, SIGURG);
  3714. }
  3715. return AST_SUCCESS;
  3716. }
  3717. }
  3718. /*! \brief Kill a SIP dialog (called only by the scheduler)
  3719. * The scheduler has a reference to this dialog when p->autokillid != -1,
  3720. * and we are called using that reference. So if the event is not
  3721. * rescheduled, we need to call dialog_unref().
  3722. */
  3723. static int __sip_autodestruct(const void *data)
  3724. {
  3725. struct sip_pvt *p = (struct sip_pvt *)data;
  3726. struct ast_channel *owner;
  3727. /* If this is a subscription, tell the phone that we got a timeout */
  3728. if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
  3729. struct state_notify_data data = { 0, };
  3730. data.state = AST_EXTENSION_DEACTIVATED;
  3731. transmit_state_notify(p, &data, 1, TRUE); /* Send last notification */
  3732. p->subscribed = NONE;
  3733. append_history(p, "Subscribestatus", "timeout");
  3734. ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
  3735. return 10000; /* Reschedule this destruction so that we know that it's gone */
  3736. }
  3737. /* If there are packets still waiting for delivery, delay the destruction */
  3738. if (p->packets) {
  3739. if (!p->needdestroy) {
  3740. char method_str[31];
  3741. ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
  3742. append_history(p, "ReliableXmit", "timeout");
  3743. if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
  3744. if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
  3745. pvt_set_needdestroy(p, "autodestruct");
  3746. }
  3747. }
  3748. return 10000;
  3749. } else {
  3750. /* They've had their chance to respond. Time to bail */
  3751. __sip_pretend_ack(p);
  3752. }
  3753. }
  3754. /* Reset schedule ID */
  3755. p->autokillid = -1;
  3756. /*
  3757. * Lock both the pvt and the channel safely so that we can queue up a frame.
  3758. */
  3759. owner = sip_pvt_lock_full(p);
  3760. if (owner) {
  3761. ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner %s in place (Method: %s). Rescheduling destruction for 10000 ms\n", p->callid, ast_channel_name(owner), sip_methods[p->method].text);
  3762. ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
  3763. ast_channel_unlock(owner);
  3764. ast_channel_unref(owner);
  3765. sip_pvt_unlock(p);
  3766. return 10000;
  3767. } else if (p->refer && !p->alreadygone) {
  3768. ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
  3769. stop_media_flows(p);
  3770. transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
  3771. append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
  3772. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  3773. } else {
  3774. append_history(p, "AutoDestroy", "%s", p->callid);
  3775. ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
  3776. sip_pvt_unlock(p);
  3777. dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
  3778. sip_pvt_lock(p);
  3779. /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
  3780. /* sip_destroy(p); */ /* Go ahead and destroy dialog. All attempts to recover is done */
  3781. /* sip_destroy also absorbs the reference */
  3782. }
  3783. sip_pvt_unlock(p);
  3784. dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
  3785. return 0;
  3786. }
  3787. /*! \brief Schedule final destruction of SIP dialog. This can not be canceled.
  3788. * This function is used to keep a dialog around for a period of time in order
  3789. * to properly respond to any retransmits. */
  3790. void sip_scheddestroy_final(struct sip_pvt *p, int ms)
  3791. {
  3792. if (p->final_destruction_scheduled) {
  3793. return; /* already set final destruction */
  3794. }
  3795. sip_scheddestroy(p, ms);
  3796. if (p->autokillid != -1) {
  3797. p->final_destruction_scheduled = 1;
  3798. }
  3799. }
  3800. /*! \brief Schedule destruction of SIP dialog */
  3801. void sip_scheddestroy(struct sip_pvt *p, int ms)
  3802. {
  3803. if (p->final_destruction_scheduled) {
  3804. return; /* already set final destruction */
  3805. }
  3806. if (ms < 0) {
  3807. if (p->timer_t1 == 0) {
  3808. p->timer_t1 = global_t1; /* Set timer T1 if not set (RFC 3261) */
  3809. }
  3810. if (p->timer_b == 0) {
  3811. p->timer_b = global_timer_b; /* Set timer B if not set (RFC 3261) */
  3812. }
  3813. ms = p->timer_t1 * 64;
  3814. }
  3815. if (sip_debug_test_pvt(p)) {
  3816. ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
  3817. }
  3818. if (sip_cancel_destroy(p)) {
  3819. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  3820. }
  3821. if (p->do_history) {
  3822. append_history(p, "SchedDestroy", "%d ms", ms);
  3823. }
  3824. p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
  3825. if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
  3826. stop_session_timer(p);
  3827. }
  3828. }
  3829. /*! \brief Cancel destruction of SIP dialog.
  3830. * Be careful as this also absorbs the reference - if you call it
  3831. * from within the scheduler, this might be the last reference.
  3832. */
  3833. int sip_cancel_destroy(struct sip_pvt *p)
  3834. {
  3835. if (p->final_destruction_scheduled) {
  3836. return 0;
  3837. }
  3838. if (p->autokillid > -1) {
  3839. append_history(p, "CancelDestroy", "");
  3840. AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
  3841. }
  3842. return 0;
  3843. }
  3844. /*! \brief Acknowledges receipt of a packet and stops retransmission
  3845. * called with p locked*/
  3846. int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
  3847. {
  3848. struct sip_pkt *cur, *prev = NULL;
  3849. const char *msg = "Not Found"; /* used only for debugging */
  3850. int res = FALSE;
  3851. /* If we have an outbound proxy for this dialog, then delete it now since
  3852. the rest of the requests in this dialog needs to follow the routing.
  3853. If obforcing is set, we will keep the outbound proxy during the whole
  3854. dialog, regardless of what the SIP rfc says
  3855. */
  3856. if (p->outboundproxy && !p->outboundproxy->force) {
  3857. ref_proxy(p, NULL);
  3858. }
  3859. for (cur = p->packets; cur; prev = cur, cur = cur->next) {
  3860. if (cur->seqno != seqno || cur->is_resp != resp) {
  3861. continue;
  3862. }
  3863. if (cur->is_resp || cur->method == sipmethod) {
  3864. res = TRUE;
  3865. msg = "Found";
  3866. if (!resp && (seqno == p->pendinginvite)) {
  3867. ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
  3868. p->pendinginvite = 0;
  3869. }
  3870. if (cur->retransid > -1) {
  3871. if (sipdebug)
  3872. ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
  3873. }
  3874. /* This odd section is designed to thwart a
  3875. * race condition in the packet scheduler. There are
  3876. * two conditions under which deleting the packet from the
  3877. * scheduler can fail.
  3878. *
  3879. * 1. The packet has been removed from the scheduler because retransmission
  3880. * is being attempted. The problem is that if the packet is currently attempting
  3881. * retransmission and we are at this point in the code, then that MUST mean
  3882. * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
  3883. * lock temporarily to allow retransmission.
  3884. *
  3885. * 2. The packet has reached its maximum number of retransmissions and has
  3886. * been permanently removed from the packet scheduler. If this is the case, then
  3887. * the packet's retransid will be set to -1. The atomicity of the setting and checking
  3888. * of the retransid to -1 is ensured since in both cases p's lock is held.
  3889. */
  3890. while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
  3891. sip_pvt_unlock(p);
  3892. usleep(1);
  3893. sip_pvt_lock(p);
  3894. }
  3895. UNLINK(cur, p->packets, prev);
  3896. dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
  3897. if (cur->data) {
  3898. ast_free(cur->data);
  3899. }
  3900. ast_free(cur);
  3901. break;
  3902. }
  3903. }
  3904. ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
  3905. p->callid, resp ? "Response" : "Request", seqno, msg);
  3906. return res;
  3907. }
  3908. /*! \brief Pretend to ack all packets
  3909. * called with p locked */
  3910. void __sip_pretend_ack(struct sip_pvt *p)
  3911. {
  3912. struct sip_pkt *cur = NULL;
  3913. while (p->packets) {
  3914. int method;
  3915. if (cur == p->packets) {
  3916. ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
  3917. return;
  3918. }
  3919. cur = p->packets;
  3920. method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
  3921. __sip_ack(p, cur->seqno, cur->is_resp, method);
  3922. }
  3923. }
  3924. /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
  3925. int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
  3926. {
  3927. struct sip_pkt *cur;
  3928. int res = FALSE;
  3929. for (cur = p->packets; cur; cur = cur->next) {
  3930. if (cur->seqno == seqno && cur->is_resp == resp &&
  3931. (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
  3932. /* this is our baby */
  3933. if (cur->retransid > -1) {
  3934. if (sipdebug)
  3935. ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
  3936. }
  3937. AST_SCHED_DEL(sched, cur->retransid);
  3938. res = TRUE;
  3939. break;
  3940. }
  3941. }
  3942. ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %u: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
  3943. return res;
  3944. }
  3945. /*! \brief Copy SIP request, parse it */
  3946. static void parse_copy(struct sip_request *dst, const struct sip_request *src)
  3947. {
  3948. copy_request(dst, src);
  3949. parse_request(dst);
  3950. }
  3951. /*! \brief add a blank line if no body */
  3952. static void add_blank(struct sip_request *req)
  3953. {
  3954. if (!req->lines) {
  3955. /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
  3956. ast_str_append(&req->data, 0, "\r\n");
  3957. }
  3958. }
  3959. static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
  3960. {
  3961. const char *msg = NULL;
  3962. struct ast_channel *chan;
  3963. int res = 0;
  3964. int old_sched_id = pvt->provisional_keepalive_sched_id;
  3965. chan = sip_pvt_lock_full(pvt);
  3966. /* Check that nothing has changed while we were waiting for the lock */
  3967. if (old_sched_id != pvt->provisional_keepalive_sched_id) {
  3968. /* Keepalive has been cancelled or rescheduled, clean up and leave */
  3969. if (chan) {
  3970. ast_channel_unlock(chan);
  3971. chan = ast_channel_unref(chan);
  3972. }
  3973. sip_pvt_unlock(pvt);
  3974. dialog_unref(pvt, "dialog ref for provisional keepalive");
  3975. return 0;
  3976. }
  3977. if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
  3978. msg = "183 Session Progress";
  3979. }
  3980. if (pvt->invitestate < INV_COMPLETED) {
  3981. if (with_sdp) {
  3982. transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
  3983. } else {
  3984. transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
  3985. }
  3986. res = PROVIS_KEEPALIVE_TIMEOUT;
  3987. }
  3988. if (chan) {
  3989. ast_channel_unlock(chan);
  3990. chan = ast_channel_unref(chan);
  3991. }
  3992. if (!res) {
  3993. pvt->provisional_keepalive_sched_id = -1;
  3994. }
  3995. sip_pvt_unlock(pvt);
  3996. if (!res) {
  3997. dialog_unref(pvt, "dialog ref for provisional keepalive");
  3998. }
  3999. return res;
  4000. }
  4001. static int send_provisional_keepalive(const void *data)
  4002. {
  4003. struct sip_pvt *pvt = (struct sip_pvt *) data;
  4004. return send_provisional_keepalive_full(pvt, 0);
  4005. }
  4006. static int send_provisional_keepalive_with_sdp(const void *data)
  4007. {
  4008. struct sip_pvt *pvt = (void *) data;
  4009. return send_provisional_keepalive_full(pvt, 1);
  4010. }
  4011. static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
  4012. {
  4013. AST_SCHED_DEL_UNREF(sched, pvt->provisional_keepalive_sched_id, dialog_unref(pvt, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
  4014. pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
  4015. with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
  4016. }
  4017. static void add_required_respheader(struct sip_request *req)
  4018. {
  4019. struct ast_str *str;
  4020. int i;
  4021. if (!req->reqsipoptions) {
  4022. return;
  4023. }
  4024. str = ast_str_create(32);
  4025. for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
  4026. if (!(req->reqsipoptions & sip_options[i].id)) {
  4027. continue;
  4028. }
  4029. if (ast_str_strlen(str) > 0) {
  4030. ast_str_append(&str, 0, ", ");
  4031. }
  4032. ast_str_append(&str, 0, "%s", sip_options[i].text);
  4033. }
  4034. if (ast_str_strlen(str) > 0) {
  4035. add_header(req, "Require", ast_str_buffer(str));
  4036. }
  4037. ast_free(str);
  4038. }
  4039. /*! \brief Transmit response on SIP request*/
  4040. static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
  4041. {
  4042. int res;
  4043. finalize_content(req);
  4044. add_blank(req);
  4045. if (sip_debug_test_pvt(p)) {
  4046. const struct ast_sockaddr *dst = sip_real_dst(p);
  4047. ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
  4048. reliable ? "Reliably " : "", sip_nat_mode(p),
  4049. ast_sockaddr_stringify(dst),
  4050. ast_str_buffer(req->data));
  4051. }
  4052. if (p->do_history) {
  4053. struct sip_request tmp = { .rlpart1 = 0, };
  4054. parse_copy(&tmp, req);
  4055. append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"),
  4056. (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlpart2) : sip_methods[tmp.method].text);
  4057. deinit_req(&tmp);
  4058. }
  4059. /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
  4060. if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
  4061. AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
  4062. }
  4063. res = (reliable) ?
  4064. __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
  4065. __sip_xmit(p, req->data);
  4066. deinit_req(req);
  4067. if (res > 0) {
  4068. return 0;
  4069. }
  4070. return res;
  4071. }
  4072. /*!
  4073. * \internal
  4074. * \brief Send SIP Request to the other part of the dialogue
  4075. * \return see \ref __sip_xmit
  4076. */
  4077. static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
  4078. {
  4079. int res;
  4080. /* If we have an outbound proxy, reset peer address
  4081. Only do this once.
  4082. */
  4083. if (p->outboundproxy) {
  4084. p->sa = p->outboundproxy->ip;
  4085. }
  4086. finalize_content(req);
  4087. add_blank(req);
  4088. if (sip_debug_test_pvt(p)) {
  4089. if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
  4090. ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
  4091. } else {
  4092. ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
  4093. }
  4094. }
  4095. if (p->do_history) {
  4096. struct sip_request tmp = { .rlpart1 = 0, };
  4097. parse_copy(&tmp, req);
  4098. append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
  4099. deinit_req(&tmp);
  4100. }
  4101. res = (reliable) ?
  4102. __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
  4103. __sip_xmit(p, req->data);
  4104. deinit_req(req);
  4105. return res;
  4106. }
  4107. static void enable_dsp_detect(struct sip_pvt *p)
  4108. {
  4109. int features = 0;
  4110. if (p->dsp) {
  4111. return;
  4112. }
  4113. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  4114. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  4115. if (p->rtp) {
  4116. ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
  4117. }
  4118. features |= DSP_FEATURE_DIGIT_DETECT;
  4119. }
  4120. if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
  4121. features |= DSP_FEATURE_FAX_DETECT;
  4122. }
  4123. if (!features) {
  4124. return;
  4125. }
  4126. if (!(p->dsp = ast_dsp_new())) {
  4127. return;
  4128. }
  4129. ast_dsp_set_features(p->dsp, features);
  4130. if (global_relaxdtmf) {
  4131. ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
  4132. }
  4133. }
  4134. static void disable_dsp_detect(struct sip_pvt *p)
  4135. {
  4136. if (p->dsp) {
  4137. ast_dsp_free(p->dsp);
  4138. p->dsp = NULL;
  4139. }
  4140. }
  4141. /*! \brief Set an option on a SIP dialog */
  4142. static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
  4143. {
  4144. int res = -1;
  4145. struct sip_pvt *p = ast_channel_tech_pvt(chan);
  4146. if (!p) {
  4147. ast_log(LOG_ERROR, "Attempt to Ref a null pointer. sip private structure is gone!\n");
  4148. return -1;
  4149. }
  4150. sip_pvt_lock(p);
  4151. switch (option) {
  4152. case AST_OPTION_FORMAT_READ:
  4153. if (p->rtp) {
  4154. res = ast_rtp_instance_set_read_format(p->rtp, *(struct ast_format **) data);
  4155. }
  4156. break;
  4157. case AST_OPTION_FORMAT_WRITE:
  4158. if (p->rtp) {
  4159. res = ast_rtp_instance_set_write_format(p->rtp, *(struct ast_format **) data);
  4160. }
  4161. break;
  4162. case AST_OPTION_DIGIT_DETECT:
  4163. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  4164. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  4165. char *cp = (char *) data;
  4166. ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", ast_channel_name(chan));
  4167. if (*cp) {
  4168. enable_dsp_detect(p);
  4169. } else {
  4170. disable_dsp_detect(p);
  4171. }
  4172. res = 0;
  4173. }
  4174. break;
  4175. case AST_OPTION_SECURE_SIGNALING:
  4176. p->req_secure_signaling = *(unsigned int *) data;
  4177. res = 0;
  4178. break;
  4179. case AST_OPTION_SECURE_MEDIA:
  4180. ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
  4181. res = 0;
  4182. break;
  4183. default:
  4184. break;
  4185. }
  4186. sip_pvt_unlock(p);
  4187. return res;
  4188. }
  4189. /*! \brief Query an option on a SIP dialog */
  4190. static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
  4191. {
  4192. int res = -1;
  4193. enum ast_t38_state state = T38_STATE_UNAVAILABLE;
  4194. struct sip_pvt *p = (struct sip_pvt *) ast_channel_tech_pvt(chan);
  4195. char *cp;
  4196. sip_pvt_lock(p);
  4197. switch (option) {
  4198. case AST_OPTION_T38_STATE:
  4199. /* Make sure we got an ast_t38_state enum passed in */
  4200. if (*datalen != sizeof(enum ast_t38_state)) {
  4201. ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
  4202. break;
  4203. }
  4204. /* Now if T38 support is enabled we need to look and see what the current state is to get what we want to report back */
  4205. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
  4206. switch (p->t38.state) {
  4207. case T38_LOCAL_REINVITE:
  4208. case T38_PEER_REINVITE:
  4209. state = T38_STATE_NEGOTIATING;
  4210. break;
  4211. case T38_ENABLED:
  4212. state = T38_STATE_NEGOTIATED;
  4213. break;
  4214. case T38_REJECTED:
  4215. state = T38_STATE_REJECTED;
  4216. break;
  4217. default:
  4218. state = T38_STATE_UNKNOWN;
  4219. }
  4220. }
  4221. *((enum ast_t38_state *) data) = state;
  4222. res = 0;
  4223. break;
  4224. case AST_OPTION_DIGIT_DETECT:
  4225. cp = (char *) data;
  4226. *cp = p->dsp ? 1 : 0;
  4227. ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", ast_channel_name(chan));
  4228. break;
  4229. case AST_OPTION_SECURE_SIGNALING:
  4230. *((unsigned int *) data) = p->req_secure_signaling;
  4231. res = 0;
  4232. break;
  4233. case AST_OPTION_SECURE_MEDIA:
  4234. *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
  4235. res = 0;
  4236. break;
  4237. case AST_OPTION_DEVICE_NAME:
  4238. if (p && p->outgoing_call) {
  4239. cp = (char *) data;
  4240. ast_copy_string(cp, p->dialstring, *datalen);
  4241. res = 0;
  4242. }
  4243. /* We purposely break with a return of -1 in the
  4244. * implied else case here
  4245. */
  4246. break;
  4247. default:
  4248. break;
  4249. }
  4250. sip_pvt_unlock(p);
  4251. return res;
  4252. }
  4253. /*! \brief Locate closing quote in a string, skipping escaped quotes.
  4254. * optionally with a limit on the search.
  4255. * start must be past the first quote.
  4256. */
  4257. const char *find_closing_quote(const char *start, const char *lim)
  4258. {
  4259. char last_char = '\0';
  4260. const char *s;
  4261. for (s = start; *s && s != lim; last_char = *s++) {
  4262. if (*s == '"' && last_char != '\\')
  4263. break;
  4264. }
  4265. return s;
  4266. }
  4267. /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
  4268. static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
  4269. {
  4270. struct sip_pvt *p = ast_channel_tech_pvt(chan);
  4271. if (subclass != AST_HTML_URL)
  4272. return -1;
  4273. ast_string_field_build(p, url, "<%s>;mode=active", data);
  4274. if (sip_debug_test_pvt(p))
  4275. ast_debug(1, "Send URL %s, state = %u!\n", data, ast_channel_state(chan));
  4276. switch (ast_channel_state(chan)) {
  4277. case AST_STATE_RING:
  4278. transmit_response(p, "100 Trying", &p->initreq);
  4279. break;
  4280. case AST_STATE_RINGING:
  4281. transmit_response(p, "180 Ringing", &p->initreq);
  4282. break;
  4283. case AST_STATE_UP:
  4284. if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
  4285. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  4286. } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  4287. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  4288. }
  4289. break;
  4290. default:
  4291. ast_log(LOG_WARNING, "Don't know how to send URI when state is %u!\n", ast_channel_state(chan));
  4292. }
  4293. return 0;
  4294. }
  4295. /*! \brief Deliver SIP call ID for the call */
  4296. static const char *sip_get_callid(struct ast_channel *chan)
  4297. {
  4298. return ast_channel_tech_pvt(chan) ? ((struct sip_pvt *) ast_channel_tech_pvt(chan))->callid : "";
  4299. }
  4300. /*!
  4301. * \internal
  4302. * \brief Send SIP MESSAGE text within a call
  4303. * \note Called from PBX core sendtext() application
  4304. */
  4305. static int sip_sendtext(struct ast_channel *ast, const char *text)
  4306. {
  4307. struct sip_pvt *dialog = ast_channel_tech_pvt(ast);
  4308. int debug;
  4309. if (!dialog) {
  4310. return -1;
  4311. }
  4312. /* NOT ast_strlen_zero, because a zero-length message is specifically
  4313. * allowed by RFC 3428 (See section 10, Examples) */
  4314. if (!text) {
  4315. return 0;
  4316. }
  4317. if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
  4318. ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
  4319. return 0;
  4320. }
  4321. debug = sip_debug_test_pvt(dialog);
  4322. if (debug) {
  4323. ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
  4324. }
  4325. /* Setup to send text message */
  4326. sip_pvt_lock(dialog);
  4327. destroy_msg_headers(dialog);
  4328. ast_string_field_set(dialog, msg_body, text);
  4329. transmit_message(dialog, 0, 0);
  4330. sip_pvt_unlock(dialog);
  4331. return 0;
  4332. }
  4333. /*! \brief Update peer object in realtime storage
  4334. If the Asterisk system name is set in asterisk.conf, we will use
  4335. that name and store that in the "regserver" field in the sippeers
  4336. table to facilitate multi-server setups.
  4337. */
  4338. static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms, const char *path)
  4339. {
  4340. char port[10];
  4341. char ipaddr[INET6_ADDRSTRLEN];
  4342. char regseconds[20];
  4343. char *tablename = NULL;
  4344. char str_lastms[20];
  4345. const char *sysname = ast_config_AST_SYSTEM_NAME;
  4346. char *syslabel = NULL;
  4347. time_t nowtime = time(NULL) + expirey;
  4348. const char *fc = fullcontact ? "fullcontact" : NULL;
  4349. int realtimeregs = ast_check_realtime("sipregs");
  4350. tablename = realtimeregs ? "sipregs" : "sippeers";
  4351. snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
  4352. snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
  4353. ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
  4354. ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
  4355. if (ast_strlen_zero(sysname)) { /* No system name, disable this */
  4356. sysname = NULL;
  4357. } else if (sip_cfg.rtsave_sysname) {
  4358. syslabel = "regserver";
  4359. }
  4360. /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
  4361. * must also add it to contrib/scripts/asterisk.ldap-schema,
  4362. * contrib/scripts/asterisk.ldif,
  4363. * and to configs/res_ldap.conf.sample as described in
  4364. * bugs 15156 and 15895
  4365. */
  4366. /* This is ugly, we need something better ;-) */
  4367. if (sip_cfg.rtsave_path) {
  4368. if (fc) {
  4369. ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
  4370. "port", port, "regseconds", regseconds,
  4371. deprecated_username ? "username" : "defaultuser", defaultuser,
  4372. "useragent", useragent, "lastms", str_lastms,
  4373. "path", path, /* Path data can be NULL */
  4374. fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
  4375. } else {
  4376. ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
  4377. "port", port, "regseconds", regseconds,
  4378. "useragent", useragent, "lastms", str_lastms,
  4379. deprecated_username ? "username" : "defaultuser", defaultuser,
  4380. "path", path, /* Path data can be NULL */
  4381. syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
  4382. }
  4383. } else {
  4384. if (fc) {
  4385. ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
  4386. "port", port, "regseconds", regseconds,
  4387. deprecated_username ? "username" : "defaultuser", defaultuser,
  4388. "useragent", useragent, "lastms", str_lastms,
  4389. fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
  4390. } else {
  4391. ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
  4392. "port", port, "regseconds", regseconds,
  4393. "useragent", useragent, "lastms", str_lastms,
  4394. deprecated_username ? "username" : "defaultuser", defaultuser,
  4395. syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
  4396. }
  4397. }
  4398. }
  4399. /*! \brief Automatically add peer extension to dial plan */
  4400. static void register_peer_exten(struct sip_peer *peer, int onoff)
  4401. {
  4402. char multi[256];
  4403. char *stringp, *ext, *context;
  4404. struct pbx_find_info q = { .stacklen = 0 };
  4405. /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
  4406. * the name of the global regexten context, if not specified
  4407. * individually.
  4408. */
  4409. if (ast_strlen_zero(sip_cfg.regcontext))
  4410. return;
  4411. ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
  4412. stringp = multi;
  4413. while ((ext = strsep(&stringp, "&"))) {
  4414. if ((context = strchr(ext, '@'))) {
  4415. *context++ = '\0'; /* split ext@context */
  4416. if (!ast_context_find(context)) {
  4417. ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
  4418. continue;
  4419. }
  4420. } else {
  4421. context = sip_cfg.regcontext;
  4422. }
  4423. if (onoff) {
  4424. if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
  4425. ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
  4426. ast_strdup(peer->name), ast_free_ptr, "SIP");
  4427. }
  4428. } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
  4429. ast_context_remove_extension(context, ext, 1, NULL);
  4430. }
  4431. }
  4432. }
  4433. /*! Destroy mailbox subscriptions */
  4434. static void destroy_mailbox(struct sip_mailbox *mailbox)
  4435. {
  4436. if (mailbox->event_sub) {
  4437. mailbox->event_sub = stasis_unsubscribe(mailbox->event_sub);
  4438. }
  4439. ast_free(mailbox);
  4440. }
  4441. /*! Destroy all peer-related mailbox subscriptions */
  4442. static void clear_peer_mailboxes(struct sip_peer *peer)
  4443. {
  4444. struct sip_mailbox *mailbox;
  4445. while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
  4446. destroy_mailbox(mailbox);
  4447. }
  4448. static void sip_destroy_peer_fn(void *peer)
  4449. {
  4450. sip_destroy_peer(peer);
  4451. }
  4452. /*! \brief Destroy peer object from memory */
  4453. static void sip_destroy_peer(struct sip_peer *peer)
  4454. {
  4455. ast_debug(3, "Destroying SIP peer %s\n", peer->name);
  4456. /*
  4457. * Remove any mailbox event subscriptions for this peer before
  4458. * we destroy anything. An event subscription callback may be
  4459. * happening right now.
  4460. */
  4461. clear_peer_mailboxes(peer);
  4462. if (peer->outboundproxy) {
  4463. ao2_ref(peer->outboundproxy, -1);
  4464. peer->outboundproxy = NULL;
  4465. }
  4466. /* Delete it, it needs to disappear */
  4467. if (peer->call) {
  4468. dialog_unlink_all(peer->call);
  4469. peer->call = dialog_unref(peer->call, "peer->call is being unset");
  4470. }
  4471. if (peer->mwipvt) { /* We have an active subscription, delete it */
  4472. dialog_unlink_all(peer->mwipvt);
  4473. peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
  4474. }
  4475. if (peer->chanvars) {
  4476. ast_variables_destroy(peer->chanvars);
  4477. peer->chanvars = NULL;
  4478. }
  4479. sip_route_clear(&peer->path);
  4480. register_peer_exten(peer, FALSE);
  4481. ast_free_acl_list(peer->acl);
  4482. ast_free_acl_list(peer->directmediaacl);
  4483. if (peer->selfdestruct)
  4484. ast_atomic_fetchadd_int(&apeerobjs, -1);
  4485. else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
  4486. ast_atomic_fetchadd_int(&rpeerobjs, -1);
  4487. ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
  4488. } else
  4489. ast_atomic_fetchadd_int(&speerobjs, -1);
  4490. if (peer->auth) {
  4491. ao2_t_ref(peer->auth, -1, "Removing peer authentication");
  4492. peer->auth = NULL;
  4493. }
  4494. if (peer->socket.tcptls_session) {
  4495. ao2_ref(peer->socket.tcptls_session, -1);
  4496. peer->socket.tcptls_session = NULL;
  4497. } else if (peer->socket.ws_session) {
  4498. ast_websocket_unref(peer->socket.ws_session);
  4499. peer->socket.ws_session = NULL;
  4500. }
  4501. peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
  4502. peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
  4503. ast_cc_config_params_destroy(peer->cc_params);
  4504. ast_string_field_free_memory(peer);
  4505. ao2_cleanup(peer->caps);
  4506. ast_rtp_dtls_cfg_free(&peer->dtls_cfg);
  4507. ast_endpoint_shutdown(peer->endpoint);
  4508. peer->endpoint = NULL;
  4509. }
  4510. /*! \brief Update peer data in database (if used) */
  4511. static void update_peer(struct sip_peer *p, int expire)
  4512. {
  4513. int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
  4514. if (sip_cfg.peer_rtupdate && (p->is_realtime || rtcachefriends)) {
  4515. struct ast_str *r = sip_route_list(&p->path, 0, 0);
  4516. if (r) {
  4517. realtime_update_peer(p->name, &p->addr, p->username,
  4518. p->fullcontact, p->useragent, expire, p->deprecated_username,
  4519. p->lastms, ast_str_buffer(r));
  4520. ast_free(r);
  4521. }
  4522. }
  4523. }
  4524. static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
  4525. {
  4526. struct ast_variable *var = NULL;
  4527. struct ast_flags flags = {0};
  4528. char *cat = NULL;
  4529. const char *insecure;
  4530. while ((cat = ast_category_browse(cfg, cat))) {
  4531. insecure = ast_variable_retrieve(cfg, cat, "insecure");
  4532. set_insecure_flags(&flags, insecure, -1);
  4533. if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
  4534. var = ast_category_root(cfg, cat);
  4535. break;
  4536. }
  4537. }
  4538. return var;
  4539. }
  4540. static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
  4541. {
  4542. struct ast_config *peerlist;
  4543. struct ast_variable *var = NULL;
  4544. if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
  4545. if ((var = get_insecure_variable_from_config(peerlist))) {
  4546. /* Must clone, because var will get freed along with
  4547. * peerlist. */
  4548. var = ast_variables_dup(var);
  4549. }
  4550. ast_config_destroy(peerlist);
  4551. }
  4552. return var;
  4553. }
  4554. /* Yes.. the only column that makes sense to pass is "ipaddr", but for
  4555. * consistency's sake, we require the column name to be passed. As extra
  4556. * argument, we take a pointer to var. We already got the info, so we better
  4557. * return it and save the caller a query. If return value is nonzero, then *var
  4558. * is nonzero too (and the other way around). */
  4559. static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
  4560. {
  4561. struct ast_variable *varregs = NULL;
  4562. struct ast_config *regs, *peers;
  4563. char *regscat;
  4564. const char *regname;
  4565. if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
  4566. return NULL;
  4567. }
  4568. /* Load *all* peers that are probably insecure=port */
  4569. if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
  4570. ast_config_destroy(regs);
  4571. return NULL;
  4572. }
  4573. /* Loop over the sipregs that match IP address and attempt to find an
  4574. * insecure=port match to it in sippeers. */
  4575. regscat = NULL;
  4576. while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
  4577. char *peerscat;
  4578. const char *peername;
  4579. peerscat = NULL;
  4580. while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
  4581. if (!strcasecmp(regname, peername)) {
  4582. /* Ensure that it really is insecure=port and
  4583. * not something else. */
  4584. const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
  4585. struct ast_flags flags = {0};
  4586. set_insecure_flags(&flags, insecure, -1);
  4587. if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
  4588. /* ENOMEM checks till the bitter end. */
  4589. if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
  4590. if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
  4591. ast_variables_destroy(varregs);
  4592. varregs = NULL;
  4593. }
  4594. }
  4595. goto done;
  4596. }
  4597. }
  4598. }
  4599. }
  4600. done:
  4601. ast_config_destroy(regs);
  4602. ast_config_destroy(peers);
  4603. return varregs;
  4604. }
  4605. static const char *get_name_from_variable(const struct ast_variable *var)
  4606. {
  4607. /* Don't expect this to return non-NULL. Both NULL and empty
  4608. * values can cause the option to get removed from the variable
  4609. * list. This is called on ast_variables gotten from both
  4610. * ast_load_realtime and ast_load_realtime_multientry.
  4611. * - ast_load_realtime removes options with empty values
  4612. * - ast_load_realtime_multientry does not!
  4613. * For consistent behaviour, we check for the empty name and
  4614. * return NULL instead. */
  4615. const struct ast_variable *tmp;
  4616. for (tmp = var; tmp; tmp = tmp->next) {
  4617. if (!strcasecmp(tmp->name, "name")) {
  4618. if (!ast_strlen_zero(tmp->value)) {
  4619. return tmp->value;
  4620. }
  4621. break;
  4622. }
  4623. }
  4624. return NULL;
  4625. }
  4626. /* If varregs is NULL, we don't use sipregs.
  4627. * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
  4628. static int realtime_peer_by_name(const char *const *name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
  4629. {
  4630. /* Peer by name and host=dynamic */
  4631. if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
  4632. ;
  4633. /* Peer by name and host=IP */
  4634. } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
  4635. ;
  4636. /* Peer by name and host=HOSTNAME */
  4637. } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
  4638. /*!\note
  4639. * If this one loaded something, then we need to ensure that the host
  4640. * field matched. The only reason why we can't have this as a criteria
  4641. * is because we only have the IP address and the host field might be
  4642. * set as a name (and the reverse PTR might not match).
  4643. */
  4644. if (addr) {
  4645. struct ast_variable *tmp;
  4646. for (tmp = *var; tmp; tmp = tmp->next) {
  4647. if (!strcasecmp(tmp->name, "host")) {
  4648. struct ast_sockaddr *addrs = NULL;
  4649. if (ast_sockaddr_resolve(&addrs,
  4650. tmp->value,
  4651. PARSE_PORT_FORBID,
  4652. get_address_family_filter(AST_TRANSPORT_UDP)) <= 0 ||
  4653. ast_sockaddr_cmp(&addrs[0], addr)) {
  4654. /* No match */
  4655. ast_variables_destroy(*var);
  4656. *var = NULL;
  4657. }
  4658. ast_free(addrs);
  4659. break;
  4660. }
  4661. }
  4662. }
  4663. }
  4664. /* Did we find anything? */
  4665. if (*var) {
  4666. if (varregs) {
  4667. *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
  4668. }
  4669. return 1;
  4670. }
  4671. return 0;
  4672. }
  4673. /* Another little helper function for backwards compatibility: this
  4674. * checks/fetches the sippeer that belongs to the sipreg. If none is
  4675. * found, we free the sipreg and return false. This way we can do the
  4676. * check inside the if-condition below. In the old code, not finding
  4677. * the sippeer also had it continue look for another match, so we do
  4678. * the same. */
  4679. static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
  4680. struct ast_variable *var = NULL;
  4681. const char *old_name = *name;
  4682. *name = get_name_from_variable(*varregs);
  4683. if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
  4684. if (!*name) {
  4685. ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
  4686. }
  4687. ast_variables_destroy(*varregs);
  4688. *varregs = NULL;
  4689. *name = old_name;
  4690. }
  4691. return var;
  4692. }
  4693. /* If varregs is NULL, we don't use sipregs. If we return true, then *name is
  4694. * set. Using empty if-bodies instead of goto's while avoiding unnecessary
  4695. * indents. */
  4696. static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, const char *callbackexten, struct ast_variable **var, struct ast_variable **varregs)
  4697. {
  4698. char portstring[6]; /* up to 5 digits plus null terminator */
  4699. ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
  4700. /* We're not finding this peer by this name anymore. Reset it. */
  4701. *name = NULL;
  4702. /* First check for fixed IP hosts with matching callbackextensions, if specified */
  4703. if (!ast_strlen_zero(callbackexten) && (*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, "callbackextension", callbackexten, SENTINEL))) {
  4704. ;
  4705. /* Check for fixed IP hosts */
  4706. } else if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
  4707. ;
  4708. /* Check for registered hosts (in sipregs) */
  4709. } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
  4710. (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
  4711. ;
  4712. /* Check for registered hosts (in sippeers) */
  4713. } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
  4714. ;
  4715. /* We couldn't match on ipaddress and port, so we need to check if port is insecure */
  4716. } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
  4717. ;
  4718. /* Same as above, but try the IP address field (in sipregs)
  4719. * Observe that it fetches the name/var at the same time, without the
  4720. * realtime_peer_get_sippeer_helper. Also note that it is quite inefficient.
  4721. * Avoid sipregs if possible. */
  4722. } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
  4723. ;
  4724. /* Same as above, but try the IP address field (in sippeers) */
  4725. } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
  4726. ;
  4727. }
  4728. /* Nothing found? */
  4729. if (!*var) {
  4730. return 0;
  4731. }
  4732. /* Check peer name. It must not be empty. There may exist a
  4733. * different match that does have a name, but it's too late for
  4734. * that now. */
  4735. if (!*name && !(*name = get_name_from_variable(*var))) {
  4736. ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
  4737. ast_variables_destroy(*var);
  4738. *var = NULL;
  4739. if (varregs && *varregs) {
  4740. ast_variables_destroy(*varregs);
  4741. *varregs = NULL;
  4742. }
  4743. return 0;
  4744. }
  4745. /* Make sure varregs is populated if var is. The inverse,
  4746. * ensuring that var is set when varregs is, is taken
  4747. * care of by realtime_peer_get_sippeer_helper(). */
  4748. if (varregs && !*varregs) {
  4749. *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
  4750. }
  4751. return 1;
  4752. }
  4753. static int register_realtime_peers_with_callbackextens(void)
  4754. {
  4755. struct ast_config *cfg;
  4756. char *cat = NULL;
  4757. if (!(ast_check_realtime("sippeers"))) {
  4758. return 0;
  4759. }
  4760. /* This is hacky. We want name to be the cat, so it is the first property */
  4761. if (!(cfg = ast_load_realtime_multientry("sippeers", "name LIKE", "%", "callbackextension LIKE", "%", SENTINEL))) {
  4762. return -1;
  4763. }
  4764. while ((cat = ast_category_browse(cfg, cat))) {
  4765. struct sip_peer *peer;
  4766. struct ast_variable *var = ast_category_root(cfg, cat);
  4767. if (!(peer = build_peer(cat, var, NULL, TRUE, FALSE))) {
  4768. continue;
  4769. }
  4770. ast_log(LOG_NOTICE, "Created realtime peer '%s' for registration\n", peer->name);
  4771. peer->is_realtime = 1;
  4772. sip_unref_peer(peer, "register_realtime_peers: Done registering releasing");
  4773. }
  4774. ast_config_destroy(cfg);
  4775. return 0;
  4776. }
  4777. /*! \brief realtime_peer: Get peer from realtime storage
  4778. * Checks the "sippeers" realtime family from extconfig.conf
  4779. * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
  4780. * This returns a pointer to a peer and because we use build_peer, we can rest
  4781. * assured that the refcount is bumped.
  4782. *
  4783. * \note This is never called with both newpeername and addr at the same time.
  4784. * If you do, be prepared to get a peer with a different name than newpeername.
  4785. */
  4786. static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, char *callbackexten, int devstate_only, int which_objects)
  4787. {
  4788. struct sip_peer *peer = NULL;
  4789. struct ast_variable *var = NULL;
  4790. struct ast_variable *varregs = NULL;
  4791. char ipaddr[INET6_ADDRSTRLEN];
  4792. int realtimeregs = ast_check_realtime("sipregs");
  4793. if (addr) {
  4794. ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
  4795. } else {
  4796. ipaddr[0] = '\0';
  4797. }
  4798. if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
  4799. ;
  4800. } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, callbackexten, &var, realtimeregs ? &varregs : NULL)) {
  4801. ;
  4802. } else {
  4803. return NULL;
  4804. }
  4805. /* If we're looking for users, don't return peers (although this check
  4806. * should probably be done in realtime_peer_by_* instead...) */
  4807. if (which_objects == FINDUSERS) {
  4808. struct ast_variable *tmp;
  4809. for (tmp = var; tmp; tmp = tmp->next) {
  4810. if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
  4811. goto cleanup;
  4812. }
  4813. }
  4814. }
  4815. /* Peer found in realtime, now build it in memory */
  4816. peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
  4817. if (!peer) {
  4818. goto cleanup;
  4819. }
  4820. /* Previous versions of Asterisk did not require the type field to be
  4821. * set for real time peers. This statement preserves that behavior. */
  4822. if (peer->type == 0) {
  4823. if (which_objects == FINDUSERS) {
  4824. peer->type = SIP_TYPE_USER;
  4825. } else if (which_objects == FINDPEERS) {
  4826. peer->type = SIP_TYPE_PEER;
  4827. } else {
  4828. peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
  4829. }
  4830. }
  4831. ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
  4832. if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
  4833. /* Cache peer */
  4834. ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
  4835. if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
  4836. AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
  4837. sip_unref_peer(_data, "remove registration ref"),
  4838. sip_unref_peer(peer, "remove registration ref"),
  4839. sip_ref_peer(peer, "add registration ref"));
  4840. }
  4841. ao2_t_link(peers, peer, "link peer into peers table");
  4842. if (!ast_sockaddr_isnull(&peer->addr)) {
  4843. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  4844. }
  4845. }
  4846. peer->is_realtime = 1;
  4847. cleanup:
  4848. ast_variables_destroy(var);
  4849. ast_variables_destroy(varregs);
  4850. return peer;
  4851. }
  4852. /* Function to assist finding peers by name only */
  4853. static int find_by_name(void *obj, void *arg, void *data, int flags)
  4854. {
  4855. struct sip_peer *search = obj, *match = arg;
  4856. int *which_objects = data;
  4857. /* Usernames in SIP uri's are case sensitive. Domains are not */
  4858. if (strcmp(search->name, match->name)) {
  4859. return 0;
  4860. }
  4861. switch (*which_objects) {
  4862. case FINDUSERS:
  4863. if (!(search->type & SIP_TYPE_USER)) {
  4864. return 0;
  4865. }
  4866. break;
  4867. case FINDPEERS:
  4868. if (!(search->type & SIP_TYPE_PEER)) {
  4869. return 0;
  4870. }
  4871. break;
  4872. case FINDALLDEVICES:
  4873. break;
  4874. }
  4875. return CMP_MATCH | CMP_STOP;
  4876. }
  4877. static struct sip_peer *sip_find_peer_full(const char *peer, struct ast_sockaddr *addr, char *callbackexten, int realtime, int which_objects, int devstate_only, int transport)
  4878. {
  4879. struct sip_peer *p = NULL;
  4880. struct sip_peer tmp_peer;
  4881. if (peer) {
  4882. ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
  4883. p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
  4884. } else if (addr) { /* search by addr? */
  4885. ast_sockaddr_copy(&tmp_peer.addr, addr);
  4886. tmp_peer.flags[0].flags = 0;
  4887. tmp_peer.transports = transport;
  4888. p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table");
  4889. if (!p) {
  4890. ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
  4891. p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table 2");
  4892. if (p) {
  4893. return p;
  4894. }
  4895. }
  4896. }
  4897. if (!p && (realtime || devstate_only)) {
  4898. /* realtime_peer will return a peer with matching callbackexten if possible, otherwise one matching
  4899. * without the callbackexten */
  4900. p = realtime_peer(peer, addr, callbackexten, devstate_only, which_objects);
  4901. if (p) {
  4902. switch (which_objects) {
  4903. case FINDUSERS:
  4904. if (!(p->type & SIP_TYPE_USER)) {
  4905. sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
  4906. return NULL;
  4907. }
  4908. break;
  4909. case FINDPEERS:
  4910. if (!(p->type & SIP_TYPE_PEER)) {
  4911. sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
  4912. return NULL;
  4913. }
  4914. break;
  4915. case FINDALLDEVICES:
  4916. break;
  4917. }
  4918. }
  4919. }
  4920. return p;
  4921. }
  4922. /*!
  4923. * \brief Locate device by name or ip address
  4924. * \param peer, addr, realtime, devstate_only, transport
  4925. * \param which_objects Define which objects should be matched when doing a lookup
  4926. * by name. Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
  4927. * Note that this option is not used at all when doing a lookup by IP.
  4928. *
  4929. * This is used on find matching device on name or ip/port.
  4930. * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
  4931. *
  4932. * \note Avoid using this function in new functions if there is a way to avoid it,
  4933. * since it might cause a database lookup.
  4934. */
  4935. struct sip_peer *sip_find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
  4936. {
  4937. return sip_find_peer_full(peer, addr, NULL, realtime, which_objects, devstate_only, transport);
  4938. }
  4939. static struct sip_peer *sip_find_peer_by_ip_and_exten(struct ast_sockaddr *addr, char *callbackexten, int transport)
  4940. {
  4941. return sip_find_peer_full(NULL, addr, callbackexten, TRUE, FINDPEERS, FALSE, transport);
  4942. }
  4943. /*! \brief Set nat mode on the various data sockets */
  4944. static void do_setnat(struct sip_pvt *p)
  4945. {
  4946. const char *mode;
  4947. int natflags;
  4948. natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
  4949. mode = natflags ? "On" : "Off";
  4950. if (p->rtp) {
  4951. ast_debug(1, "Setting NAT on RTP to %s\n", mode);
  4952. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
  4953. }
  4954. if (p->vrtp) {
  4955. ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
  4956. ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
  4957. }
  4958. if (p->udptl) {
  4959. ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
  4960. ast_udptl_setnat(p->udptl, natflags);
  4961. }
  4962. if (p->trtp) {
  4963. ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
  4964. ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
  4965. }
  4966. }
  4967. /*! \brief Change the T38 state on a SIP dialog */
  4968. static void change_t38_state(struct sip_pvt *p, int state)
  4969. {
  4970. int old = p->t38.state;
  4971. struct ast_channel *chan = p->owner;
  4972. struct ast_control_t38_parameters parameters = { .request_response = 0 };
  4973. /* Don't bother changing if we are already in the state wanted */
  4974. if (old == state)
  4975. return;
  4976. p->t38.state = state;
  4977. ast_debug(2, "T38 state changed to %u on channel %s\n", p->t38.state, chan ? ast_channel_name(chan) : "<none>");
  4978. /* If no channel was provided we can't send off a control frame */
  4979. if (!chan)
  4980. return;
  4981. /* Given the state requested and old state determine what control frame we want to queue up */
  4982. switch (state) {
  4983. case T38_PEER_REINVITE:
  4984. parameters = p->t38.their_parms;
  4985. parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
  4986. parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
  4987. ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
  4988. break;
  4989. case T38_ENABLED:
  4990. parameters = p->t38.their_parms;
  4991. parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
  4992. parameters.request_response = AST_T38_NEGOTIATED;
  4993. ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
  4994. break;
  4995. case T38_REJECTED:
  4996. case T38_DISABLED:
  4997. if (old == T38_ENABLED) {
  4998. parameters.request_response = AST_T38_TERMINATED;
  4999. } else if (old == T38_LOCAL_REINVITE) {
  5000. parameters.request_response = AST_T38_REFUSED;
  5001. }
  5002. break;
  5003. case T38_LOCAL_REINVITE:
  5004. /* wait until we get a peer response before responding to local reinvite */
  5005. break;
  5006. }
  5007. /* Woot we got a message, create a control frame and send it on! */
  5008. if (parameters.request_response)
  5009. ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
  5010. }
  5011. /*! \brief Set the global T38 capabilities on a SIP dialog structure */
  5012. static void set_t38_capabilities(struct sip_pvt *p)
  5013. {
  5014. if (p->udptl) {
  5015. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
  5016. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
  5017. } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
  5018. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
  5019. } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
  5020. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
  5021. }
  5022. }
  5023. }
  5024. static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
  5025. {
  5026. if (to_sock->tcptls_session) {
  5027. ao2_ref(to_sock->tcptls_session, -1);
  5028. to_sock->tcptls_session = NULL;
  5029. } else if (to_sock->ws_session) {
  5030. ast_websocket_unref(to_sock->ws_session);
  5031. to_sock->ws_session = NULL;
  5032. }
  5033. if (from_sock->tcptls_session) {
  5034. ao2_ref(from_sock->tcptls_session, +1);
  5035. } else if (from_sock->ws_session) {
  5036. ast_websocket_ref(from_sock->ws_session);
  5037. }
  5038. *to_sock = *from_sock;
  5039. }
  5040. /*! \brief Initialize DTLS-SRTP support on an RTP instance */
  5041. static int dialog_initialize_dtls_srtp(const struct sip_pvt *dialog, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp)
  5042. {
  5043. struct ast_rtp_engine_dtls *dtls;
  5044. if (!dialog->dtls_cfg.enabled) {
  5045. return 0;
  5046. }
  5047. if (!ast_rtp_engine_srtp_is_registered()) {
  5048. ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
  5049. return -1;
  5050. }
  5051. if (!(dtls = ast_rtp_instance_get_dtls(rtp))) {
  5052. ast_log(LOG_ERROR, "No DTLS-SRTP support present on engine for RTP instance '%p', was it compiled with support for it?\n",
  5053. rtp);
  5054. return -1;
  5055. }
  5056. if (dtls->set_configuration(rtp, &dialog->dtls_cfg)) {
  5057. ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
  5058. rtp);
  5059. return -1;
  5060. }
  5061. if (!(*srtp = ast_sdp_srtp_alloc())) {
  5062. ast_log(LOG_ERROR, "Failed to create required SRTP structure on RTP instance '%p'\n",
  5063. rtp);
  5064. return -1;
  5065. }
  5066. return 0;
  5067. }
  5068. /*! \brief Initialize RTP portion of a dialog
  5069. * \return -1 on failure, 0 on success
  5070. */
  5071. static int dialog_initialize_rtp(struct sip_pvt *dialog)
  5072. {
  5073. struct ast_sockaddr bindaddr_tmp;
  5074. struct ast_rtp_engine_ice *ice;
  5075. if (!sip_methods[dialog->method].need_rtp) {
  5076. return 0;
  5077. }
  5078. if (!ast_sockaddr_isnull(&rtpbindaddr)) {
  5079. ast_sockaddr_copy(&bindaddr_tmp, &rtpbindaddr);
  5080. } else {
  5081. ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
  5082. }
  5083. if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
  5084. return -1;
  5085. }
  5086. if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->rtp))) {
  5087. ice->stop(dialog->rtp);
  5088. }
  5089. if (dialog_initialize_dtls_srtp(dialog, dialog->rtp, &dialog->srtp)) {
  5090. return -1;
  5091. }
  5092. if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
  5093. (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (ast_format_cap_has_type(dialog->caps, AST_MEDIA_TYPE_VIDEO)))) {
  5094. if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
  5095. return -1;
  5096. }
  5097. if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->vrtp))) {
  5098. ice->stop(dialog->vrtp);
  5099. }
  5100. if (dialog_initialize_dtls_srtp(dialog, dialog->vrtp, &dialog->vsrtp)) {
  5101. return -1;
  5102. }
  5103. ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
  5104. ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
  5105. ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
  5106. ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
  5107. ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
  5108. }
  5109. if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
  5110. if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
  5111. return -1;
  5112. }
  5113. if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->trtp))) {
  5114. ice->stop(dialog->trtp);
  5115. }
  5116. if (dialog_initialize_dtls_srtp(dialog, dialog->trtp, &dialog->tsrtp)) {
  5117. return -1;
  5118. }
  5119. /* Do not timeout text as its not constant*/
  5120. ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
  5121. ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
  5122. }
  5123. ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
  5124. ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
  5125. ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
  5126. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
  5127. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  5128. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  5129. ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
  5130. do_setnat(dialog);
  5131. return 0;
  5132. }
  5133. static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp);
  5134. /*! \brief Create address structure from peer reference.
  5135. * This function copies data from peer to the dialog, so we don't have to look up the peer
  5136. * again from memory or database during the life time of the dialog.
  5137. *
  5138. * \return -1 on error, 0 on success.
  5139. *
  5140. */
  5141. static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
  5142. {
  5143. struct sip_auth_container *credentials;
  5144. /* this checks that the dialog is contacting the peer on a valid
  5145. * transport type based on the peers transport configuration,
  5146. * otherwise, this function bails out */
  5147. if (dialog->socket.type && check_request_transport(peer, dialog))
  5148. return -1;
  5149. copy_socket_data(&dialog->socket, &peer->socket);
  5150. if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
  5151. (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
  5152. dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
  5153. dialog->recv = dialog->sa;
  5154. } else
  5155. return -1;
  5156. /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
  5157. ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
  5158. ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  5159. ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  5160. /* Take the peer's caps */
  5161. if (peer->caps) {
  5162. ast_format_cap_remove_by_type(dialog->caps, AST_MEDIA_TYPE_UNKNOWN);
  5163. ast_format_cap_append_from_cap(dialog->caps, peer->caps, AST_MEDIA_TYPE_UNKNOWN);
  5164. }
  5165. dialog->amaflags = peer->amaflags;
  5166. ast_string_field_set(dialog, engine, peer->engine);
  5167. ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &dialog->dtls_cfg);
  5168. dialog->rtptimeout = peer->rtptimeout;
  5169. dialog->rtpholdtimeout = peer->rtpholdtimeout;
  5170. dialog->rtpkeepalive = peer->rtpkeepalive;
  5171. sip_route_copy(&dialog->route, &peer->path);
  5172. if (!sip_route_empty(&dialog->route)) {
  5173. /* Parse SIP URI of first route-set hop and use it as target address */
  5174. __set_address_from_contact(sip_route_first_uri(&dialog->route), &dialog->sa, dialog->socket.type == AST_TRANSPORT_TLS ? 1 : 0);
  5175. }
  5176. if (dialog_initialize_rtp(dialog)) {
  5177. return -1;
  5178. }
  5179. if (dialog->rtp) { /* Audio */
  5180. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  5181. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  5182. /* Set Frame packetization */
  5183. dialog->autoframing = peer->autoframing;
  5184. ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(dialog->rtp), ast_format_cap_get_framing(dialog->caps));
  5185. }
  5186. /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
  5187. ast_string_field_set(dialog, peername, peer->name);
  5188. ast_string_field_set(dialog, authname, peer->username);
  5189. ast_string_field_set(dialog, username, peer->username);
  5190. ast_string_field_set(dialog, peersecret, peer->secret);
  5191. ast_string_field_set(dialog, peermd5secret, peer->md5secret);
  5192. ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
  5193. ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
  5194. ast_string_field_set(dialog, tohost, peer->tohost);
  5195. ast_string_field_set(dialog, fullcontact, peer->fullcontact);
  5196. ast_string_field_set(dialog, accountcode, peer->accountcode);
  5197. ast_string_field_set(dialog, context, peer->context);
  5198. ast_string_field_set(dialog, cid_num, peer->cid_num);
  5199. ast_string_field_set(dialog, cid_name, peer->cid_name);
  5200. ast_string_field_set(dialog, cid_tag, peer->cid_tag);
  5201. ast_string_field_set(dialog, mwi_from, peer->mwi_from);
  5202. if (!ast_strlen_zero(peer->parkinglot)) {
  5203. ast_string_field_set(dialog, parkinglot, peer->parkinglot);
  5204. }
  5205. ast_string_field_set(dialog, engine, peer->engine);
  5206. ref_proxy(dialog, obproxy_get(dialog, peer));
  5207. dialog->callgroup = peer->callgroup;
  5208. dialog->pickupgroup = peer->pickupgroup;
  5209. ast_unref_namedgroups(dialog->named_callgroups);
  5210. dialog->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);
  5211. ast_unref_namedgroups(dialog->named_pickupgroups);
  5212. dialog->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
  5213. ast_copy_string(dialog->zone, peer->zone, sizeof(dialog->zone));
  5214. dialog->allowtransfer = peer->allowtransfer;
  5215. dialog->jointnoncodeccapability = dialog->noncodeccapability;
  5216. /* Update dialog authorization credentials */
  5217. ao2_lock(peer);
  5218. credentials = peer->auth;
  5219. if (credentials) {
  5220. ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
  5221. }
  5222. ao2_unlock(peer);
  5223. ao2_lock(dialog);
  5224. if (dialog->peerauth) {
  5225. ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
  5226. }
  5227. dialog->peerauth = credentials;
  5228. ao2_unlock(dialog);
  5229. dialog->maxcallbitrate = peer->maxcallbitrate;
  5230. dialog->disallowed_methods = peer->disallowed_methods;
  5231. ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
  5232. if (ast_strlen_zero(dialog->tohost))
  5233. ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
  5234. if (!ast_strlen_zero(peer->fromdomain)) {
  5235. ast_string_field_set(dialog, fromdomain, peer->fromdomain);
  5236. if (!dialog->initreq.headers) {
  5237. char *new_callid;
  5238. char *tmpcall = ast_strdupa(dialog->callid);
  5239. /* this sure looks to me like we are going to change the callid on this dialog!! */
  5240. new_callid = strchr(tmpcall, '@');
  5241. if (new_callid) {
  5242. int callid_size;
  5243. *new_callid = '\0';
  5244. /* Change the dialog callid. */
  5245. callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
  5246. new_callid = ast_alloca(callid_size);
  5247. snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
  5248. change_callid_pvt(dialog, new_callid);
  5249. }
  5250. }
  5251. }
  5252. if (!ast_strlen_zero(peer->fromuser)) {
  5253. ast_string_field_set(dialog, fromuser, peer->fromuser);
  5254. }
  5255. if (!ast_strlen_zero(peer->language)) {
  5256. ast_string_field_set(dialog, language, peer->language);
  5257. }
  5258. /* Set timer T1 to RTT for this peer (if known by qualify=) */
  5259. /* Minimum is settable or default to 100 ms */
  5260. /* If there is a maxms and lastms from a qualify use that over a manual T1
  5261. value. Otherwise, use the peer's T1 value. */
  5262. if (peer->maxms && peer->lastms) {
  5263. dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
  5264. } else {
  5265. dialog->timer_t1 = peer->timer_t1;
  5266. }
  5267. /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
  5268. the known timer */
  5269. if (peer->timer_b) {
  5270. dialog->timer_b = peer->timer_b;
  5271. } else {
  5272. dialog->timer_b = 64 * dialog->timer_t1;
  5273. }
  5274. if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
  5275. (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  5276. dialog->noncodeccapability |= AST_RTP_DTMF;
  5277. } else {
  5278. dialog->noncodeccapability &= ~AST_RTP_DTMF;
  5279. }
  5280. dialog->directmediaacl = ast_duplicate_acl_list(peer->directmediaacl);
  5281. if (peer->call_limit) {
  5282. ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
  5283. }
  5284. if (!dialog->portinuri) {
  5285. dialog->portinuri = peer->portinuri;
  5286. }
  5287. dialog->chanvars = copy_vars(peer->chanvars);
  5288. if (peer->fromdomainport) {
  5289. dialog->fromdomainport = peer->fromdomainport;
  5290. }
  5291. dialog->callingpres = peer->callingpres;
  5292. return 0;
  5293. }
  5294. /*! \brief The default sip port for the given transport */
  5295. static inline int default_sip_port(enum ast_transport type)
  5296. {
  5297. return type == AST_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
  5298. }
  5299. /*! \brief create address structure from device name
  5300. * Or, if peer not found, find it in the global DNS
  5301. * returns TRUE (-1) on failure, FALSE on success */
  5302. static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
  5303. {
  5304. struct sip_peer *peer;
  5305. char *peername, *peername2, *hostn;
  5306. char host[MAXHOSTNAMELEN];
  5307. char service[MAXHOSTNAMELEN];
  5308. int srv_ret = 0;
  5309. int tportno;
  5310. AST_DECLARE_APP_ARGS(hostport,
  5311. AST_APP_ARG(host);
  5312. AST_APP_ARG(port);
  5313. );
  5314. peername = ast_strdupa(opeer);
  5315. peername2 = ast_strdupa(opeer);
  5316. AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
  5317. if (hostport.port)
  5318. dialog->portinuri = 1;
  5319. dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
  5320. dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
  5321. peer = sip_find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
  5322. if (peer) {
  5323. int res;
  5324. if (newdialog) {
  5325. set_socket_transport(&dialog->socket, 0);
  5326. }
  5327. res = create_addr_from_peer(dialog, peer);
  5328. dialog->relatedpeer = sip_ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
  5329. sip_unref_peer(peer, "create_addr: unref peer from sip_find_peer hashtab lookup");
  5330. return res;
  5331. } else if (ast_check_digits(peername)) {
  5332. /* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
  5333. * it makes dialing SIP/${EXTEN} for a peer that isn't defined resolve to an IP that is
  5334. * almost certainly not intended. It is much better to just reject purely numeric hostnames */
  5335. ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
  5336. return -1;
  5337. } else {
  5338. dialog->rtptimeout = global_rtptimeout;
  5339. dialog->rtpholdtimeout = global_rtpholdtimeout;
  5340. dialog->rtpkeepalive = global_rtpkeepalive;
  5341. if (dialog_initialize_rtp(dialog)) {
  5342. return -1;
  5343. }
  5344. }
  5345. ast_string_field_set(dialog, tohost, hostport.host);
  5346. dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
  5347. /* Get the outbound proxy information */
  5348. ref_proxy(dialog, obproxy_get(dialog, NULL));
  5349. if (addr) {
  5350. /* This address should be updated using dnsmgr */
  5351. ast_sockaddr_copy(&dialog->sa, addr);
  5352. } else {
  5353. /* Let's see if we can find the host in DNS. First try DNS SRV records,
  5354. then hostname lookup */
  5355. /*! \todo Fix this function. When we ask for SRV, we should check all transports
  5356. In the future, we should first check NAPTR to find out transport preference
  5357. */
  5358. hostn = peername;
  5359. /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
  5360. * an A record lookup should be used instead of SRV.
  5361. */
  5362. if (!hostport.port && sip_cfg.srvlookup) {
  5363. snprintf(service, sizeof(service), "_%s._%s.%s",
  5364. get_srv_service(dialog->socket.type),
  5365. get_srv_protocol(dialog->socket.type), peername);
  5366. if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
  5367. service)) > 0) {
  5368. hostn = host;
  5369. }
  5370. }
  5371. if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : AST_TRANSPORT_UDP)) {
  5372. ast_log(LOG_WARNING, "No such host: %s\n", peername);
  5373. return -1;
  5374. }
  5375. if (srv_ret > 0) {
  5376. ast_sockaddr_set_port(&dialog->sa, tportno);
  5377. }
  5378. }
  5379. if (!dialog->socket.type)
  5380. set_socket_transport(&dialog->socket, AST_TRANSPORT_UDP);
  5381. if (!dialog->socket.port) {
  5382. dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
  5383. }
  5384. if (!ast_sockaddr_port(&dialog->sa)) {
  5385. ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
  5386. }
  5387. ast_sockaddr_copy(&dialog->recv, &dialog->sa);
  5388. return 0;
  5389. }
  5390. /*! \brief Scheduled congestion on a call.
  5391. * Only called by the scheduler, must return the reference when done.
  5392. */
  5393. static int auto_congest(const void *arg)
  5394. {
  5395. struct sip_pvt *p = (struct sip_pvt *)arg;
  5396. sip_pvt_lock(p);
  5397. p->initid = -1; /* event gone, will not be rescheduled */
  5398. if (p->owner) {
  5399. /* XXX fails on possible deadlock */
  5400. if (!ast_channel_trylock(p->owner)) {
  5401. append_history(p, "Cong", "Auto-congesting (timer)");
  5402. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  5403. ast_channel_unlock(p->owner);
  5404. }
  5405. /* Give the channel a chance to act before we proceed with destruction */
  5406. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  5407. }
  5408. sip_pvt_unlock(p);
  5409. dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
  5410. return 0;
  5411. }
  5412. /*! \brief Initiate SIP call from PBX
  5413. * used from the dial() application */
  5414. static int sip_call(struct ast_channel *ast, const char *dest, int timeout)
  5415. {
  5416. int res;
  5417. struct sip_pvt *p = ast_channel_tech_pvt(ast); /* chan is locked, so the reference cannot go away */
  5418. struct varshead *headp;
  5419. struct ast_var_t *current;
  5420. const char *referer = NULL; /* SIP referrer */
  5421. int cc_core_id;
  5422. char uri[SIPBUFSIZE] = "";
  5423. if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
  5424. ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
  5425. return -1;
  5426. }
  5427. if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
  5428. char device_name[AST_CHANNEL_NAME];
  5429. struct ast_cc_monitor *recall_monitor;
  5430. struct sip_monitor_instance *monitor_instance;
  5431. ast_channel_get_device_name(ast, device_name, sizeof(device_name));
  5432. if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
  5433. monitor_instance = recall_monitor->private_data;
  5434. ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
  5435. ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
  5436. }
  5437. }
  5438. /* Check whether there is vxml_url, distinctive ring variables */
  5439. headp = ast_channel_varshead(ast);
  5440. AST_LIST_TRAVERSE(headp, current, entries) {
  5441. /* Check whether there is a VXML_URL variable */
  5442. if (!p->options->vxml_url && !strcmp(ast_var_name(current), "VXML_URL")) {
  5443. p->options->vxml_url = ast_var_value(current);
  5444. } else if (!p->options->uri_options && !strcmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
  5445. p->options->uri_options = ast_var_value(current);
  5446. } else if (!p->options->addsipheaders && !strncmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
  5447. /* Check whether there is a variable with a name starting with SIPADDHEADER */
  5448. p->options->addsipheaders = 1;
  5449. } else if (!strcmp(ast_var_name(current), "SIPFROMDOMAIN")) {
  5450. ast_string_field_set(p, fromdomain, ast_var_value(current));
  5451. } else if (!strcmp(ast_var_name(current), "SIPTRANSFER")) {
  5452. /* This is a transferred call */
  5453. p->options->transfer = 1;
  5454. } else if (!strcmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
  5455. /* This is the referrer */
  5456. referer = ast_var_value(current);
  5457. } else if (!strcmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
  5458. /* We're replacing a call. */
  5459. p->options->replaces = ast_var_value(current);
  5460. } else if (!strcmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
  5461. if (sscanf(ast_var_value(current), "%30d", &(p->maxforwards)) != 1) {
  5462. ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
  5463. }
  5464. }
  5465. }
  5466. /* Check to see if we should try to force encryption */
  5467. if (p->req_secure_signaling && p->socket.type != AST_TRANSPORT_TLS) {
  5468. ast_log(LOG_WARNING, "Encrypted signaling is required\n");
  5469. ast_channel_hangupcause_set(ast, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  5470. return -1;
  5471. }
  5472. if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
  5473. if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
  5474. ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
  5475. ast_clear_flag(&p->flags[0], SIP_REINVITE);
  5476. }
  5477. if (p->rtp && !p->srtp && !(p->srtp = ast_sdp_srtp_alloc())) {
  5478. ast_log(LOG_WARNING, "SRTP audio setup failed\n");
  5479. return -1;
  5480. }
  5481. if (p->vrtp && !p->vsrtp && !(p->vsrtp = ast_sdp_srtp_alloc())) {
  5482. ast_log(LOG_WARNING, "SRTP video setup failed\n");
  5483. return -1;
  5484. }
  5485. if (p->trtp && !p->tsrtp && !(p->tsrtp = ast_sdp_srtp_alloc())) {
  5486. ast_log(LOG_WARNING, "SRTP text setup failed\n");
  5487. return -1;
  5488. }
  5489. }
  5490. res = 0;
  5491. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  5492. /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
  5493. * so ensure it is disabled.
  5494. */
  5495. ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
  5496. if (p->options->transfer) {
  5497. char buf[SIPBUFSIZE / 2];
  5498. if (referer) {
  5499. if (sipdebug)
  5500. ast_debug(3, "Call for %s transferred by %s\n", p->username, referer);
  5501. snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
  5502. } else
  5503. snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
  5504. ast_string_field_set(p, cid_name, buf);
  5505. }
  5506. ast_debug(1, "Outgoing Call for %s\n", p->username);
  5507. res = update_call_counter(p, INC_CALL_RINGING);
  5508. if (res == -1) {
  5509. ast_channel_hangupcause_set(ast, AST_CAUSE_USER_BUSY);
  5510. return res;
  5511. }
  5512. p->callingpres = ast_party_id_presentation(&ast_channel_caller(ast)->id);
  5513. ast_rtp_instance_available_formats(p->rtp, p->caps, p->prefcaps, p->jointcaps);
  5514. p->jointnoncodeccapability = p->noncodeccapability;
  5515. /* If there are no audio formats left to offer, punt */
  5516. if (!(ast_format_cap_has_type(p->jointcaps, AST_MEDIA_TYPE_AUDIO))) {
  5517. ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
  5518. res = -1;
  5519. } else {
  5520. int xmitres;
  5521. struct ast_party_connected_line connected;
  5522. struct ast_set_party_connected_line update_connected;
  5523. sip_pvt_lock(p);
  5524. /* Supply initial connected line information if available. */
  5525. memset(&update_connected, 0, sizeof(update_connected));
  5526. ast_party_connected_line_init(&connected);
  5527. if (!ast_strlen_zero(p->cid_num)
  5528. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  5529. update_connected.id.number = 1;
  5530. connected.id.number.valid = 1;
  5531. connected.id.number.str = (char *) p->cid_num;
  5532. connected.id.number.presentation = p->callingpres;
  5533. }
  5534. if (!ast_strlen_zero(p->cid_name)
  5535. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  5536. update_connected.id.name = 1;
  5537. connected.id.name.valid = 1;
  5538. connected.id.name.str = (char *) p->cid_name;
  5539. connected.id.name.presentation = p->callingpres;
  5540. }
  5541. if (update_connected.id.number || update_connected.id.name) {
  5542. /* Invalidate any earlier private connected id representation */
  5543. ast_set_party_id_all(&update_connected.priv);
  5544. connected.id.tag = (char *) p->cid_tag;
  5545. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  5546. ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
  5547. }
  5548. xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
  5549. if (xmitres == XMIT_ERROR) {
  5550. sip_pvt_unlock(p);
  5551. return -1;
  5552. }
  5553. p->invitestate = INV_CALLING;
  5554. /* Initialize auto-congest time */
  5555. AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
  5556. dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
  5557. dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
  5558. dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
  5559. sip_pvt_unlock(p);
  5560. }
  5561. return res;
  5562. }
  5563. /*! \brief Destroy registry object
  5564. Objects created with the register= statement in static configuration */
  5565. static void sip_registry_destroy(void *obj)
  5566. {
  5567. struct sip_registry *reg = obj;
  5568. /* Really delete */
  5569. ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
  5570. if (reg->call) {
  5571. /* Clear registry before destroying to ensure
  5572. we don't get reentered trying to grab the registry lock */
  5573. ao2_t_replace(reg->call->registry, NULL, "destroy reg->call->registry");
  5574. ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
  5575. dialog_unlink_all(reg->call);
  5576. reg->call = dialog_unref(reg->call, "unref reg->call");
  5577. /* reg->call = sip_destroy(reg->call); */
  5578. }
  5579. AST_SCHED_DEL(sched, reg->expire);
  5580. AST_SCHED_DEL(sched, reg->timeout);
  5581. ast_string_field_free_memory(reg);
  5582. }
  5583. /*! \brief Destroy MWI subscription object */
  5584. static void sip_subscribe_mwi_destroy(void *data)
  5585. {
  5586. struct sip_subscription_mwi *mwi = data;
  5587. if (mwi->call) {
  5588. mwi->call->mwi = NULL;
  5589. mwi->call = dialog_unref(mwi->call, "sip_subscription_mwi destruction");
  5590. }
  5591. AST_SCHED_DEL(sched, mwi->resub);
  5592. ast_string_field_free_memory(mwi);
  5593. }
  5594. /*! \brief Destroy SDP media offer list */
  5595. static void offered_media_list_destroy(struct sip_pvt *p)
  5596. {
  5597. struct offered_media *offer;
  5598. while ((offer = AST_LIST_REMOVE_HEAD(&p->offered_media, next))) {
  5599. ast_free(offer->decline_m_line);
  5600. ast_free(offer);
  5601. }
  5602. }
  5603. /*! \brief Execute destruction of SIP dialog structure, release memory */
  5604. void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
  5605. {
  5606. struct sip_request *req;
  5607. /* Destroy Session-Timers if allocated */
  5608. if (p->stimer) {
  5609. p->stimer->quit_flag = 1;
  5610. stop_session_timer(p);
  5611. ast_free(p->stimer);
  5612. p->stimer = NULL;
  5613. }
  5614. if (sip_debug_test_pvt(p))
  5615. ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
  5616. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  5617. update_call_counter(p, DEC_CALL_LIMIT);
  5618. ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
  5619. }
  5620. /* Unlink us from the owner if we have one */
  5621. if (p->owner) {
  5622. if (lockowner)
  5623. ast_channel_lock(p->owner);
  5624. ast_debug(1, "Detaching from %s\n", ast_channel_name(p->owner));
  5625. ast_channel_tech_pvt_set(p->owner, NULL);
  5626. /* Make sure that the channel knows its backend is going away */
  5627. ast_channel_softhangup_internal_flag_add(p->owner, AST_SOFTHANGUP_DEV);
  5628. if (lockowner)
  5629. ast_channel_unlock(p->owner);
  5630. /* Give the channel a chance to react before deallocation */
  5631. usleep(1);
  5632. }
  5633. /* Remove link from peer to subscription of MWI */
  5634. if (p->relatedpeer && p->relatedpeer->mwipvt == p)
  5635. p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
  5636. if (p->relatedpeer && p->relatedpeer->call == p)
  5637. p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
  5638. if (p->relatedpeer)
  5639. p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
  5640. if (p->registry) {
  5641. if (p->registry->call == p)
  5642. p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
  5643. ao2_t_replace(p->registry, NULL, "delete p->registry");
  5644. }
  5645. if (p->mwi) {
  5646. p->mwi->call = NULL;
  5647. p->mwi = NULL;
  5648. }
  5649. if (dumphistory)
  5650. sip_dump_history(p);
  5651. if (p->options) {
  5652. if (p->options->outboundproxy) {
  5653. ao2_ref(p->options->outboundproxy, -1);
  5654. }
  5655. ast_free(p->options);
  5656. p->options = NULL;
  5657. }
  5658. if (p->outboundproxy) {
  5659. ref_proxy(p, NULL);
  5660. }
  5661. if (p->notify) {
  5662. ast_variables_destroy(p->notify->headers);
  5663. ast_free(p->notify->content);
  5664. ast_free(p->notify);
  5665. p->notify = NULL;
  5666. }
  5667. if (p->rtp) {
  5668. ast_rtp_instance_destroy(p->rtp);
  5669. p->rtp = NULL;
  5670. }
  5671. if (p->vrtp) {
  5672. ast_rtp_instance_destroy(p->vrtp);
  5673. p->vrtp = NULL;
  5674. }
  5675. if (p->trtp) {
  5676. ast_rtp_instance_destroy(p->trtp);
  5677. p->trtp = NULL;
  5678. }
  5679. if (p->udptl) {
  5680. ast_udptl_destroy(p->udptl);
  5681. p->udptl = NULL;
  5682. }
  5683. sip_refer_destroy(p);
  5684. sip_route_clear(&p->route);
  5685. deinit_req(&p->initreq);
  5686. /* Clear history */
  5687. if (p->history) {
  5688. struct sip_history *hist;
  5689. while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
  5690. ast_free(hist);
  5691. p->history_entries--;
  5692. }
  5693. ast_free(p->history);
  5694. p->history = NULL;
  5695. }
  5696. while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
  5697. ast_free(req);
  5698. }
  5699. offered_media_list_destroy(p);
  5700. if (p->chanvars) {
  5701. ast_variables_destroy(p->chanvars);
  5702. p->chanvars = NULL;
  5703. }
  5704. destroy_msg_headers(p);
  5705. if (p->srtp) {
  5706. ast_sdp_srtp_destroy(p->srtp);
  5707. p->srtp = NULL;
  5708. }
  5709. if (p->vsrtp) {
  5710. ast_sdp_srtp_destroy(p->vsrtp);
  5711. p->vsrtp = NULL;
  5712. }
  5713. if (p->tsrtp) {
  5714. ast_sdp_srtp_destroy(p->tsrtp);
  5715. p->tsrtp = NULL;
  5716. }
  5717. if (p->directmediaacl) {
  5718. p->directmediaacl = ast_free_acl_list(p->directmediaacl);
  5719. }
  5720. ast_string_field_free_memory(p);
  5721. ast_cc_config_params_destroy(p->cc_params);
  5722. p->cc_params = NULL;
  5723. if (p->epa_entry) {
  5724. ao2_ref(p->epa_entry, -1);
  5725. p->epa_entry = NULL;
  5726. }
  5727. if (p->socket.tcptls_session) {
  5728. ao2_ref(p->socket.tcptls_session, -1);
  5729. p->socket.tcptls_session = NULL;
  5730. } else if (p->socket.ws_session) {
  5731. ast_websocket_unref(p->socket.ws_session);
  5732. p->socket.ws_session = NULL;
  5733. }
  5734. if (p->peerauth) {
  5735. ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
  5736. p->peerauth = NULL;
  5737. }
  5738. p->named_callgroups = ast_unref_namedgroups(p->named_callgroups);
  5739. p->named_pickupgroups = ast_unref_namedgroups(p->named_pickupgroups);
  5740. ao2_cleanup(p->caps);
  5741. ao2_cleanup(p->jointcaps);
  5742. ao2_cleanup(p->peercaps);
  5743. ao2_cleanup(p->redircaps);
  5744. ao2_cleanup(p->prefcaps);
  5745. ast_rtp_dtls_cfg_free(&p->dtls_cfg);
  5746. if (p->last_device_state_info) {
  5747. ao2_ref(p->last_device_state_info, -1);
  5748. p->last_device_state_info = NULL;
  5749. }
  5750. }
  5751. /*! \brief update_call_counter: Handle call_limit for SIP devices
  5752. * Setting a call-limit will cause calls above the limit not to be accepted.
  5753. *
  5754. * Remember that for a type=friend, there's one limit for the user and
  5755. * another for the peer, not a combined call limit.
  5756. * This will cause unexpected behaviour in subscriptions, since a "friend"
  5757. * is *two* devices in Asterisk, not one.
  5758. *
  5759. * Thought: For realtime, we should probably update storage with inuse counter...
  5760. *
  5761. * \return 0 if call is ok (no call limit, below threshold)
  5762. * -1 on rejection of call
  5763. *
  5764. */
  5765. static int update_call_counter(struct sip_pvt *fup, int event)
  5766. {
  5767. char name[256];
  5768. int *inuse = NULL, *call_limit = NULL, *ringing = NULL;
  5769. int outgoing = fup->outgoing_call;
  5770. struct sip_peer *p = NULL;
  5771. ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
  5772. /* Test if we need to check call limits, in order to avoid
  5773. realtime lookups if we do not need it */
  5774. if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
  5775. return 0;
  5776. ast_copy_string(name, fup->username, sizeof(name));
  5777. /* Check the list of devices */
  5778. if (fup->relatedpeer) {
  5779. p = sip_ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
  5780. inuse = &p->inuse;
  5781. call_limit = &p->call_limit;
  5782. ringing = &p->ringing;
  5783. ast_copy_string(name, fup->peername, sizeof(name));
  5784. }
  5785. if (!p) {
  5786. ast_debug(2, "%s is not a local device, no call limit\n", name);
  5787. return 0;
  5788. }
  5789. switch(event) {
  5790. /* incoming and outgoing affects the inuse counter */
  5791. case DEC_CALL_LIMIT:
  5792. /* Decrement inuse count if applicable */
  5793. if (inuse) {
  5794. sip_pvt_lock(fup);
  5795. ao2_lock(p);
  5796. if (*inuse > 0) {
  5797. if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
  5798. (*inuse)--;
  5799. ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
  5800. }
  5801. } else {
  5802. *inuse = 0;
  5803. }
  5804. ao2_unlock(p);
  5805. sip_pvt_unlock(fup);
  5806. }
  5807. /* Decrement ringing count if applicable */
  5808. if (ringing) {
  5809. sip_pvt_lock(fup);
  5810. ao2_lock(p);
  5811. if (*ringing > 0) {
  5812. if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
  5813. (*ringing)--;
  5814. ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
  5815. }
  5816. } else {
  5817. *ringing = 0;
  5818. }
  5819. ao2_unlock(p);
  5820. sip_pvt_unlock(fup);
  5821. }
  5822. /* Decrement onhold count if applicable */
  5823. sip_pvt_lock(fup);
  5824. ao2_lock(p);
  5825. if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
  5826. ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
  5827. ao2_unlock(p);
  5828. sip_pvt_unlock(fup);
  5829. sip_peer_hold(fup, FALSE);
  5830. } else {
  5831. ao2_unlock(p);
  5832. sip_pvt_unlock(fup);
  5833. }
  5834. if (sipdebug)
  5835. ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
  5836. break;
  5837. case INC_CALL_RINGING:
  5838. case INC_CALL_LIMIT:
  5839. /* If call limit is active and we have reached the limit, reject the call */
  5840. if (*call_limit > 0 ) {
  5841. if (*inuse >= *call_limit) {
  5842. ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
  5843. sip_unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
  5844. return -1;
  5845. }
  5846. }
  5847. if (ringing && (event == INC_CALL_RINGING)) {
  5848. sip_pvt_lock(fup);
  5849. ao2_lock(p);
  5850. if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
  5851. (*ringing)++;
  5852. ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
  5853. }
  5854. ao2_unlock(p);
  5855. sip_pvt_unlock(fup);
  5856. }
  5857. if (inuse) {
  5858. sip_pvt_lock(fup);
  5859. ao2_lock(p);
  5860. if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
  5861. (*inuse)++;
  5862. ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
  5863. }
  5864. ao2_unlock(p);
  5865. sip_pvt_unlock(fup);
  5866. }
  5867. if (sipdebug) {
  5868. ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
  5869. }
  5870. break;
  5871. case DEC_CALL_RINGING:
  5872. if (ringing) {
  5873. sip_pvt_lock(fup);
  5874. ao2_lock(p);
  5875. if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
  5876. if (*ringing > 0) {
  5877. (*ringing)--;
  5878. }
  5879. ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
  5880. }
  5881. ao2_unlock(p);
  5882. sip_pvt_unlock(fup);
  5883. }
  5884. break;
  5885. default:
  5886. ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
  5887. }
  5888. if (p) {
  5889. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", p->name);
  5890. sip_unref_peer(p, "update_call_counter: sip_unref_peer from call counter");
  5891. }
  5892. return 0;
  5893. }
  5894. static void sip_destroy_fn(void *p)
  5895. {
  5896. sip_destroy(p);
  5897. }
  5898. /*! \brief Destroy SIP call structure.
  5899. * Make it return NULL so the caller can do things like
  5900. * foo = sip_destroy(foo);
  5901. * and reduce the chance of bugs due to dangling pointers.
  5902. */
  5903. struct sip_pvt *sip_destroy(struct sip_pvt *p)
  5904. {
  5905. ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
  5906. __sip_destroy(p, TRUE, TRUE);
  5907. return NULL;
  5908. }
  5909. /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
  5910. int hangup_sip2cause(int cause)
  5911. {
  5912. /* Possible values taken from causes.h */
  5913. switch(cause) {
  5914. case 401: /* Unauthorized */
  5915. return AST_CAUSE_CALL_REJECTED;
  5916. case 403: /* Not found */
  5917. return AST_CAUSE_CALL_REJECTED;
  5918. case 404: /* Not found */
  5919. return AST_CAUSE_UNALLOCATED;
  5920. case 405: /* Method not allowed */
  5921. return AST_CAUSE_INTERWORKING;
  5922. case 407: /* Proxy authentication required */
  5923. return AST_CAUSE_CALL_REJECTED;
  5924. case 408: /* No reaction */
  5925. return AST_CAUSE_NO_USER_RESPONSE;
  5926. case 409: /* Conflict */
  5927. return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
  5928. case 410: /* Gone */
  5929. return AST_CAUSE_NUMBER_CHANGED;
  5930. case 411: /* Length required */
  5931. return AST_CAUSE_INTERWORKING;
  5932. case 413: /* Request entity too large */
  5933. return AST_CAUSE_INTERWORKING;
  5934. case 414: /* Request URI too large */
  5935. return AST_CAUSE_INTERWORKING;
  5936. case 415: /* Unsupported media type */
  5937. return AST_CAUSE_INTERWORKING;
  5938. case 420: /* Bad extension */
  5939. return AST_CAUSE_NO_ROUTE_DESTINATION;
  5940. case 480: /* No answer */
  5941. return AST_CAUSE_NO_ANSWER;
  5942. case 481: /* No answer */
  5943. return AST_CAUSE_INTERWORKING;
  5944. case 482: /* Loop detected */
  5945. return AST_CAUSE_INTERWORKING;
  5946. case 483: /* Too many hops */
  5947. return AST_CAUSE_NO_ANSWER;
  5948. case 484: /* Address incomplete */
  5949. return AST_CAUSE_INVALID_NUMBER_FORMAT;
  5950. case 485: /* Ambiguous */
  5951. return AST_CAUSE_UNALLOCATED;
  5952. case 486: /* Busy everywhere */
  5953. return AST_CAUSE_BUSY;
  5954. case 487: /* Request terminated */
  5955. return AST_CAUSE_INTERWORKING;
  5956. case 488: /* No codecs approved */
  5957. return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  5958. case 491: /* Request pending */
  5959. return AST_CAUSE_INTERWORKING;
  5960. case 493: /* Undecipherable */
  5961. return AST_CAUSE_INTERWORKING;
  5962. case 500: /* Server internal failure */
  5963. return AST_CAUSE_FAILURE;
  5964. case 501: /* Call rejected */
  5965. return AST_CAUSE_FACILITY_REJECTED;
  5966. case 502:
  5967. return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
  5968. case 503: /* Service unavailable */
  5969. return AST_CAUSE_CONGESTION;
  5970. case 504: /* Gateway timeout */
  5971. return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
  5972. case 505: /* SIP version not supported */
  5973. return AST_CAUSE_INTERWORKING;
  5974. case 600: /* Busy everywhere */
  5975. return AST_CAUSE_USER_BUSY;
  5976. case 603: /* Decline */
  5977. return AST_CAUSE_CALL_REJECTED;
  5978. case 604: /* Does not exist anywhere */
  5979. return AST_CAUSE_UNALLOCATED;
  5980. case 606: /* Not acceptable */
  5981. return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  5982. default:
  5983. if (cause < 500 && cause >= 400) {
  5984. /* 4xx class error that is unknown - someting wrong with our request */
  5985. return AST_CAUSE_INTERWORKING;
  5986. } else if (cause < 600 && cause >= 500) {
  5987. /* 5xx class error - problem in the remote end */
  5988. return AST_CAUSE_CONGESTION;
  5989. } else if (cause < 700 && cause >= 600) {
  5990. /* 6xx - global errors in the 4xx class */
  5991. return AST_CAUSE_INTERWORKING;
  5992. }
  5993. return AST_CAUSE_NORMAL;
  5994. }
  5995. /* Never reached */
  5996. return 0;
  5997. }
  5998. /*! \brief Convert Asterisk hangup causes to SIP codes
  5999. \verbatim
  6000. Possible values from causes.h
  6001. AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
  6002. AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
  6003. In addition to these, a lot of PRI codes is defined in causes.h
  6004. ...should we take care of them too ?
  6005. Quote RFC 3398
  6006. ISUP Cause value SIP response
  6007. ---------------- ------------
  6008. 1 unallocated number 404 Not Found
  6009. 2 no route to network 404 Not found
  6010. 3 no route to destination 404 Not found
  6011. 16 normal call clearing --- (*)
  6012. 17 user busy 486 Busy here
  6013. 18 no user responding 408 Request Timeout
  6014. 19 no answer from the user 480 Temporarily unavailable
  6015. 20 subscriber absent 480 Temporarily unavailable
  6016. 21 call rejected 403 Forbidden (+)
  6017. 22 number changed (w/o diagnostic) 410 Gone
  6018. 22 number changed (w/ diagnostic) 301 Moved Permanently
  6019. 23 redirection to new destination 410 Gone
  6020. 26 non-selected user clearing 404 Not Found (=)
  6021. 27 destination out of order 502 Bad Gateway
  6022. 28 address incomplete 484 Address incomplete
  6023. 29 facility rejected 501 Not implemented
  6024. 31 normal unspecified 480 Temporarily unavailable
  6025. \endverbatim
  6026. */
  6027. const char *hangup_cause2sip(int cause)
  6028. {
  6029. switch (cause) {
  6030. case AST_CAUSE_UNALLOCATED: /* 1 */
  6031. case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
  6032. case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
  6033. return "404 Not Found";
  6034. case AST_CAUSE_CONGESTION: /* 34 */
  6035. case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
  6036. return "503 Service Unavailable";
  6037. case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
  6038. return "408 Request Timeout";
  6039. case AST_CAUSE_NO_ANSWER: /* 19 */
  6040. case AST_CAUSE_UNREGISTERED: /* 20 */
  6041. return "480 Temporarily unavailable";
  6042. case AST_CAUSE_CALL_REJECTED: /* 21 */
  6043. return "403 Forbidden";
  6044. case AST_CAUSE_NUMBER_CHANGED: /* 22 */
  6045. return "410 Gone";
  6046. case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
  6047. return "480 Temporarily unavailable";
  6048. case AST_CAUSE_INVALID_NUMBER_FORMAT:
  6049. return "484 Address incomplete";
  6050. case AST_CAUSE_USER_BUSY:
  6051. return "486 Busy here";
  6052. case AST_CAUSE_FAILURE:
  6053. return "500 Server internal failure";
  6054. case AST_CAUSE_FACILITY_REJECTED: /* 29 */
  6055. return "501 Not Implemented";
  6056. case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
  6057. return "503 Service Unavailable";
  6058. /* Used in chan_iax2 */
  6059. case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
  6060. return "502 Bad Gateway";
  6061. case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
  6062. return "488 Not Acceptable Here";
  6063. case AST_CAUSE_INTERWORKING: /* Unspecified Interworking issues */
  6064. return "500 Network error";
  6065. case AST_CAUSE_NOTDEFINED:
  6066. default:
  6067. ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
  6068. return NULL;
  6069. }
  6070. /* Never reached */
  6071. return 0;
  6072. }
  6073. static int reinvite_timeout(const void *data)
  6074. {
  6075. struct sip_pvt *dialog = (struct sip_pvt *) data;
  6076. struct ast_channel *owner = sip_pvt_lock_full(dialog);
  6077. dialog->reinviteid = -1;
  6078. check_pendings(dialog);
  6079. if (owner) {
  6080. ast_channel_unlock(owner);
  6081. ast_channel_unref(owner);
  6082. }
  6083. ao2_unlock(dialog);
  6084. dialog_unref(dialog, "unref for reinvite timeout");
  6085. return 0;
  6086. }
  6087. /*! \brief sip_hangup: Hangup SIP call
  6088. * Part of PBX interface, called from ast_hangup */
  6089. static int sip_hangup(struct ast_channel *ast)
  6090. {
  6091. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6092. int needcancel = FALSE;
  6093. int needdestroy = 0;
  6094. struct ast_channel *oldowner = ast;
  6095. if (!p) {
  6096. ast_debug(1, "Asked to hangup channel that was not connected\n");
  6097. return 0;
  6098. }
  6099. if (ast_channel_hangupcause(ast) == AST_CAUSE_ANSWERED_ELSEWHERE) {
  6100. ast_debug(1, "This call was answered elsewhere\n");
  6101. append_history(p, "Cancel", "Call answered elsewhere");
  6102. p->answered_elsewhere = TRUE;
  6103. }
  6104. /* Store hangupcause locally in PVT so we still have it before disconnect */
  6105. if (p->owner)
  6106. p->hangupcause = ast_channel_hangupcause(p->owner);
  6107. if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
  6108. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  6109. if (sipdebug)
  6110. ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
  6111. update_call_counter(p, DEC_CALL_LIMIT);
  6112. }
  6113. ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
  6114. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  6115. ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
  6116. if (p->owner) {
  6117. sip_pvt_lock(p);
  6118. oldowner = p->owner;
  6119. sip_set_owner(p, NULL); /* Owner will be gone after we return, so take it away */
  6120. sip_pvt_unlock(p);
  6121. ast_channel_tech_pvt_set(oldowner, dialog_unref(ast_channel_tech_pvt(oldowner), "unref oldowner->tech_pvt"));
  6122. }
  6123. ast_module_unref(ast_module_info->self);
  6124. return 0;
  6125. }
  6126. ast_debug(1, "Hangup call %s, SIP callid %s\n", ast_channel_name(ast), p->callid);
  6127. sip_pvt_lock(p);
  6128. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  6129. if (sipdebug)
  6130. ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
  6131. update_call_counter(p, DEC_CALL_LIMIT);
  6132. }
  6133. /* Determine how to disconnect */
  6134. if (p->owner != ast) {
  6135. ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
  6136. sip_pvt_unlock(p);
  6137. return 0;
  6138. }
  6139. /* If the call is not UP, we need to send CANCEL instead of BYE */
  6140. /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
  6141. if (p->invitestate < INV_COMPLETED && ast_channel_state(p->owner) != AST_STATE_UP) {
  6142. needcancel = TRUE;
  6143. ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast_channel_state(ast)));
  6144. }
  6145. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  6146. append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", ast_cause2str(p->hangupcause));
  6147. /* Disconnect */
  6148. disable_dsp_detect(p);
  6149. sip_set_owner(p, NULL);
  6150. ast_channel_tech_pvt_set(ast, NULL);
  6151. ast_module_unref(ast_module_info->self);
  6152. /* Do not destroy this pvt until we have timeout or
  6153. get an answer to the BYE or INVITE/CANCEL
  6154. If we get no answer during retransmit period, drop the call anyway.
  6155. (Sorry, mother-in-law, you can't deny a hangup by sending
  6156. 603 declined to BYE...)
  6157. */
  6158. if (p->alreadygone)
  6159. needdestroy = 1; /* Set destroy flag at end of this function */
  6160. else if (p->invitestate != INV_CALLING)
  6161. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  6162. /* Start the process if it's not already started */
  6163. if (!p->alreadygone && p->initreq.data && ast_str_strlen(p->initreq.data)) {
  6164. if (needcancel) { /* Outgoing call, not up */
  6165. if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6166. /* if we can't send right now, mark it pending */
  6167. if (p->invitestate == INV_CALLING) {
  6168. /* We can't send anything in CALLING state */
  6169. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  6170. /* Do we need a timer here if we don't hear from them at all? Yes we do or else we will get hung dialogs and those are no fun. */
  6171. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  6172. append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
  6173. } else {
  6174. struct sip_pkt *cur;
  6175. for (cur = p->packets; cur; cur = cur->next) {
  6176. __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(ast_str_buffer(cur->data)));
  6177. }
  6178. p->invitestate = INV_CANCELLED;
  6179. /* Send a new request: CANCEL */
  6180. transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
  6181. /* Actually don't destroy us yet, wait for the 487 on our original
  6182. INVITE, but do set an autodestruct just in case we never get it. */
  6183. needdestroy = 0;
  6184. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  6185. }
  6186. } else { /* Incoming call, not up */
  6187. const char *res;
  6188. AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
  6189. if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
  6190. transmit_response_reliable(p, res, &p->initreq);
  6191. else
  6192. transmit_response_reliable(p, "603 Declined", &p->initreq);
  6193. p->invitestate = INV_TERMINATED;
  6194. }
  6195. } else { /* Call is in UP state, send BYE */
  6196. if (p->stimer->st_active == TRUE) {
  6197. stop_session_timer(p);
  6198. }
  6199. if (!p->pendinginvite) {
  6200. char *quality;
  6201. char quality_buf[AST_MAX_USER_FIELD];
  6202. if (p->rtp) {
  6203. struct ast_rtp_instance *p_rtp;
  6204. p_rtp = p->rtp;
  6205. ao2_ref(p_rtp, +1);
  6206. ast_channel_unlock(oldowner);
  6207. sip_pvt_unlock(p);
  6208. ast_rtp_instance_set_stats_vars(oldowner, p_rtp);
  6209. ao2_ref(p_rtp, -1);
  6210. ast_channel_lock(oldowner);
  6211. sip_pvt_lock(p);
  6212. }
  6213. /*
  6214. * The channel variables are set below just to get the AMI
  6215. * VarSet event because the channel is being hungup.
  6216. */
  6217. if (p->rtp || p->vrtp || p->trtp) {
  6218. ast_channel_stage_snapshot(oldowner);
  6219. }
  6220. if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  6221. if (p->do_history) {
  6222. append_history(p, "RTCPaudio", "Quality:%s", quality);
  6223. }
  6224. pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
  6225. }
  6226. if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  6227. if (p->do_history) {
  6228. append_history(p, "RTCPvideo", "Quality:%s", quality);
  6229. }
  6230. pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
  6231. }
  6232. if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  6233. if (p->do_history) {
  6234. append_history(p, "RTCPtext", "Quality:%s", quality);
  6235. }
  6236. pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
  6237. }
  6238. if (p->rtp || p->vrtp || p->trtp) {
  6239. ast_channel_stage_snapshot_done(oldowner);
  6240. }
  6241. /* Send a hangup */
  6242. if (ast_channel_state(oldowner) == AST_STATE_UP) {
  6243. transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
  6244. }
  6245. } else {
  6246. /* Note we will need a BYE when this all settles out
  6247. but we can't send one while we have "INVITE" outstanding. */
  6248. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  6249. ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
  6250. AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
  6251. if (sip_cancel_destroy(p)) {
  6252. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  6253. }
  6254. /* If we have an ongoing reinvite, there is a chance that we have gotten a provisional
  6255. * response, but something weird has happened and we will never receive a final response.
  6256. * So, just in case, check for pending actions after a bit of time to trigger the pending
  6257. * bye that we are setting above */
  6258. if (p->ongoing_reinvite && p->reinviteid < 0) {
  6259. p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));
  6260. }
  6261. }
  6262. }
  6263. }
  6264. if (needdestroy) {
  6265. pvt_set_needdestroy(p, "hangup");
  6266. }
  6267. sip_pvt_unlock(p);
  6268. dialog_unref(p, "unref ast->tech_pvt");
  6269. return 0;
  6270. }
  6271. /*! \brief Try setting the codecs suggested by the SIP_CODEC channel variable */
  6272. static void try_suggested_sip_codec(struct sip_pvt *p)
  6273. {
  6274. const char *codec_list;
  6275. char *codec_list_copy;
  6276. struct ast_format_cap *original_jointcaps;
  6277. char *codec;
  6278. int first_codec = 1;
  6279. char *strtok_ptr;
  6280. if (p->outgoing_call) {
  6281. codec_list = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
  6282. } else if (!(codec_list = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
  6283. codec_list = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
  6284. }
  6285. if (ast_strlen_zero(codec_list)) {
  6286. return;
  6287. }
  6288. codec_list_copy = ast_strdupa(codec_list);
  6289. original_jointcaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  6290. if (!original_jointcaps) {
  6291. return;
  6292. }
  6293. ast_format_cap_append_from_cap(original_jointcaps, p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  6294. for (codec = strtok_r(codec_list_copy, ",", &strtok_ptr); codec; codec = strtok_r(NULL, ",", &strtok_ptr)) {
  6295. struct ast_format *fmt;
  6296. codec = ast_strip(codec);
  6297. fmt = ast_format_cache_get(codec);
  6298. if (!fmt) {
  6299. ast_log(AST_LOG_NOTICE, "Ignoring ${SIP_CODEC*} variable because of unrecognized/not configured codec %s (check allow/disallow in sip.conf)\n", codec);
  6300. continue;
  6301. }
  6302. if (ast_format_cap_iscompatible_format(original_jointcaps, fmt) != AST_FORMAT_CMP_NOT_EQUAL) {
  6303. if (first_codec) {
  6304. ast_verb(4, "Set codec to '%s' for this call because of ${SIP_CODEC*} variable\n", codec);
  6305. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  6306. ast_format_cap_append(p->jointcaps, fmt, 0);
  6307. ast_format_cap_remove_by_type(p->caps, AST_MEDIA_TYPE_UNKNOWN);
  6308. ast_format_cap_append(p->caps, fmt, 0);
  6309. first_codec = 0;
  6310. } else {
  6311. ast_verb(4, "Add codec to '%s' for this call because of ${SIP_CODEC*} variable\n", codec);
  6312. /* Add the format to the capabilities structure */
  6313. ast_format_cap_append(p->jointcaps, fmt, 0);
  6314. ast_format_cap_append(p->caps, fmt, 0);
  6315. }
  6316. } else {
  6317. ast_log(AST_LOG_NOTICE, "Ignoring ${SIP_CODEC*} variable because it is not shared by both ends: %s\n", codec);
  6318. }
  6319. ao2_ref(fmt, -1);
  6320. }
  6321. ao2_ref(original_jointcaps, -1);
  6322. return;
  6323. }
  6324. /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
  6325. * Part of PBX interface */
  6326. static int sip_answer(struct ast_channel *ast)
  6327. {
  6328. int res = 0;
  6329. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6330. int oldsdp = FALSE;
  6331. if (!p) {
  6332. ast_debug(1, "Asked to answer channel %s without tech pvt; ignoring\n",
  6333. ast_channel_name(ast));
  6334. return res;
  6335. }
  6336. sip_pvt_lock(p);
  6337. if (ast_channel_state(ast) != AST_STATE_UP) {
  6338. try_suggested_sip_codec(p);
  6339. if (ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
  6340. oldsdp = TRUE;
  6341. }
  6342. ast_setstate(ast, AST_STATE_UP);
  6343. ast_debug(1, "SIP answering channel: %s\n", ast_channel_name(ast));
  6344. ast_rtp_instance_update_source(p->rtp);
  6345. res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, oldsdp, TRUE);
  6346. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  6347. /* RFC says the session timer starts counting on 200,
  6348. * not on INVITE. */
  6349. if (p->stimer->st_active == TRUE) {
  6350. start_session_timer(p);
  6351. }
  6352. }
  6353. sip_pvt_unlock(p);
  6354. return res;
  6355. }
  6356. /*! \brief Send frame to media channel (rtp) */
  6357. static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
  6358. {
  6359. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6360. int res = 0;
  6361. switch (frame->frametype) {
  6362. case AST_FRAME_VOICE:
  6363. if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
  6364. struct ast_str *codec_buf = ast_str_alloca(64);
  6365. ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
  6366. ast_format_get_name(frame->subclass.format),
  6367. ast_format_cap_get_names(ast_channel_nativeformats(ast), &codec_buf),
  6368. ast_format_get_name(ast_channel_readformat(ast)),
  6369. ast_format_get_name(ast_channel_writeformat(ast)));
  6370. return 0;
  6371. }
  6372. if (p) {
  6373. sip_pvt_lock(p);
  6374. if (p->t38.state == T38_ENABLED) {
  6375. /* drop frame, can't sent VOICE frames while in T.38 mode */
  6376. sip_pvt_unlock(p);
  6377. break;
  6378. } else if (p->rtp) {
  6379. /* If channel is not up, activate early media session */
  6380. if ((ast_channel_state(ast) != AST_STATE_UP) &&
  6381. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6382. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6383. ast_rtp_instance_update_source(p->rtp);
  6384. if (!global_prematuremediafilter) {
  6385. p->invitestate = INV_EARLY_MEDIA;
  6386. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6387. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6388. }
  6389. }
  6390. if (p->invitestate > INV_EARLY_MEDIA || (p->invitestate == INV_EARLY_MEDIA &&
  6391. ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT))) {
  6392. p->lastrtptx = time(NULL);
  6393. res = ast_rtp_instance_write(p->rtp, frame);
  6394. }
  6395. }
  6396. sip_pvt_unlock(p);
  6397. }
  6398. break;
  6399. case AST_FRAME_VIDEO:
  6400. if (p) {
  6401. sip_pvt_lock(p);
  6402. if (p->vrtp) {
  6403. /* Activate video early media */
  6404. if ((ast_channel_state(ast) != AST_STATE_UP) &&
  6405. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6406. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6407. p->invitestate = INV_EARLY_MEDIA;
  6408. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6409. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6410. }
  6411. if (p->invitestate > INV_EARLY_MEDIA || (p->invitestate == INV_EARLY_MEDIA &&
  6412. ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT))) {
  6413. p->lastrtptx = time(NULL);
  6414. res = ast_rtp_instance_write(p->vrtp, frame);
  6415. }
  6416. }
  6417. sip_pvt_unlock(p);
  6418. }
  6419. break;
  6420. case AST_FRAME_TEXT:
  6421. if (p) {
  6422. sip_pvt_lock(p);
  6423. if (p->red) {
  6424. ast_rtp_red_buffer(p->trtp, frame);
  6425. } else {
  6426. if (p->trtp) {
  6427. /* Activate text early media */
  6428. if ((ast_channel_state(ast) != AST_STATE_UP) &&
  6429. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6430. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6431. p->invitestate = INV_EARLY_MEDIA;
  6432. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6433. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6434. }
  6435. if (p->invitestate > INV_EARLY_MEDIA || (p->invitestate == INV_EARLY_MEDIA &&
  6436. ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT))) {
  6437. p->lastrtptx = time(NULL);
  6438. res = ast_rtp_instance_write(p->trtp, frame);
  6439. }
  6440. }
  6441. }
  6442. sip_pvt_unlock(p);
  6443. }
  6444. break;
  6445. case AST_FRAME_IMAGE:
  6446. return 0;
  6447. break;
  6448. case AST_FRAME_MODEM:
  6449. if (p) {
  6450. sip_pvt_lock(p);
  6451. /* UDPTL requires two-way communication, so early media is not needed here.
  6452. we simply forget the frames if we get modem frames before the bridge is up.
  6453. Fax will re-transmit.
  6454. */
  6455. if ((ast_channel_state(ast) == AST_STATE_UP) &&
  6456. p->udptl &&
  6457. (p->t38.state == T38_ENABLED)) {
  6458. res = ast_udptl_write(p->udptl, frame);
  6459. }
  6460. sip_pvt_unlock(p);
  6461. }
  6462. break;
  6463. default:
  6464. ast_log(LOG_WARNING, "Can't send %u type frames with SIP write\n", frame->frametype);
  6465. return 0;
  6466. }
  6467. return res;
  6468. }
  6469. /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
  6470. Basically update any ->owner links */
  6471. static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
  6472. {
  6473. int ret = -1;
  6474. struct sip_pvt *p;
  6475. if (newchan && ast_test_flag(ast_channel_flags(newchan), AST_FLAG_ZOMBIE))
  6476. ast_debug(1, "New channel is zombie\n");
  6477. if (oldchan && ast_test_flag(ast_channel_flags(oldchan), AST_FLAG_ZOMBIE))
  6478. ast_debug(1, "Old channel is zombie\n");
  6479. if (!newchan || !ast_channel_tech_pvt(newchan)) {
  6480. if (!newchan)
  6481. ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", ast_channel_name(oldchan));
  6482. else
  6483. ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", ast_channel_name(oldchan));
  6484. return -1;
  6485. }
  6486. p = ast_channel_tech_pvt(newchan);
  6487. sip_pvt_lock(p);
  6488. append_history(p, "Masq", "Old channel: %s\n", ast_channel_name(oldchan));
  6489. append_history(p, "Masq (cont)", "...new owner: %s\n", ast_channel_name(newchan));
  6490. if (p->owner != oldchan)
  6491. ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
  6492. else {
  6493. sip_set_owner(p, newchan);
  6494. /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
  6495. RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
  6496. able to do this if the masquerade happens before the bridge breaks (e.g., AMI
  6497. redirect of both channels). Note that a channel can not be masqueraded *into*
  6498. a native bridge. So there is no danger that this breaks a native bridge that
  6499. should stay up. */
  6500. sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
  6501. ret = 0;
  6502. }
  6503. ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, ast_channel_name(p->owner), ast_channel_name(oldchan));
  6504. sip_pvt_unlock(p);
  6505. return ret;
  6506. }
  6507. static int sip_senddigit_begin(struct ast_channel *ast, char digit)
  6508. {
  6509. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6510. int res = 0;
  6511. if (!p) {
  6512. ast_debug(1, "Asked to begin DTMF digit on channel %s with no pvt; ignoring\n",
  6513. ast_channel_name(ast));
  6514. return res;
  6515. }
  6516. sip_pvt_lock(p);
  6517. switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
  6518. case SIP_DTMF_INBAND:
  6519. res = -1; /* Tell Asterisk to generate inband indications */
  6520. break;
  6521. case SIP_DTMF_RFC2833:
  6522. if (p->rtp)
  6523. ast_rtp_instance_dtmf_begin(p->rtp, digit);
  6524. break;
  6525. default:
  6526. break;
  6527. }
  6528. sip_pvt_unlock(p);
  6529. return res;
  6530. }
  6531. /*! \brief Send DTMF character on SIP channel
  6532. within one call, we're able to transmit in many methods simultaneously */
  6533. static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
  6534. {
  6535. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6536. int res = 0;
  6537. if (!p) {
  6538. ast_debug(1, "Asked to end DTMF digit on channel %s with no pvt; ignoring\n",
  6539. ast_channel_name(ast));
  6540. return res;
  6541. }
  6542. sip_pvt_lock(p);
  6543. switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
  6544. case SIP_DTMF_INFO:
  6545. case SIP_DTMF_SHORTINFO:
  6546. transmit_info_with_digit(p, digit, duration);
  6547. break;
  6548. case SIP_DTMF_RFC2833:
  6549. if (p->rtp)
  6550. ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
  6551. break;
  6552. case SIP_DTMF_INBAND:
  6553. res = -1; /* Tell Asterisk to stop inband indications */
  6554. break;
  6555. }
  6556. sip_pvt_unlock(p);
  6557. return res;
  6558. }
  6559. /*! \brief Transfer SIP call */
  6560. static int sip_transfer(struct ast_channel *ast, const char *dest)
  6561. {
  6562. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6563. int res;
  6564. if (!p) {
  6565. ast_debug(1, "Asked to transfer channel %s with no pvt; ignoring\n",
  6566. ast_channel_name(ast));
  6567. return -1;
  6568. }
  6569. if (dest == NULL) /* functions below do not take a NULL */
  6570. dest = "";
  6571. sip_pvt_lock(p);
  6572. if (ast_channel_state(ast) == AST_STATE_RING)
  6573. res = sip_sipredirect(p, dest);
  6574. else
  6575. res = transmit_refer(p, dest);
  6576. sip_pvt_unlock(p);
  6577. return res;
  6578. }
  6579. /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
  6580. static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
  6581. {
  6582. int res = 0;
  6583. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
  6584. return -1;
  6585. }
  6586. switch (parameters->request_response) {
  6587. case AST_T38_NEGOTIATED:
  6588. case AST_T38_REQUEST_NEGOTIATE: /* Request T38 */
  6589. /* Negotiation can not take place without a valid max_ifp value. */
  6590. if (!parameters->max_ifp) {
  6591. if (p->t38.state == T38_PEER_REINVITE) {
  6592. AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
  6593. transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
  6594. }
  6595. change_t38_state(p, T38_REJECTED);
  6596. break;
  6597. } else if (p->t38.state == T38_PEER_REINVITE) {
  6598. AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
  6599. p->t38.our_parms = *parameters;
  6600. /* modify our parameters to conform to the peer's parameters,
  6601. * based on the rules in the ITU T.38 recommendation
  6602. */
  6603. if (!p->t38.their_parms.fill_bit_removal) {
  6604. p->t38.our_parms.fill_bit_removal = FALSE;
  6605. }
  6606. if (!p->t38.their_parms.transcoding_mmr) {
  6607. p->t38.our_parms.transcoding_mmr = FALSE;
  6608. }
  6609. if (!p->t38.their_parms.transcoding_jbig) {
  6610. p->t38.our_parms.transcoding_jbig = FALSE;
  6611. }
  6612. p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
  6613. p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
  6614. ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
  6615. change_t38_state(p, T38_ENABLED);
  6616. transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
  6617. } else if (p->t38.state != T38_ENABLED) {
  6618. p->t38.our_parms = *parameters;
  6619. ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
  6620. change_t38_state(p, T38_LOCAL_REINVITE);
  6621. if (!p->pendinginvite) {
  6622. transmit_reinvite_with_sdp(p, TRUE, FALSE);
  6623. } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  6624. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  6625. }
  6626. }
  6627. break;
  6628. case AST_T38_TERMINATED:
  6629. case AST_T38_REFUSED:
  6630. case AST_T38_REQUEST_TERMINATE: /* Shutdown T38 */
  6631. if (p->t38.state == T38_PEER_REINVITE) {
  6632. AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
  6633. change_t38_state(p, T38_REJECTED);
  6634. transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
  6635. } else if (p->t38.state == T38_ENABLED)
  6636. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  6637. break;
  6638. case AST_T38_REQUEST_PARMS: { /* Application wants remote's parameters re-sent */
  6639. struct ast_control_t38_parameters parameters = p->t38.their_parms;
  6640. if (p->t38.state == T38_PEER_REINVITE) {
  6641. AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
  6642. parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
  6643. parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
  6644. if (p->owner) {
  6645. ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
  6646. }
  6647. /* we need to return a positive value here, so that applications that
  6648. * send this request can determine conclusively whether it was accepted or not...
  6649. * older versions of chan_sip would just silently accept it and return zero.
  6650. */
  6651. res = AST_T38_REQUEST_PARMS;
  6652. }
  6653. break;
  6654. }
  6655. default:
  6656. res = -1;
  6657. break;
  6658. }
  6659. return res;
  6660. }
  6661. /*!
  6662. * \internal
  6663. * \brief Create and initialize UDPTL for the specified dialog
  6664. *
  6665. * \param p SIP private structure to create UDPTL object for
  6666. * \pre p is locked
  6667. * \pre p->owner is locked
  6668. *
  6669. * \note In the case of failure, SIP_PAGE2_T38SUPPORT is cleared on p
  6670. *
  6671. * \return 0 on success, any other value on failure
  6672. */
  6673. static int initialize_udptl(struct sip_pvt *p)
  6674. {
  6675. int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
  6676. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
  6677. return 1;
  6678. }
  6679. /* If we've already initialized T38, don't take any further action */
  6680. if (p->udptl) {
  6681. return 0;
  6682. }
  6683. /* T38 can be supported by this dialog, create it and set the derived properties */
  6684. if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
  6685. if (p->owner) {
  6686. ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
  6687. }
  6688. ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
  6689. p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
  6690. set_t38_capabilities(p);
  6691. ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
  6692. ast_udptl_setnat(p->udptl, natflags);
  6693. } else {
  6694. ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
  6695. ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
  6696. return 1;
  6697. }
  6698. return 0;
  6699. }
  6700. static int sipinfo_send(
  6701. struct ast_channel *chan,
  6702. struct ast_variable *headers,
  6703. const char *content_type,
  6704. const char *content,
  6705. const char *useragent_filter)
  6706. {
  6707. struct sip_pvt *p;
  6708. struct ast_variable *var;
  6709. struct sip_request req;
  6710. int res = -1;
  6711. ast_channel_lock(chan);
  6712. if (ast_channel_tech(chan) != &sip_tech) {
  6713. ast_log(LOG_WARNING, "Attempted to send a custom INFO on a non-SIP channel %s\n", ast_channel_name(chan));
  6714. ast_channel_unlock(chan);
  6715. return res;
  6716. }
  6717. p = ast_channel_tech_pvt(chan);
  6718. sip_pvt_lock(p);
  6719. if (!(ast_strlen_zero(useragent_filter))) {
  6720. int match = (strstr(p->useragent, useragent_filter)) ? 1 : 0;
  6721. if (!match) {
  6722. goto cleanup;
  6723. }
  6724. }
  6725. reqprep(&req, p, SIP_INFO, 0, 1);
  6726. for (var = headers; var; var = var->next) {
  6727. add_header(&req, var->name, var->value);
  6728. }
  6729. if (!ast_strlen_zero(content) && !ast_strlen_zero(content_type)) {
  6730. add_header(&req, "Content-Type", content_type);
  6731. add_content(&req, content);
  6732. }
  6733. res = send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  6734. cleanup:
  6735. sip_pvt_unlock(p);
  6736. ast_channel_unlock(chan);
  6737. return res;
  6738. }
  6739. /*! \brief Play indication to user
  6740. * With SIP a lot of indications is sent as messages, letting the device play
  6741. the indication - busy signal, congestion etc
  6742. \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
  6743. */
  6744. static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
  6745. {
  6746. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6747. int res = 0;
  6748. if (!p) {
  6749. ast_debug(1, "Asked to indicate condition on channel %s with no pvt; ignoring\n",
  6750. ast_channel_name(ast));
  6751. return res;
  6752. }
  6753. sip_pvt_lock(p);
  6754. switch(condition) {
  6755. case AST_CONTROL_RINGING:
  6756. if (ast_channel_state(ast) == AST_STATE_RING) {
  6757. p->invitestate = INV_EARLY_MEDIA;
  6758. if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
  6759. (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
  6760. /* Send 180 ringing if out-of-band seems reasonable */
  6761. transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
  6762. ast_set_flag(&p->flags[0], SIP_RINGING);
  6763. if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
  6764. break;
  6765. } else {
  6766. /* Well, if it's not reasonable, just send in-band */
  6767. }
  6768. }
  6769. res = -1;
  6770. break;
  6771. case AST_CONTROL_BUSY:
  6772. if (ast_channel_state(ast) != AST_STATE_UP) {
  6773. transmit_response_reliable(p, "486 Busy Here", &p->initreq);
  6774. p->invitestate = INV_COMPLETED;
  6775. sip_alreadygone(p);
  6776. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6777. break;
  6778. }
  6779. res = -1;
  6780. break;
  6781. case AST_CONTROL_CONGESTION:
  6782. if (ast_channel_state(ast) != AST_STATE_UP) {
  6783. transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
  6784. p->invitestate = INV_COMPLETED;
  6785. sip_alreadygone(p);
  6786. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6787. break;
  6788. }
  6789. res = -1;
  6790. break;
  6791. case AST_CONTROL_INCOMPLETE:
  6792. if (ast_channel_state(ast) != AST_STATE_UP) {
  6793. switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
  6794. case SIP_PAGE2_ALLOWOVERLAP_YES:
  6795. transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
  6796. p->invitestate = INV_COMPLETED;
  6797. sip_alreadygone(p);
  6798. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6799. break;
  6800. case SIP_PAGE2_ALLOWOVERLAP_DTMF:
  6801. /* Just wait for inband DTMF digits */
  6802. break;
  6803. default:
  6804. /* it actually means no support for overlap */
  6805. transmit_response_reliable(p, "404 Not Found", &p->initreq);
  6806. p->invitestate = INV_COMPLETED;
  6807. sip_alreadygone(p);
  6808. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6809. break;
  6810. }
  6811. }
  6812. break;
  6813. case AST_CONTROL_PROCEEDING:
  6814. if ((ast_channel_state(ast) != AST_STATE_UP) &&
  6815. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6816. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6817. transmit_response(p, "100 Trying", &p->initreq);
  6818. p->invitestate = INV_PROCEEDING;
  6819. break;
  6820. }
  6821. res = -1;
  6822. break;
  6823. case AST_CONTROL_PROGRESS:
  6824. if ((ast_channel_state(ast) != AST_STATE_UP) &&
  6825. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6826. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6827. p->invitestate = INV_EARLY_MEDIA;
  6828. /* SIP_PROG_INBAND_NEVER means sending 180 ringing in place of a 183 */
  6829. if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_NEVER) {
  6830. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6831. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6832. } else if (ast_channel_state(ast) == AST_STATE_RING && !ast_test_flag(&p->flags[0], SIP_RINGING)) {
  6833. transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
  6834. ast_set_flag(&p->flags[0], SIP_RINGING);
  6835. }
  6836. break;
  6837. }
  6838. res = -1;
  6839. break;
  6840. case AST_CONTROL_HOLD:
  6841. ast_rtp_instance_update_source(p->rtp);
  6842. ast_moh_start(ast, data, p->mohinterpret);
  6843. break;
  6844. case AST_CONTROL_UNHOLD:
  6845. ast_rtp_instance_update_source(p->rtp);
  6846. ast_moh_stop(ast);
  6847. break;
  6848. case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
  6849. if (p->vrtp && !p->novideo) {
  6850. /* FIXME: Only use this for VP8. Additional work would have to be done to
  6851. * fully support other video codecs */
  6852. if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL) {
  6853. /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
  6854. * RTP engine would provide a way to externally write/schedule RTCP
  6855. * packets */
  6856. struct ast_frame fr;
  6857. fr.frametype = AST_FRAME_CONTROL;
  6858. fr.subclass.integer = AST_CONTROL_VIDUPDATE;
  6859. res = ast_rtp_instance_write(p->vrtp, &fr);
  6860. } else {
  6861. transmit_info_with_vidupdate(p);
  6862. }
  6863. } else {
  6864. res = -1;
  6865. }
  6866. break;
  6867. case AST_CONTROL_T38_PARAMETERS:
  6868. res = -1;
  6869. if (datalen != sizeof(struct ast_control_t38_parameters)) {
  6870. ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38_PARAMETERS. Expected %d, got %d\n", (int) sizeof(struct ast_control_t38_parameters), (int) datalen);
  6871. } else {
  6872. const struct ast_control_t38_parameters *parameters = data;
  6873. if (!initialize_udptl(p)) {
  6874. res = interpret_t38_parameters(p, parameters);
  6875. }
  6876. }
  6877. break;
  6878. case AST_CONTROL_SRCUPDATE:
  6879. ast_rtp_instance_update_source(p->rtp);
  6880. break;
  6881. case AST_CONTROL_SRCCHANGE:
  6882. ast_rtp_instance_change_source(p->rtp);
  6883. break;
  6884. case AST_CONTROL_CONNECTED_LINE:
  6885. update_connectedline(p, data, datalen);
  6886. break;
  6887. case AST_CONTROL_REDIRECTING:
  6888. update_redirecting(p, data, datalen);
  6889. break;
  6890. case AST_CONTROL_AOC:
  6891. {
  6892. struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
  6893. if (!decoded) {
  6894. ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
  6895. res = -1;
  6896. break;
  6897. }
  6898. switch (ast_aoc_get_msg_type(decoded)) {
  6899. case AST_AOC_REQUEST:
  6900. if (ast_aoc_get_termination_request(decoded)) {
  6901. /* TODO, once there is a way to get AOC-E on hangup, attempt that here
  6902. * before hanging up the channel.*/
  6903. /* The other side has already initiated the hangup. This frame
  6904. * just says they are waiting to get AOC-E before completely tearing
  6905. * the call down. Since SIP does not support this at the moment go
  6906. * ahead and terminate the call here to avoid an unnecessary timeout. */
  6907. ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", ast_channel_name(p->owner));
  6908. ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
  6909. }
  6910. break;
  6911. case AST_AOC_D:
  6912. case AST_AOC_E:
  6913. if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
  6914. transmit_info_with_aoc(p, decoded);
  6915. }
  6916. break;
  6917. case AST_AOC_S: /* S not supported yet */
  6918. default:
  6919. break;
  6920. }
  6921. ast_aoc_destroy_decoded(decoded);
  6922. }
  6923. break;
  6924. case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
  6925. break;
  6926. case AST_CONTROL_FLASH: /* We don't currently handle AST_CONTROL_FLASH here, but it is expected, so we don't need to warn either. */
  6927. res = -1;
  6928. break;
  6929. case AST_CONTROL_PVT_CAUSE_CODE: /* these should be handled by the code in channel.c */
  6930. case AST_CONTROL_MASQUERADE_NOTIFY:
  6931. case -1:
  6932. res = -1;
  6933. break;
  6934. default:
  6935. ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
  6936. res = -1;
  6937. break;
  6938. }
  6939. sip_pvt_unlock(p);
  6940. return res;
  6941. }
  6942. /*!
  6943. * \brief Initiate a call in the SIP channel
  6944. *
  6945. * \note called from sip_request_call (calls from the pbx ) for
  6946. * outbound channels and from handle_request_invite for inbound
  6947. * channels
  6948. *
  6949. * \pre i is locked
  6950. *
  6951. * \return New ast_channel locked.
  6952. */
  6953. static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, ast_callid callid)
  6954. {
  6955. struct ast_format_cap *caps;
  6956. struct ast_channel *tmp;
  6957. struct ast_variable *v = NULL;
  6958. struct ast_format *fmt;
  6959. struct ast_format_cap *what = NULL; /* SHALLOW COPY DO NOT DESTROY! */
  6960. struct ast_str *codec_buf = ast_str_alloca(64);
  6961. int needvideo = 0;
  6962. int needtext = 0;
  6963. char *exten;
  6964. caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  6965. if (!caps) {
  6966. return NULL;
  6967. }
  6968. {
  6969. const char *my_name; /* pick a good name */
  6970. if (title) {
  6971. my_name = title;
  6972. } else {
  6973. my_name = ast_strdupa(i->fromdomain);
  6974. }
  6975. /* Don't hold a sip pvt lock while we allocate a channel */
  6976. sip_pvt_unlock(i);
  6977. if (i->relatedpeer && i->relatedpeer->endpoint) {
  6978. tmp = ast_channel_alloc_with_endpoint(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, assignedids, requestor, i->amaflags, i->relatedpeer->endpoint, "SIP/%s-%08x", my_name, (unsigned)ast_atomic_fetchadd_int((int *)&chan_idx, +1));
  6979. } else {
  6980. tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, assignedids, requestor, i->amaflags, "SIP/%s-%08x", my_name, (unsigned)ast_atomic_fetchadd_int((int *)&chan_idx, +1));
  6981. }
  6982. }
  6983. if (!tmp) {
  6984. ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
  6985. ao2_ref(caps, -1);
  6986. sip_pvt_lock(i);
  6987. return NULL;
  6988. }
  6989. ast_channel_stage_snapshot(tmp);
  6990. /* If we sent in a callid, bind it to the channel. */
  6991. if (callid) {
  6992. ast_channel_callid_set(tmp, callid);
  6993. }
  6994. sip_pvt_lock(i);
  6995. ast_channel_cc_params_init(tmp, i->cc_params);
  6996. ast_channel_caller(tmp)->id.tag = ast_strdup(i->cid_tag);
  6997. ast_channel_tech_set(tmp, (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO || ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO) ? &sip_tech_info : &sip_tech);
  6998. /* Select our native format based on codec preference until we receive
  6999. something from another device to the contrary. */
  7000. if (ast_format_cap_count(i->jointcaps)) { /* The joint capabilities of us and peer */
  7001. what = i->jointcaps;
  7002. } else if (ast_format_cap_count(i->caps)) { /* Our configured capability for this peer */
  7003. what = i->caps;
  7004. } else {
  7005. what = sip_cfg.caps;
  7006. }
  7007. /* Set the native formats */
  7008. ast_format_cap_append_from_cap(caps, what, AST_MEDIA_TYPE_UNKNOWN);
  7009. /* Use only the preferred audio format, which is stored at the '0' index */
  7010. fmt = ast_format_cap_get_best_by_type(what, AST_MEDIA_TYPE_AUDIO); /* get the best audio format */
  7011. if (fmt) {
  7012. ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_AUDIO); /* remove only the other audio formats */
  7013. ast_format_cap_append(caps, fmt, 0); /* add our best choice back */
  7014. } else {
  7015. /* If we don't have an audio format, try to get something */
  7016. fmt = ast_format_cap_get_format(caps, 0);
  7017. if (!fmt) {
  7018. ast_log(LOG_WARNING, "No compatible formats could be found for %s\n", ast_channel_name(tmp));
  7019. ao2_ref(caps, -1);
  7020. tmp = ast_channel_unref(tmp);
  7021. return NULL;
  7022. }
  7023. }
  7024. ast_channel_nativeformats_set(tmp, caps);
  7025. ao2_ref(caps, -1);
  7026. ast_debug(3, "*** Our native formats are %s \n", ast_format_cap_get_names(ast_channel_nativeformats(tmp), &codec_buf));
  7027. ast_debug(3, "*** Joint capabilities are %s \n", ast_format_cap_get_names(i->jointcaps, &codec_buf));
  7028. ast_debug(3, "*** Our capabilities are %s \n", ast_format_cap_get_names(i->caps, &codec_buf));
  7029. ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_format_get_name(fmt));
  7030. if (ast_format_cap_count(i->prefcaps)) {
  7031. ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_format_cap_get_names(i->prefcaps, &codec_buf));
  7032. }
  7033. /* If we have a prefcodec setting, we have an inbound channel that set a
  7034. preferred format for this call. Otherwise, we check the jointcapability
  7035. We also check for vrtp. If it's not there, we are not allowed do any video anyway.
  7036. */
  7037. if (i->vrtp) {
  7038. if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
  7039. needvideo = 1;
  7040. else if (ast_format_cap_count(i->prefcaps))
  7041. needvideo = ast_format_cap_has_type(i->prefcaps, AST_MEDIA_TYPE_VIDEO); /* Outbound call */
  7042. else
  7043. needvideo = ast_format_cap_has_type(i->jointcaps, AST_MEDIA_TYPE_VIDEO); /* Inbound call */
  7044. }
  7045. if (i->trtp) {
  7046. if (ast_format_cap_count(i->prefcaps))
  7047. needtext = ast_format_cap_has_type(i->prefcaps, AST_MEDIA_TYPE_TEXT); /* Outbound call */
  7048. else
  7049. needtext = ast_format_cap_has_type(i->jointcaps, AST_MEDIA_TYPE_TEXT); /* Inbound call */
  7050. }
  7051. if (needvideo) {
  7052. ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
  7053. } else {
  7054. ast_debug(3, "This channel will not be able to handle video.\n");
  7055. }
  7056. enable_dsp_detect(i);
  7057. if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  7058. (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  7059. if (i->rtp) {
  7060. ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
  7061. }
  7062. } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
  7063. if (i->rtp) {
  7064. ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
  7065. }
  7066. }
  7067. /* Set file descriptors for audio, video, and realtime text. Since
  7068. * UDPTL is created as needed in the lifetime of a dialog, its file
  7069. * descriptor is set in initialize_udptl */
  7070. if (i->rtp) {
  7071. ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
  7072. ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
  7073. ast_rtp_instance_set_write_format(i->rtp, fmt);
  7074. ast_rtp_instance_set_read_format(i->rtp, fmt);
  7075. }
  7076. if (needvideo && i->vrtp) {
  7077. ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
  7078. ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
  7079. }
  7080. if (needtext && i->trtp) {
  7081. ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
  7082. }
  7083. if (i->udptl) {
  7084. ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
  7085. }
  7086. if (state == AST_STATE_RING) {
  7087. ast_channel_rings_set(tmp, 1);
  7088. }
  7089. ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
  7090. ast_channel_set_writeformat(tmp, fmt);
  7091. ast_channel_set_rawwriteformat(tmp, fmt);
  7092. ast_channel_set_readformat(tmp, fmt);
  7093. ast_channel_set_rawreadformat(tmp, fmt);
  7094. ao2_ref(fmt, -1);
  7095. ast_channel_tech_pvt_set(tmp, dialog_ref(i, "sip_new: set chan->tech_pvt to i"));
  7096. ast_channel_callgroup_set(tmp, i->callgroup);
  7097. ast_channel_pickupgroup_set(tmp, i->pickupgroup);
  7098. ast_channel_named_callgroups_set(tmp, i->named_callgroups);
  7099. ast_channel_named_pickupgroups_set(tmp, i->named_pickupgroups);
  7100. ast_channel_caller(tmp)->id.name.presentation = i->callingpres;
  7101. ast_channel_caller(tmp)->id.number.presentation = i->callingpres;
  7102. if (!ast_strlen_zero(i->parkinglot)) {
  7103. ast_channel_parkinglot_set(tmp, i->parkinglot);
  7104. }
  7105. if (!ast_strlen_zero(i->accountcode)) {
  7106. ast_channel_accountcode_set(tmp, i->accountcode);
  7107. }
  7108. if (i->amaflags) {
  7109. ast_channel_amaflags_set(tmp, i->amaflags);
  7110. }
  7111. if (!ast_strlen_zero(i->language)) {
  7112. ast_channel_language_set(tmp, i->language);
  7113. }
  7114. if (!ast_strlen_zero(i->zone)) {
  7115. struct ast_tone_zone *zone;
  7116. if (!(zone = ast_get_indication_zone(i->zone))) {
  7117. ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", i->zone);
  7118. }
  7119. ast_channel_zone_set(tmp, zone);
  7120. }
  7121. sip_set_owner(i, tmp);
  7122. ast_module_ref(ast_module_info->self);
  7123. ast_channel_context_set(tmp, i->context);
  7124. /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
  7125. * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
  7126. * structure so that there aren't issues when forming URI's
  7127. */
  7128. exten = ast_strdupa(i->exten);
  7129. sip_pvt_unlock(i);
  7130. ast_channel_unlock(tmp);
  7131. if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
  7132. ast_uri_decode(exten, ast_uri_sip_user);
  7133. }
  7134. ast_channel_lock(tmp);
  7135. sip_pvt_lock(i);
  7136. ast_channel_exten_set(tmp, exten);
  7137. /* Don't use ast_set_callerid() here because it will
  7138. * generate an unnecessary NewCallerID event */
  7139. if (!ast_strlen_zero(i->cid_num)) {
  7140. ast_channel_caller(tmp)->ani.number.valid = 1;
  7141. ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
  7142. }
  7143. if (!ast_strlen_zero(i->rdnis)) {
  7144. ast_channel_redirecting(tmp)->from.number.valid = 1;
  7145. ast_channel_redirecting(tmp)->from.number.str = ast_strdup(i->rdnis);
  7146. }
  7147. if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
  7148. ast_channel_dialed(tmp)->number.str = ast_strdup(i->exten);
  7149. }
  7150. ast_channel_priority_set(tmp, 1);
  7151. if (!ast_strlen_zero(i->uri)) {
  7152. pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
  7153. }
  7154. if (!ast_strlen_zero(i->domain)) {
  7155. pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
  7156. }
  7157. if (!ast_strlen_zero(i->tel_phone_context)) {
  7158. pbx_builtin_setvar_helper(tmp, "SIPURIPHONECONTEXT", i->tel_phone_context);
  7159. }
  7160. if (!ast_strlen_zero(i->callid)) {
  7161. pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
  7162. }
  7163. if (i->rtp) {
  7164. ast_jb_configure(tmp, &global_jbconf);
  7165. }
  7166. if (!i->relatedpeer) {
  7167. ast_set_flag(ast_channel_flags(tmp), AST_FLAG_DISABLE_DEVSTATE_CACHE);
  7168. }
  7169. /* Set channel variables for this call from configuration */
  7170. for (v = i->chanvars ; v ; v = v->next) {
  7171. char valuebuf[1024];
  7172. pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
  7173. }
  7174. if (i->do_history) {
  7175. append_history(i, "NewChan", "Channel %s - from %s", ast_channel_name(tmp), i->callid);
  7176. }
  7177. ast_channel_stage_snapshot_done(tmp);
  7178. return tmp;
  7179. }
  7180. /*! \brief Lookup 'name' in the SDP starting
  7181. * at the 'start' line. Returns the matching line, and 'start'
  7182. * is updated with the next line number.
  7183. */
  7184. static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
  7185. {
  7186. int len = strlen(name);
  7187. const char *line;
  7188. while (*start < (req->sdp_start + req->sdp_count)) {
  7189. line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
  7190. if (!strncasecmp(line, name, len) && line[len] == '=') {
  7191. return ast_skip_blanks(line + len + 1);
  7192. }
  7193. }
  7194. /* if the line was not found, ensure that *start points past the SDP */
  7195. (*start)++;
  7196. return "";
  7197. }
  7198. /*! \brief Fetches the next valid SDP line between the 'start' line
  7199. * (inclusive) and the 'stop' line (exclusive). Returns the type
  7200. * ('a', 'c', ...) and matching line in reference 'start' is updated
  7201. * with the next line number.
  7202. */
  7203. static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
  7204. {
  7205. char type = '\0';
  7206. const char *line = NULL;
  7207. if (stop > (req->sdp_start + req->sdp_count)) {
  7208. stop = req->sdp_start + req->sdp_count;
  7209. }
  7210. while (*start < stop) {
  7211. line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
  7212. if (line[1] == '=') {
  7213. type = line[0];
  7214. *value = ast_skip_blanks(line + 2);
  7215. break;
  7216. }
  7217. }
  7218. return type;
  7219. }
  7220. /*! \brief Get a specific line from the message content */
  7221. static char *get_content_line(struct sip_request *req, char *name, char delimiter)
  7222. {
  7223. int i;
  7224. int len = strlen(name);
  7225. const char *line;
  7226. for (i = 0; i < req->lines; i++) {
  7227. line = REQ_OFFSET_TO_STR(req, line[i]);
  7228. if (!strncasecmp(line, name, len) && line[len] == delimiter) {
  7229. return ast_skip_blanks(line + len + 1);
  7230. }
  7231. }
  7232. return "";
  7233. }
  7234. /*! \brief Structure for conversion between compressed SIP and "normal" SIP headers */
  7235. struct cfalias {
  7236. const char *fullname;
  7237. const char *shortname;
  7238. };
  7239. static const struct cfalias aliases[] = {
  7240. { "Content-Type", "c" },
  7241. { "Content-Encoding", "e" },
  7242. { "From", "f" },
  7243. { "Call-ID", "i" },
  7244. { "Contact", "m" },
  7245. { "Content-Length", "l" },
  7246. { "Subject", "s" },
  7247. { "To", "t" },
  7248. { "Supported", "k" },
  7249. { "Refer-To", "r" },
  7250. { "Referred-By", "b" },
  7251. { "Allow-Events", "u" },
  7252. { "Event", "o" },
  7253. { "Via", "v" },
  7254. { "Accept-Contact", "a" },
  7255. { "Reject-Contact", "j" },
  7256. { "Request-Disposition", "d" },
  7257. { "Session-Expires", "x" },
  7258. { "Identity", "y" },
  7259. { "Identity-Info", "n" },
  7260. };
  7261. /*! \brief Find compressed SIP alias */
  7262. static const char *find_alias(const char *name, const char *_default)
  7263. {
  7264. int x;
  7265. for (x = 0; x < ARRAY_LEN(aliases); x++) {
  7266. if (!strcasecmp(aliases[x].fullname, name))
  7267. return aliases[x].shortname;
  7268. }
  7269. return _default;
  7270. }
  7271. /*! \brief Find full SIP alias */
  7272. static const char *find_full_alias(const char *name, const char *_default)
  7273. {
  7274. int x;
  7275. if (strlen(name) == 1) {
  7276. /* We have a short header name to convert. */
  7277. for (x = 0; x < ARRAY_LEN(aliases); ++x) {
  7278. if (!strcasecmp(aliases[x].shortname, name))
  7279. return aliases[x].fullname;
  7280. }
  7281. }
  7282. return _default;
  7283. }
  7284. static const char *__get_header(const struct sip_request *req, const char *name, int *start)
  7285. {
  7286. /*
  7287. * Technically you can place arbitrary whitespace both before and after the ':' in
  7288. * a header, although RFC3261 clearly says you shouldn't before, and place just
  7289. * one afterwards. If you shouldn't do it, what absolute idiot decided it was
  7290. * a good idea to say you can do it, and if you can do it, why in the hell would.
  7291. * you say you shouldn't.
  7292. * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
  7293. * and we always allow spaces after that for compatibility.
  7294. */
  7295. const char *sname = find_alias(name, NULL);
  7296. int x, len = strlen(name), slen = (sname ? 1 : 0);
  7297. for (x = *start; x < req->headers; x++) {
  7298. const char *header = REQ_OFFSET_TO_STR(req, header[x]);
  7299. int smatch = 0, match = !strncasecmp(header, name, len);
  7300. if (slen) {
  7301. smatch = !strncasecmp(header, sname, slen);
  7302. }
  7303. if (match || smatch) {
  7304. /* skip name */
  7305. const char *r = header + (match ? len : slen );
  7306. if (sip_cfg.pedanticsipchecking) {
  7307. r = ast_skip_blanks(r);
  7308. }
  7309. if (*r == ':') {
  7310. *start = x+1;
  7311. return ast_skip_blanks(r+1);
  7312. }
  7313. }
  7314. }
  7315. /* Don't return NULL, so sip_get_header is always a valid pointer */
  7316. return "";
  7317. }
  7318. /*! \brief Get header from SIP request
  7319. \return Always return something, so don't check for NULL because it won't happen :-)
  7320. */
  7321. const char *sip_get_header(const struct sip_request *req, const char *name)
  7322. {
  7323. int start = 0;
  7324. return __get_header(req, name, &start);
  7325. }
  7326. AST_THREADSTORAGE(sip_content_buf);
  7327. /*! \brief Get message body content */
  7328. static char *get_content(struct sip_request *req)
  7329. {
  7330. struct ast_str *str;
  7331. int i;
  7332. if (!(str = ast_str_thread_get(&sip_content_buf, 128))) {
  7333. return NULL;
  7334. }
  7335. ast_str_reset(str);
  7336. for (i = 0; i < req->lines; i++) {
  7337. if (ast_str_append(&str, 0, "%s\n", REQ_OFFSET_TO_STR(req, line[i])) < 0) {
  7338. return NULL;
  7339. }
  7340. }
  7341. return ast_str_buffer(str);
  7342. }
  7343. /*! \brief Read RTP from network */
  7344. static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
  7345. {
  7346. /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
  7347. struct ast_frame *f;
  7348. if (!p->rtp) {
  7349. /* We have no RTP allocated for this channel */
  7350. return &ast_null_frame;
  7351. }
  7352. switch(ast_channel_fdno(ast)) {
  7353. case 0:
  7354. f = ast_rtp_instance_read(p->rtp, 0); /* RTP Audio */
  7355. break;
  7356. case 1:
  7357. f = ast_rtp_instance_read(p->rtp, 1); /* RTCP Control Channel */
  7358. break;
  7359. case 2:
  7360. f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
  7361. break;
  7362. case 3:
  7363. f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
  7364. break;
  7365. case 4:
  7366. f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
  7367. if (sipdebug_text) {
  7368. struct ast_str *out = ast_str_create(f->datalen * 4 + 6);
  7369. int i;
  7370. unsigned char* arr = f->data.ptr;
  7371. do {
  7372. if (!out) {
  7373. break;
  7374. }
  7375. for (i = 0; i < f->datalen; i++) {
  7376. ast_str_append(&out, 0, "%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
  7377. }
  7378. ast_str_append(&out, 0, " -> ");
  7379. for (i = 0; i < f->datalen; i++) {
  7380. ast_str_append(&out, 0, "%02hhX ", arr[i]);
  7381. }
  7382. ast_verb(0, "%s\n", ast_str_buffer(out));
  7383. ast_free(out);
  7384. } while (0);
  7385. }
  7386. break;
  7387. case 5:
  7388. f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
  7389. break;
  7390. default:
  7391. f = &ast_null_frame;
  7392. }
  7393. /* Don't forward RFC2833 if we're not supposed to */
  7394. if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
  7395. (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
  7396. ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
  7397. ast_frfree(f);
  7398. return &ast_null_frame;
  7399. }
  7400. /* We already hold the channel lock */
  7401. if (!p->owner || (f && f->frametype != AST_FRAME_VOICE)) {
  7402. return f;
  7403. }
  7404. if (f && ast_format_cap_iscompatible_format(ast_channel_nativeformats(p->owner), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
  7405. struct ast_format_cap *caps;
  7406. if (ast_format_cap_iscompatible_format(p->jointcaps, f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
  7407. ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
  7408. ast_format_get_name(f->subclass.format), ast_channel_name(p->owner));
  7409. ast_frfree(f);
  7410. return &ast_null_frame;
  7411. }
  7412. ast_debug(1, "Oooh, format changed to %s\n",
  7413. ast_format_get_name(f->subclass.format));
  7414. caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7415. if (caps) {
  7416. ast_format_cap_append_from_cap(caps, ast_channel_nativeformats(p->owner), AST_MEDIA_TYPE_UNKNOWN);
  7417. ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_AUDIO);
  7418. ast_format_cap_append(caps, f->subclass.format, 0);
  7419. ast_channel_nativeformats_set(p->owner, caps);
  7420. ao2_ref(caps, -1);
  7421. }
  7422. ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
  7423. ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
  7424. }
  7425. if (f && p->dsp) {
  7426. f = ast_dsp_process(p->owner, p->dsp, f);
  7427. if (f && f->frametype == AST_FRAME_DTMF) {
  7428. if (f->subclass.integer == 'f') {
  7429. ast_debug(1, "Fax CNG detected on %s\n", ast_channel_name(ast));
  7430. *faxdetect = 1;
  7431. /* If we only needed this DSP for fax detection purposes we can just drop it now */
  7432. if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
  7433. ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
  7434. } else {
  7435. ast_dsp_free(p->dsp);
  7436. p->dsp = NULL;
  7437. }
  7438. } else {
  7439. ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
  7440. }
  7441. }
  7442. }
  7443. return f;
  7444. }
  7445. /*! \brief Read SIP RTP from channel */
  7446. static struct ast_frame *sip_read(struct ast_channel *ast)
  7447. {
  7448. struct ast_frame *fr;
  7449. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  7450. int faxdetected = FALSE;
  7451. sip_pvt_lock(p);
  7452. fr = sip_rtp_read(ast, p, &faxdetected);
  7453. p->lastrtprx = time(NULL);
  7454. /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
  7455. if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
  7456. if (strcmp(ast_channel_exten(ast), "fax")) {
  7457. const char *target_context = S_OR(ast_channel_macrocontext(ast), ast_channel_context(ast));
  7458. /* We need to unlock 'ast' here because
  7459. * ast_exists_extension has the potential to start and
  7460. * stop an autoservice on the channel. Such action is
  7461. * prone to deadlock if the channel is locked.
  7462. */
  7463. sip_pvt_unlock(p);
  7464. ast_channel_unlock(ast);
  7465. if (ast_exists_extension(ast, target_context, "fax", 1,
  7466. S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, NULL))) {
  7467. ast_channel_lock(ast);
  7468. sip_pvt_lock(p);
  7469. ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n", ast_channel_name(ast));
  7470. pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
  7471. if (ast_async_goto(ast, target_context, "fax", 1)) {
  7472. ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
  7473. }
  7474. ast_frfree(fr);
  7475. fr = &ast_null_frame;
  7476. } else {
  7477. ast_channel_lock(ast);
  7478. sip_pvt_lock(p);
  7479. ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
  7480. }
  7481. }
  7482. }
  7483. /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
  7484. if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast_channel_state(ast) != AST_STATE_UP) {
  7485. ast_frfree(fr);
  7486. fr = &ast_null_frame;
  7487. }
  7488. sip_pvt_unlock(p);
  7489. return fr;
  7490. }
  7491. /*! \brief Generate 32 byte random string for callid's etc */
  7492. static char *generate_random_string(char *buf, size_t size)
  7493. {
  7494. long val[4];
  7495. int x;
  7496. for (x=0; x<4; x++)
  7497. val[x] = ast_random();
  7498. snprintf(buf, size, "%08lx%08lx%08lx%08lx", (unsigned long)val[0], (unsigned long)val[1], (unsigned long)val[2], (unsigned long)val[3]);
  7499. return buf;
  7500. }
  7501. static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
  7502. {
  7503. struct ast_str *uri = ast_str_alloca(size);
  7504. ast_str_set(&uri, 0, "%s", pvt->socket.type == AST_TRANSPORT_TLS ? "sips:" : "sip:");
  7505. /* Here would be a great place to generate a UUID, but for now we'll
  7506. * use the handy random string generation function we already have
  7507. */
  7508. ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
  7509. ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
  7510. ast_copy_string(buf, ast_str_buffer(uri), size);
  7511. return buf;
  7512. }
  7513. /*!
  7514. * \brief Build SIP Call-ID value for a non-REGISTER transaction
  7515. *
  7516. * \note The passed in pvt must not be in a dialogs container
  7517. * since this function changes the hash key used by the
  7518. * container.
  7519. */
  7520. static void build_callid_pvt(struct sip_pvt *pvt)
  7521. {
  7522. char buf[33];
  7523. const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
  7524. ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
  7525. }
  7526. /*! \brief Unlink the given object from the container and return TRUE if it was in the container. */
  7527. #define CONTAINER_UNLINK(container, obj, tag) \
  7528. ({ \
  7529. int found = 0; \
  7530. typeof((obj)) __removed_obj; \
  7531. __removed_obj = ao2_t_callback((container), \
  7532. OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag)); \
  7533. if (__removed_obj) { \
  7534. ao2_ref(__removed_obj, -1); \
  7535. found = 1; \
  7536. } \
  7537. found; \
  7538. })
  7539. /*!
  7540. * \internal
  7541. * \brief Safely change the callid of the given SIP dialog.
  7542. *
  7543. * \param pvt SIP private structure to change callid
  7544. * \param callid Specified new callid to use. NULL if generate new callid.
  7545. *
  7546. * \return Nothing
  7547. */
  7548. static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
  7549. {
  7550. int in_dialog_container;
  7551. int in_rtp_container;
  7552. char *oldid = ast_strdupa(pvt->callid);
  7553. ao2_lock(dialogs);
  7554. ao2_lock(dialogs_rtpcheck);
  7555. in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
  7556. "About to change the callid -- remove the old name");
  7557. in_rtp_container = CONTAINER_UNLINK(dialogs_rtpcheck, pvt,
  7558. "About to change the callid -- remove the old name");
  7559. if (callid) {
  7560. ast_string_field_set(pvt, callid, callid);
  7561. } else {
  7562. build_callid_pvt(pvt);
  7563. }
  7564. if (in_dialog_container) {
  7565. ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
  7566. }
  7567. if (in_rtp_container) {
  7568. ao2_t_link(dialogs_rtpcheck, pvt, "New dialog callid -- inserted back into table");
  7569. }
  7570. ao2_unlock(dialogs_rtpcheck);
  7571. ao2_unlock(dialogs);
  7572. if (strcmp(oldid, pvt->callid)) {
  7573. ast_debug(1, "SIP call-id changed from '%s' to '%s'\n", oldid, pvt->callid);
  7574. }
  7575. }
  7576. /*! \brief Build SIP Call-ID value for a REGISTER transaction */
  7577. static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
  7578. {
  7579. char buf[33];
  7580. const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
  7581. ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
  7582. }
  7583. /*! \brief Build SIP From tag value for REGISTER */
  7584. static void build_localtag_registry(struct sip_registry *reg)
  7585. {
  7586. ast_string_field_build(reg, localtag, "as%08lx", (unsigned long)ast_random());
  7587. }
  7588. /*! \brief Make our SIP dialog tag */
  7589. static void make_our_tag(struct sip_pvt *pvt)
  7590. {
  7591. ast_string_field_build(pvt, tag, "as%08lx", (unsigned long)ast_random());
  7592. }
  7593. /*! \brief Allocate Session-Timers struct w/in dialog */
  7594. static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
  7595. {
  7596. struct sip_st_dlg *stp;
  7597. if (p->stimer) {
  7598. ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
  7599. return p->stimer;
  7600. }
  7601. if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
  7602. return NULL;
  7603. p->stimer = stp;
  7604. stp->st_schedid = -1; /* Session-Timers ast_sched scheduler id */
  7605. return p->stimer;
  7606. }
  7607. static void sip_pvt_callid_set(struct sip_pvt *pvt, ast_callid callid)
  7608. {
  7609. pvt->logger_callid = callid;
  7610. }
  7611. /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
  7612. * Returns a reference to the object so whoever uses it later must
  7613. * remember to release the reference.
  7614. */
  7615. struct sip_pvt *__sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
  7616. int useglobal_nat, const int intended_method, struct sip_request *req, ast_callid logger_callid,
  7617. const char *file, int line, const char *func)
  7618. {
  7619. struct sip_pvt *p;
  7620. p = __ao2_alloc_debug(sizeof(*p), sip_destroy_fn,
  7621. AO2_ALLOC_OPT_LOCK_MUTEX, "allocate a dialog(pvt) struct",
  7622. file, line, func, 1);
  7623. if (!p) {
  7624. return NULL;
  7625. }
  7626. if (ast_string_field_init(p, 512)) {
  7627. ao2_t_ref(p, -1, "failed to string_field_init, drop p");
  7628. return NULL;
  7629. }
  7630. if (!(p->cc_params = ast_cc_config_params_init())) {
  7631. ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
  7632. return NULL;
  7633. }
  7634. if (logger_callid) {
  7635. sip_pvt_callid_set(p, logger_callid);
  7636. }
  7637. p->caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7638. p->jointcaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7639. p->peercaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7640. p->redircaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7641. p->prefcaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7642. if (!p->caps|| !p->jointcaps || !p->peercaps || !p->redircaps || !p->prefcaps) {
  7643. ao2_cleanup(p->caps);
  7644. ao2_cleanup(p->jointcaps);
  7645. ao2_cleanup(p->peercaps);
  7646. ao2_cleanup(p->redircaps);
  7647. ao2_cleanup(p->prefcaps);
  7648. ao2_t_ref(p, -1, "Yuck, couldn't allocate format capabilities. Get rid o' p");
  7649. return NULL;
  7650. }
  7651. /* If this dialog is created as a result of a request or response, lets store
  7652. * some information about it in the dialog. */
  7653. if (req) {
  7654. struct sip_via *via;
  7655. const char *cseq = sip_get_header(req, "Cseq");
  7656. uint32_t seqno;
  7657. /* get branch parameter from initial Request that started this dialog */
  7658. via = parse_via(sip_get_header(req, "Via"));
  7659. if (via) {
  7660. /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
  7661. * it is not useful to us to have it */
  7662. if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
  7663. ast_string_field_set(p, initviabranch, via->branch);
  7664. ast_string_field_set(p, initviasentby, via->sent_by);
  7665. }
  7666. free_via(via);
  7667. }
  7668. /* Store initial incoming cseq. An error in sscanf here is ignored. There is no approperiate
  7669. * except not storing the number. CSeq validation must take place before dialog creation in find_call */
  7670. if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
  7671. p->init_icseq = seqno;
  7672. }
  7673. /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
  7674. set_socket_transport(&p->socket, req->socket.type);
  7675. } else {
  7676. set_socket_transport(&p->socket, AST_TRANSPORT_UDP);
  7677. }
  7678. p->socket.fd = -1;
  7679. p->method = intended_method;
  7680. p->initid = -1;
  7681. p->waitid = -1;
  7682. p->reinviteid = -1;
  7683. p->autokillid = -1;
  7684. p->request_queue_sched_id = -1;
  7685. p->provisional_keepalive_sched_id = -1;
  7686. p->t38id = -1;
  7687. p->subscribed = NONE;
  7688. p->stateid = -1;
  7689. p->sessionversion_remote = -1;
  7690. p->session_modify = TRUE;
  7691. p->stimer = NULL;
  7692. ast_copy_string(p->zone, default_zone, sizeof(p->zone));
  7693. p->maxforwards = sip_cfg.default_max_forwards;
  7694. if (intended_method != SIP_OPTIONS) { /* Peerpoke has it's own system */
  7695. p->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
  7696. p->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
  7697. }
  7698. if (!addr) {
  7699. p->ourip = internip;
  7700. } else {
  7701. ast_sockaddr_copy(&p->sa, addr);
  7702. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  7703. }
  7704. /* Copy global flags to this PVT at setup. */
  7705. ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
  7706. ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  7707. ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  7708. p->do_history = recordhistory;
  7709. p->branch = ast_random();
  7710. make_our_tag(p);
  7711. p->ocseq = INITIAL_CSEQ;
  7712. p->allowed_methods = UINT_MAX;
  7713. if (sip_methods[intended_method].need_rtp) {
  7714. p->maxcallbitrate = default_maxcallbitrate;
  7715. p->autoframing = global_autoframing;
  7716. }
  7717. if (useglobal_nat && addr) {
  7718. /* Setup NAT structure according to global settings if we have an address */
  7719. ast_sockaddr_copy(&p->recv, addr);
  7720. check_via(p, req);
  7721. do_setnat(p);
  7722. }
  7723. if (p->method != SIP_REGISTER) {
  7724. ast_string_field_set(p, fromdomain, default_fromdomain);
  7725. p->fromdomainport = default_fromdomainport;
  7726. }
  7727. build_via(p);
  7728. if (!callid)
  7729. build_callid_pvt(p);
  7730. else
  7731. ast_string_field_set(p, callid, callid);
  7732. /* Assign default music on hold class */
  7733. ast_string_field_set(p, mohinterpret, default_mohinterpret);
  7734. ast_string_field_set(p, mohsuggest, default_mohsuggest);
  7735. ast_format_cap_append_from_cap(p->caps, sip_cfg.caps, AST_MEDIA_TYPE_UNKNOWN);
  7736. p->allowtransfer = sip_cfg.allowtransfer;
  7737. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
  7738. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  7739. p->noncodeccapability |= AST_RTP_DTMF;
  7740. }
  7741. ast_string_field_set(p, context, sip_cfg.default_context);
  7742. ast_string_field_set(p, parkinglot, default_parkinglot);
  7743. ast_string_field_set(p, engine, default_engine);
  7744. AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
  7745. AST_LIST_HEAD_INIT_NOLOCK(&p->offered_media);
  7746. /* Add to active dialog list */
  7747. ao2_t_link(dialogs, p, "link pvt into dialogs table");
  7748. ast_debug(1, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : p->callid, sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
  7749. return p;
  7750. }
  7751. /*!
  7752. * \brief Process the Via header according to RFC 3261 section 18.2.2.
  7753. * \param p a sip_pvt structure that will be modified according to the received
  7754. * header
  7755. * \param req a sip request with a Via header to process
  7756. *
  7757. * This function will update the destination of the response according to the
  7758. * Via header in the request and RFC 3261 section 18.2.2. We do not have a
  7759. * transport layer so we ignore certain values like the 'received' param (we
  7760. * set the destination address to the address the request came from in the
  7761. * respprep() function).
  7762. *
  7763. * \retval -1 error
  7764. * \retval 0 success
  7765. */
  7766. static int process_via(struct sip_pvt *p, const struct sip_request *req)
  7767. {
  7768. struct sip_via *via = parse_via(sip_get_header(req, "Via"));
  7769. if (!via) {
  7770. ast_log(LOG_ERROR, "error processing via header\n");
  7771. return -1;
  7772. }
  7773. if (via->maddr) {
  7774. if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
  7775. ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
  7776. ast_log(LOG_ERROR, "error processing via header\n");
  7777. free_via(via);
  7778. return -1;
  7779. }
  7780. if (ast_sockaddr_is_ipv4_multicast(&p->sa)) {
  7781. setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
  7782. }
  7783. }
  7784. ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
  7785. free_via(via);
  7786. return 0;
  7787. }
  7788. /* \brief arguments used for Request/Response to matching */
  7789. struct match_req_args {
  7790. int method;
  7791. const char *callid;
  7792. const char *totag;
  7793. const char *fromtag;
  7794. uint32_t seqno;
  7795. /* Set if this method is a Response */
  7796. int respid;
  7797. /* Set if the method is a Request */
  7798. const char *ruri;
  7799. const char *viabranch;
  7800. const char *viasentby;
  7801. /* Set this if the Authentication header is present in the Request. */
  7802. int authentication_present;
  7803. };
  7804. enum match_req_res {
  7805. SIP_REQ_MATCH,
  7806. SIP_REQ_NOT_MATCH,
  7807. SIP_REQ_LOOP_DETECTED, /* multiple incoming requests with same call-id but different branch parameters have been detected */
  7808. SIP_REQ_FORKED, /* An outgoing request has been forked as result of receiving two differing 200ok responses. */
  7809. };
  7810. /*
  7811. * \brief Match a incoming Request/Response to a dialog
  7812. *
  7813. * \retval enum match_req_res indicating if the dialog matches the arg
  7814. */
  7815. static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
  7816. {
  7817. const char *init_ruri = NULL;
  7818. if (sip_pvt_ptr->initreq.headers) {
  7819. init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlpart2);
  7820. }
  7821. /*
  7822. * Match Tags and call-id to Dialog
  7823. */
  7824. if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
  7825. /* call-id does not match. */
  7826. return SIP_REQ_NOT_MATCH;
  7827. }
  7828. if (arg->method == SIP_RESPONSE) {
  7829. /* Verify fromtag of response matches the tag we gave them. */
  7830. if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
  7831. /* fromtag from response does not match our tag */
  7832. return SIP_REQ_NOT_MATCH;
  7833. }
  7834. /* Verify totag if we have one stored for this dialog, but never be strict about this for
  7835. * a response until the dialog is established */
  7836. if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  7837. if (ast_strlen_zero(arg->totag)) {
  7838. /* missing totag when they already gave us one earlier */
  7839. return SIP_REQ_NOT_MATCH;
  7840. }
  7841. /* compare the totag of response with the tag we have stored for them */
  7842. if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
  7843. /* totag did not match what we had stored for them. */
  7844. char invite_branch[32] = { 0, };
  7845. if (sip_pvt_ptr->invite_branch) {
  7846. snprintf(invite_branch, sizeof(invite_branch), "z9hG4bK%08x", (unsigned)sip_pvt_ptr->invite_branch);
  7847. }
  7848. /* Forked Request Detection
  7849. *
  7850. * If this is a 200ok response and the totags do not match, this
  7851. * might be a forked response to an outgoing Request. Detection of
  7852. * a forked response must meet the criteria below.
  7853. *
  7854. * 1. must be a 2xx Response
  7855. * 2. call-d equal to call-id of Request. this is done earlier
  7856. * 3. from-tag equal to from-tag of Request. this is done earlier
  7857. * 4. branch parameter equal to branch of inital Request
  7858. * 5. to-tag _NOT_ equal to previous 2xx response that already established the dialog.
  7859. */
  7860. if ((arg->respid == 200) &&
  7861. !ast_strlen_zero(invite_branch) &&
  7862. !ast_strlen_zero(arg->viabranch) &&
  7863. !strcmp(invite_branch, arg->viabranch)) {
  7864. return SIP_REQ_FORKED;
  7865. }
  7866. /* The totag did not match the one we had stored, and this is not a Forked Request. */
  7867. return SIP_REQ_NOT_MATCH;
  7868. }
  7869. }
  7870. } else {
  7871. /* Verify the fromtag of Request matches the tag they provided earlier.
  7872. * If this is a Request with authentication credentials, forget their old
  7873. * tag as it is not valid after the 401 or 407 response. */
  7874. if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
  7875. /* their tag does not match the one was have stored for them */
  7876. return SIP_REQ_NOT_MATCH;
  7877. }
  7878. /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
  7879. if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
  7880. /* totag from Request does not match our tag */
  7881. return SIP_REQ_NOT_MATCH;
  7882. }
  7883. }
  7884. /*
  7885. * Compare incoming request against initial transaction.
  7886. *
  7887. * This is a best effort attempt at distinguishing forked requests from
  7888. * our initial transaction. If all the elements are NOT in place to evaluate
  7889. * this, this block is ignored and the dialog match is made regardless.
  7890. * Once the totag is established after the dialog is confirmed, this is not necessary.
  7891. *
  7892. * CRITERIA required for initial transaction matching.
  7893. *
  7894. * 1. Is a Request
  7895. * 2. Callid and theirtag match (this is done in the dialog matching block)
  7896. * 3. totag is NOT present
  7897. * 4. CSeq matchs our initial transaction's cseq number
  7898. * 5. pvt has init via branch parameter stored
  7899. */
  7900. if ((arg->method != SIP_RESPONSE) && /* must be a Request */
  7901. ast_strlen_zero(arg->totag) && /* must not have a totag */
  7902. (sip_pvt_ptr->init_icseq == arg->seqno) && /* the cseq must be the same as this dialogs initial cseq */
  7903. !ast_strlen_zero(sip_pvt_ptr->initviabranch) && /* The dialog must have started with a RFC3261 compliant branch tag */
  7904. init_ruri) { /* the dialog must have an initial request uri associated with it */
  7905. /* This Request matches all the criteria required for Loop/Merge detection.
  7906. * Now we must go down the path of comparing VIA's and RURIs. */
  7907. if (ast_strlen_zero(arg->viabranch) ||
  7908. strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
  7909. ast_strlen_zero(arg->viasentby) ||
  7910. strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
  7911. /* At this point, this request does not match this Dialog.*/
  7912. /* if methods are different this is just a mismatch */
  7913. if ((sip_pvt_ptr->method != arg->method)) {
  7914. return SIP_REQ_NOT_MATCH;
  7915. }
  7916. /* If RUIs are different, this is a forked request to a separate URI.
  7917. * Returning a mismatch allows this Request to be processed separately. */
  7918. if (sip_uri_cmp(init_ruri, arg->ruri)) {
  7919. /* not a match, request uris are different */
  7920. return SIP_REQ_NOT_MATCH;
  7921. }
  7922. /* Loop/Merge Detected
  7923. *
  7924. * ---Current Matches to Initial Request---
  7925. * request uri
  7926. * Call-id
  7927. * their-tag
  7928. * no totag present
  7929. * method
  7930. * cseq
  7931. *
  7932. * --- Does not Match Initial Request ---
  7933. * Top Via
  7934. *
  7935. * Without the same Via, this can not match our initial transaction for this dialog,
  7936. * but given that this Request matches everything else associated with that initial
  7937. * Request this is most certainly a Forked request in which we have already received
  7938. * part of the fork.
  7939. */
  7940. return SIP_REQ_LOOP_DETECTED;
  7941. }
  7942. } /* end of Request Via check */
  7943. /* Match Authentication Request.
  7944. *
  7945. * A Request with an Authentication header must come back with the
  7946. * same Request URI. Otherwise it is not a match.
  7947. */
  7948. if ((arg->method != SIP_RESPONSE) && /* Must be a Request type to even begin checking this */
  7949. ast_strlen_zero(arg->totag) && /* no totag is present to match */
  7950. arg->authentication_present && /* Authentication header is present in Request */
  7951. sip_uri_cmp(init_ruri, arg->ruri)) { /* Compare the Request URI of both the last Request and this new one */
  7952. /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
  7953. return SIP_REQ_NOT_MATCH;
  7954. }
  7955. return SIP_REQ_MATCH;
  7956. }
  7957. /*! \brief This function creates a dialog to handle a forked request. This dialog
  7958. * exists only to properly terminiate the the forked request immediately.
  7959. */
  7960. static void forked_invite_init(struct sip_request *req, const char *new_theirtag, struct sip_pvt *original, struct ast_sockaddr *addr)
  7961. {
  7962. struct sip_pvt *p;
  7963. const char *callid;
  7964. ast_callid logger_callid;
  7965. sip_pvt_lock(original);
  7966. callid = ast_strdupa(original->callid);
  7967. logger_callid = original->logger_callid;
  7968. sip_pvt_unlock(original);
  7969. p = sip_alloc(callid, addr, 1, SIP_INVITE, req, logger_callid);
  7970. if (!p) {
  7971. return; /* alloc error */
  7972. }
  7973. /* Lock p and original private structures. */
  7974. sip_pvt_lock(p);
  7975. while (sip_pvt_trylock(original)) {
  7976. /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
  7977. sip_pvt_unlock(p);
  7978. sched_yield();
  7979. sip_pvt_lock(p);
  7980. }
  7981. p->invitestate = INV_TERMINATED;
  7982. p->ocseq = original->ocseq;
  7983. p->branch = original->branch;
  7984. memcpy(&p->flags, &original->flags, sizeof(p->flags));
  7985. copy_request(&p->initreq, &original->initreq);
  7986. ast_string_field_set(p, theirtag, new_theirtag);
  7987. ast_string_field_set(p, tag, original->tag);
  7988. ast_string_field_set(p, uri, original->uri);
  7989. ast_string_field_set(p, our_contact, original->our_contact);
  7990. ast_string_field_set(p, fullcontact, original->fullcontact);
  7991. sip_pvt_unlock(original);
  7992. parse_ok_contact(p, req);
  7993. build_route(p, req, 1, 0);
  7994. transmit_request(p, SIP_ACK, p->ocseq, XMIT_UNRELIABLE, TRUE);
  7995. transmit_request(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
  7996. pvt_set_needdestroy(p, "forked request"); /* this dialog will terminate once the BYE is responed to or times out. */
  7997. sip_pvt_unlock(p);
  7998. dialog_unref(p, "setup forked invite termination");
  7999. }
  8000. /*! \internal
  8001. *
  8002. * \brief Locks both pvt and pvt owner if owner is present.
  8003. *
  8004. * \note This function gives a ref to pvt->owner if it is present and locked.
  8005. * This reference must be decremented after pvt->owner is unlocked.
  8006. *
  8007. * \note This function will never give you up,
  8008. * \note This function will never let you down.
  8009. * \note This function will run around and desert you.
  8010. *
  8011. * \pre pvt is not locked
  8012. * \post pvt is locked
  8013. * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
  8014. *
  8015. * \returns a pointer to the locked and reffed pvt->owner channel if it exists.
  8016. */
  8017. static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
  8018. {
  8019. struct ast_channel *chan;
  8020. /* Locking is simple when it is done right. If you see a deadlock resulting
  8021. * in this function, it is not this function's fault, Your problem exists elsewhere.
  8022. * This function is perfect... seriously. */
  8023. for (;;) {
  8024. /* First, get the channel and grab a reference to it */
  8025. sip_pvt_lock(pvt);
  8026. chan = pvt->owner;
  8027. if (chan) {
  8028. /* The channel can not go away while we hold the pvt lock.
  8029. * Give the channel a ref so it will not go away after we let
  8030. * the pvt lock go. */
  8031. ast_channel_ref(chan);
  8032. } else {
  8033. /* no channel, return pvt locked */
  8034. return NULL;
  8035. }
  8036. /* We had to hold the pvt lock while getting a ref to the owner channel
  8037. * but now we have to let this lock go in order to preserve proper
  8038. * locking order when grabbing the channel lock */
  8039. sip_pvt_unlock(pvt);
  8040. /* Look, no deadlock avoidance, hooray! */
  8041. ast_channel_lock(chan);
  8042. sip_pvt_lock(pvt);
  8043. if (pvt->owner == chan) {
  8044. /* done */
  8045. break;
  8046. }
  8047. /* If the owner changed while everything was unlocked, no problem,
  8048. * just start over and everthing will work. This is rare, do not be
  8049. * confused by this loop and think this it is an expensive operation.
  8050. * The majority of the calls to this function will never involve multiple
  8051. * executions of this loop. */
  8052. ast_channel_unlock(chan);
  8053. ast_channel_unref(chan);
  8054. sip_pvt_unlock(pvt);
  8055. }
  8056. /* If owner exists, it is locked and reffed */
  8057. return pvt->owner;
  8058. }
  8059. /*! \brief Set the owning channel on the \ref sip_pvt object */
  8060. static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan)
  8061. {
  8062. p->owner = chan;
  8063. if (p->rtp) {
  8064. ast_rtp_instance_set_channel_id(p->rtp, p->owner ? ast_channel_uniqueid(p->owner) : "");
  8065. }
  8066. if (p->vrtp) {
  8067. ast_rtp_instance_set_channel_id(p->vrtp, p->owner ? ast_channel_uniqueid(p->owner) : "");
  8068. }
  8069. if (p->trtp) {
  8070. ast_rtp_instance_set_channel_id(p->trtp, p->owner ? ast_channel_uniqueid(p->owner) : "");
  8071. }
  8072. }
  8073. /*! \brief find or create a dialog structure for an incoming SIP message.
  8074. * Connect incoming SIP message to current dialog or create new dialog structure
  8075. * Returns a reference to the sip_pvt object, remember to give it back once done.
  8076. * Called by handle_request_do
  8077. */
  8078. static struct sip_pvt *__find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method,
  8079. const char *file, int line, const char *func)
  8080. {
  8081. char totag[128];
  8082. char fromtag[128];
  8083. const char *callid = sip_get_header(req, "Call-ID");
  8084. const char *from = sip_get_header(req, "From");
  8085. const char *to = sip_get_header(req, "To");
  8086. const char *cseq = sip_get_header(req, "Cseq");
  8087. struct sip_pvt *sip_pvt_ptr;
  8088. uint32_t seqno;
  8089. /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
  8090. /* sip_get_header always returns non-NULL so we must use ast_strlen_zero() */
  8091. if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
  8092. ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
  8093. (sscanf(cseq, "%30u", &seqno) != 1)) {
  8094. /* RFC 3261 section 24.4.1. Send a 400 Bad Request if the request is malformed. */
  8095. if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
  8096. transmit_response_using_temp(callid, addr, 1, intended_method,
  8097. req, "400 Bad Request");
  8098. }
  8099. return NULL; /* Invalid packet */
  8100. }
  8101. if (sip_cfg.pedanticsipchecking) {
  8102. /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
  8103. we need more to identify a branch - so we have to check branch, from
  8104. and to tags to identify a call leg.
  8105. For Asterisk to behave correctly, you need to turn on pedanticsipchecking
  8106. in sip.conf
  8107. */
  8108. if (gettag(req, "To", totag, sizeof(totag)))
  8109. req->has_to_tag = 1; /* Used in handle_request/response */
  8110. gettag(req, "From", fromtag, sizeof(fromtag));
  8111. ast_debug(5, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
  8112. /* All messages must always have From: tag */
  8113. if (ast_strlen_zero(fromtag)) {
  8114. ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
  8115. return NULL;
  8116. }
  8117. /* reject requests that must always have a To: tag */
  8118. if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
  8119. if (req->method != SIP_ACK) {
  8120. transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
  8121. }
  8122. ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
  8123. return NULL;
  8124. }
  8125. }
  8126. /* match on callid only for REGISTERs */
  8127. if (!sip_cfg.pedanticsipchecking || req->method == SIP_REGISTER) {
  8128. struct sip_pvt tmp_dialog = {
  8129. .callid = callid,
  8130. };
  8131. sip_pvt_ptr = __ao2_find_debug(dialogs, &tmp_dialog, OBJ_POINTER,
  8132. "find_call in dialogs", file, line, func);
  8133. if (sip_pvt_ptr) { /* well, if we don't find it-- what IS in there? */
  8134. /* Found the call */
  8135. return sip_pvt_ptr;
  8136. }
  8137. } else { /* in pedantic mode! -- do the fancy search */
  8138. struct sip_pvt tmp_dialog = {
  8139. .callid = callid,
  8140. };
  8141. /* if a Outbound forked Request is detected, this pvt will point
  8142. * to the dialog the Request is forking off of. */
  8143. struct sip_pvt *fork_pvt = NULL;
  8144. struct match_req_args args = { 0, };
  8145. int found;
  8146. struct ao2_iterator *iterator = __ao2_callback_debug(dialogs,
  8147. OBJ_POINTER | OBJ_MULTIPLE,
  8148. dialog_find_multiple,
  8149. &tmp_dialog,
  8150. "pedantic ao2_find in dialogs",
  8151. file, line, func);
  8152. struct sip_via *via = NULL;
  8153. args.method = req->method;
  8154. args.callid = NULL; /* we already matched this. */
  8155. args.totag = totag;
  8156. args.fromtag = fromtag;
  8157. args.seqno = seqno;
  8158. /* get via header information. */
  8159. args.ruri = REQ_OFFSET_TO_STR(req, rlpart2);
  8160. via = parse_via(sip_get_header(req, "Via"));
  8161. if (via) {
  8162. args.viasentby = via->sent_by;
  8163. args.viabranch = via->branch;
  8164. }
  8165. /* determine if this is a Request with authentication credentials. */
  8166. if (!ast_strlen_zero(sip_get_header(req, "Authorization")) ||
  8167. !ast_strlen_zero(sip_get_header(req, "Proxy-Authorization"))) {
  8168. args.authentication_present = 1;
  8169. }
  8170. /* if it is a response, get the response code */
  8171. if (req->method == SIP_RESPONSE) {
  8172. const char* e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
  8173. int respid;
  8174. if (!ast_strlen_zero(e) && (sscanf(e, "%30d", &respid) == 1)) {
  8175. args.respid = respid;
  8176. }
  8177. }
  8178. /* Iterate a list of dialogs already matched by Call-id */
  8179. while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
  8180. sip_pvt_lock(sip_pvt_ptr);
  8181. found = match_req_to_dialog(sip_pvt_ptr, &args);
  8182. sip_pvt_unlock(sip_pvt_ptr);
  8183. switch (found) {
  8184. case SIP_REQ_MATCH:
  8185. ao2_iterator_destroy(iterator);
  8186. dialog_unref(fork_pvt, "unref fork_pvt");
  8187. free_via(via);
  8188. return sip_pvt_ptr; /* return pvt with ref */
  8189. case SIP_REQ_LOOP_DETECTED:
  8190. /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
  8191. * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
  8192. transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
  8193. __ao2_ref_debug(sip_pvt_ptr, -1, "pvt did not match incoming SIP msg, unref from search.",
  8194. file, line, func);
  8195. ao2_iterator_destroy(iterator);
  8196. dialog_unref(fork_pvt, "unref fork_pvt");
  8197. free_via(via);
  8198. return NULL;
  8199. case SIP_REQ_FORKED:
  8200. dialog_unref(fork_pvt, "throwing way pvt to fork off of.");
  8201. fork_pvt = dialog_ref(sip_pvt_ptr, "this pvt has a forked request, save this off to copy information into new dialog\n");
  8202. /* fall through */
  8203. case SIP_REQ_NOT_MATCH:
  8204. default:
  8205. __ao2_ref_debug(sip_pvt_ptr, -1, "pvt did not match incoming SIP msg, unref from search",
  8206. file, line, func);
  8207. break;
  8208. }
  8209. }
  8210. if (iterator) {
  8211. ao2_iterator_destroy(iterator);
  8212. }
  8213. /* Handle any possible forked requests. This must be done only after transaction matching is complete. */
  8214. if (fork_pvt) {
  8215. /* XXX right now we only support handling forked INVITE Requests. Any other
  8216. * forked request type must be added here. */
  8217. if (fork_pvt->method == SIP_INVITE) {
  8218. forked_invite_init(req, args.totag, fork_pvt, addr);
  8219. dialog_unref(fork_pvt, "throwing way old forked pvt");
  8220. free_via(via);
  8221. return NULL;
  8222. }
  8223. fork_pvt = dialog_unref(fork_pvt, "throwing way pvt to fork off of");
  8224. }
  8225. free_via(via);
  8226. } /* end of pedantic mode Request/Reponse to Dialog matching */
  8227. /* See if the method is capable of creating a dialog */
  8228. if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
  8229. struct sip_pvt *p = NULL;
  8230. ast_callid logger_callid = 0;
  8231. if (intended_method == SIP_INVITE) {
  8232. logger_callid = ast_create_callid();
  8233. }
  8234. /* Ok, time to create a new SIP dialog object, a pvt */
  8235. if (!(p = sip_alloc(callid, addr, 1, intended_method, req, logger_callid))) {
  8236. /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
  8237. getting a dialog from sip_alloc.
  8238. Without a dialog we can't retransmit and handle ACKs and all that, but at least
  8239. send an error message.
  8240. Sorry, we apologize for the inconvienience
  8241. */
  8242. transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
  8243. ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
  8244. }
  8245. return p; /* can be NULL */
  8246. } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
  8247. /* A method we do not support, let's take it on the volley */
  8248. transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
  8249. ast_debug(2, "Got a request with unsupported SIP method.\n");
  8250. } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
  8251. /* This is a request outside of a dialog that we don't know about */
  8252. transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
  8253. ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
  8254. }
  8255. /* We do not respond to responses for dialogs that we don't know about, we just drop
  8256. the session quickly */
  8257. if (intended_method == SIP_RESPONSE)
  8258. ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
  8259. return NULL;
  8260. }
  8261. /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
  8262. static int sip_register(const char *value, int lineno)
  8263. {
  8264. struct sip_registry *reg;
  8265. reg = ao2_t_find(registry_list, value, OBJ_SEARCH_KEY, "check for existing registry");
  8266. if (reg) {
  8267. ao2_t_ref(reg, -1, "throw away found registry");
  8268. return 0;
  8269. }
  8270. if (!(reg = ao2_t_alloc(sizeof(*reg), sip_registry_destroy, "allocate a registry struct"))) {
  8271. ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
  8272. return -1;
  8273. }
  8274. if (ast_string_field_init(reg, 256)) {
  8275. ao2_t_ref(reg, -1, "failed to string_field_init, drop reg");
  8276. return -1;
  8277. }
  8278. ast_string_field_set(reg, configvalue, value);
  8279. if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
  8280. ao2_t_ref(reg, -1, "failure to parse, unref the reg pointer");
  8281. return -1;
  8282. }
  8283. /* set default expiry if necessary */
  8284. if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
  8285. reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
  8286. }
  8287. ao2_t_link(registry_list, reg, "link reg to registry_list");
  8288. ao2_t_ref(reg, -1, "unref the reg pointer");
  8289. return 0;
  8290. }
  8291. /*! \brief Parse mwi=> line in sip.conf and add to list */
  8292. static int sip_subscribe_mwi(const char *value, int lineno)
  8293. {
  8294. struct sip_subscription_mwi *mwi;
  8295. int portnum = 0;
  8296. enum ast_transport transport = AST_TRANSPORT_UDP;
  8297. char buf[256] = "";
  8298. char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
  8299. if (!value) {
  8300. return -1;
  8301. }
  8302. ast_copy_string(buf, value, sizeof(buf));
  8303. username = buf;
  8304. if ((hostname = strrchr(buf, '@'))) {
  8305. *hostname++ = '\0';
  8306. } else {
  8307. return -1;
  8308. }
  8309. if ((secret = strchr(username, ':'))) {
  8310. *secret++ = '\0';
  8311. if ((authuser = strchr(secret, ':'))) {
  8312. *authuser++ = '\0';
  8313. }
  8314. }
  8315. if ((mailbox = strchr(hostname, '/'))) {
  8316. *mailbox++ = '\0';
  8317. }
  8318. if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
  8319. ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
  8320. return -1;
  8321. }
  8322. if ((porta = strchr(hostname, ':'))) {
  8323. *porta++ = '\0';
  8324. if (!(portnum = atoi(porta))) {
  8325. ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
  8326. return -1;
  8327. }
  8328. }
  8329. if (!(mwi = ao2_t_alloc(sizeof(*mwi), sip_subscribe_mwi_destroy, "allocate an mwi struct"))) {
  8330. return -1;
  8331. }
  8332. if (ast_string_field_init(mwi, 256)) {
  8333. ao2_t_ref(mwi, -1, "failed to string_field_init, drop mwi");
  8334. return -1;
  8335. }
  8336. ast_string_field_set(mwi, username, username);
  8337. if (secret) {
  8338. ast_string_field_set(mwi, secret, secret);
  8339. }
  8340. if (authuser) {
  8341. ast_string_field_set(mwi, authuser, authuser);
  8342. }
  8343. ast_string_field_set(mwi, hostname, hostname);
  8344. ast_string_field_set(mwi, mailbox, mailbox);
  8345. mwi->resub = -1;
  8346. mwi->portno = portnum;
  8347. mwi->transport = transport;
  8348. ao2_t_link(subscription_mwi_list, mwi, "link new mwi object");
  8349. ao2_t_ref(mwi, -1, "unref to match ao2_t_alloc");
  8350. return 0;
  8351. }
  8352. static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
  8353. {
  8354. (*allowed_methods) |= (1 << method);
  8355. }
  8356. static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
  8357. {
  8358. (*allowed_methods) &= ~(1 << method);
  8359. }
  8360. /*! \brief Check if method is allowed for a device or a dialog */
  8361. static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
  8362. {
  8363. return ((*allowed_methods) >> method) & 1;
  8364. }
  8365. static void mark_parsed_methods(unsigned int *methods, char *methods_str)
  8366. {
  8367. char *method;
  8368. for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
  8369. int id = find_sip_method(ast_skip_blanks(method));
  8370. if (id == SIP_UNKNOWN) {
  8371. continue;
  8372. }
  8373. mark_method_allowed(methods, id);
  8374. }
  8375. }
  8376. /*!
  8377. * \brief parse the Allow header to see what methods the endpoint we
  8378. * are communicating with allows.
  8379. *
  8380. * We parse the allow header on incoming Registrations and save the
  8381. * result to the SIP peer that is registering. When the registration
  8382. * expires, we clear what we know about the peer's allowed methods.
  8383. * When the peer re-registers, we once again parse to see if the
  8384. * list of allowed methods has changed.
  8385. *
  8386. * For peers that do not register, we parse the first message we receive
  8387. * during a call to see what is allowed, and save the information
  8388. * for the duration of the call.
  8389. * \param req The SIP request we are parsing
  8390. * \retval The methods allowed
  8391. */
  8392. static unsigned int parse_allowed_methods(struct sip_request *req)
  8393. {
  8394. char *allow = ast_strdupa(sip_get_header(req, "Allow"));
  8395. unsigned int allowed_methods = SIP_UNKNOWN;
  8396. if (ast_strlen_zero(allow)) {
  8397. /* I have witnessed that REGISTER requests from Polycom phones do not
  8398. * place the phone's allowed methods in an Allow header. Instead, they place the
  8399. * allowed methods in a methods= parameter in the Contact header.
  8400. */
  8401. char *contact = ast_strdupa(sip_get_header(req, "Contact"));
  8402. char *methods = strstr(contact, ";methods=");
  8403. if (ast_strlen_zero(methods)) {
  8404. /* RFC 3261 states:
  8405. *
  8406. * "The absence of an Allow header field MUST NOT be
  8407. * interpreted to mean that the UA sending the message supports no
  8408. * methods. Rather, it implies that the UA is not providing any
  8409. * information on what methods it supports."
  8410. *
  8411. * For simplicity, we'll assume that the peer allows all known
  8412. * SIP methods if they have no Allow header. We can then clear out the necessary
  8413. * bits if the peer lets us know that we have sent an unsupported method.
  8414. */
  8415. return UINT_MAX;
  8416. }
  8417. allow = ast_strip_quoted(methods + 9, "\"", "\"");
  8418. }
  8419. mark_parsed_methods(&allowed_methods, allow);
  8420. return allowed_methods;
  8421. }
  8422. /*! A wrapper for parse_allowed_methods geared toward sip_pvts
  8423. *
  8424. * This function, in addition to setting the allowed methods for a sip_pvt
  8425. * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
  8426. *
  8427. * \param pvt The sip_pvt we are setting the allowed_methods for
  8428. * \param req The request which we are parsing
  8429. * \retval The methods alloweded by the sip_pvt
  8430. */
  8431. static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
  8432. {
  8433. pvt->allowed_methods = parse_allowed_methods(req);
  8434. if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
  8435. mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
  8436. }
  8437. pvt->allowed_methods &= ~(pvt->disallowed_methods);
  8438. return pvt->allowed_methods;
  8439. }
  8440. /*! \brief Parse multiline SIP headers into one header
  8441. This is enabled if pedanticsipchecking is enabled */
  8442. static void lws2sws(struct ast_str *data)
  8443. {
  8444. char *msgbuf = ast_str_buffer(data);
  8445. int len = ast_str_strlen(data);
  8446. int h = 0, t = 0;
  8447. int lws = 0;
  8448. for (; h < len;) {
  8449. /* Eliminate all CRs */
  8450. if (msgbuf[h] == '\r') {
  8451. h++;
  8452. continue;
  8453. }
  8454. /* Check for end-of-line */
  8455. if (msgbuf[h] == '\n') {
  8456. /* Check for end-of-message */
  8457. if (h + 1 == len)
  8458. break;
  8459. /* Check for a continuation line */
  8460. if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
  8461. /* Merge continuation line */
  8462. h++;
  8463. continue;
  8464. }
  8465. /* Propagate LF and start new line */
  8466. msgbuf[t++] = msgbuf[h++];
  8467. lws = 0;
  8468. continue;
  8469. }
  8470. if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
  8471. if (lws) {
  8472. h++;
  8473. continue;
  8474. }
  8475. msgbuf[t++] = msgbuf[h++];
  8476. lws = 1;
  8477. continue;
  8478. }
  8479. msgbuf[t++] = msgbuf[h++];
  8480. if (lws)
  8481. lws = 0;
  8482. }
  8483. msgbuf[t] = '\0';
  8484. ast_str_update(data);
  8485. }
  8486. /*! \brief Parse a SIP message
  8487. \note this function is used both on incoming and outgoing packets
  8488. */
  8489. static int parse_request(struct sip_request *req)
  8490. {
  8491. char *c = ast_str_buffer(req->data);
  8492. ptrdiff_t *dst = req->header;
  8493. int i = 0;
  8494. unsigned int lim = SIP_MAX_HEADERS - 1;
  8495. unsigned int skipping_headers = 0;
  8496. ptrdiff_t current_header_offset = 0;
  8497. char *previous_header = "";
  8498. req->header[0] = 0;
  8499. req->headers = -1; /* mark that we are working on the header */
  8500. for (; *c; c++) {
  8501. if (*c == '\r') { /* remove \r */
  8502. *c = '\0';
  8503. } else if (*c == '\n') { /* end of this line */
  8504. *c = '\0';
  8505. current_header_offset = (c + 1) - ast_str_buffer(req->data);
  8506. previous_header = ast_str_buffer(req->data) + dst[i];
  8507. if (skipping_headers) {
  8508. /* check to see if this line is blank; if so, turn off
  8509. the skipping flag, so the next line will be processed
  8510. as a body line */
  8511. if (ast_strlen_zero(previous_header)) {
  8512. skipping_headers = 0;
  8513. }
  8514. dst[i] = current_header_offset; /* record start of next line */
  8515. continue;
  8516. }
  8517. if (sipdebug) {
  8518. ast_debug(4, "%7s %2d [%3d]: %s\n",
  8519. req->headers < 0 ? "Header" : "Body",
  8520. i, (int) strlen(previous_header), previous_header);
  8521. }
  8522. if (ast_strlen_zero(previous_header) && req->headers < 0) {
  8523. req->headers = i; /* record number of header lines */
  8524. dst = req->line; /* start working on the body */
  8525. i = 0;
  8526. lim = SIP_MAX_LINES - 1;
  8527. } else { /* move to next line, check for overflows */
  8528. if (i++ == lim) {
  8529. /* if we're processing headers, then skip any remaining
  8530. headers and move on to processing the body, otherwise
  8531. we're done */
  8532. if (req->headers != -1) {
  8533. break;
  8534. } else {
  8535. req->headers = i;
  8536. dst = req->line;
  8537. i = 0;
  8538. lim = SIP_MAX_LINES - 1;
  8539. skipping_headers = 1;
  8540. }
  8541. }
  8542. }
  8543. dst[i] = current_header_offset; /* record start of next line */
  8544. }
  8545. }
  8546. /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
  8547. but since some devices send without, we'll be generous in what we accept. However,
  8548. if we've already reached the maximum number of lines for portion of the message
  8549. we were parsing, we can't accept any more, so just ignore it.
  8550. */
  8551. previous_header = ast_str_buffer(req->data) + dst[i];
  8552. if ((i < lim) && !ast_strlen_zero(previous_header)) {
  8553. if (sipdebug) {
  8554. ast_debug(4, "%7s %2d [%3d]: %s\n",
  8555. req->headers < 0 ? "Header" : "Body",
  8556. i, (int) strlen(previous_header), previous_header );
  8557. }
  8558. i++;
  8559. }
  8560. /* update count of header or body lines */
  8561. if (req->headers >= 0) { /* we are in the body */
  8562. req->lines = i;
  8563. } else { /* no body */
  8564. req->headers = i;
  8565. req->lines = 0;
  8566. /* req->data->used will be a NULL byte */
  8567. req->line[0] = ast_str_strlen(req->data);
  8568. }
  8569. if (*c) {
  8570. ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
  8571. }
  8572. /* Split up the first line parts */
  8573. return determine_firstline_parts(req);
  8574. }
  8575. /*!
  8576. \brief Determine whether a SIP message contains an SDP in its body
  8577. \param req the SIP request to process
  8578. \return 1 if SDP found, 0 if not found
  8579. Also updates req->sdp_start and req->sdp_count to indicate where the SDP
  8580. lives in the message body.
  8581. */
  8582. static int find_sdp(struct sip_request *req)
  8583. {
  8584. const char *content_type;
  8585. const char *content_length;
  8586. const char *search;
  8587. char *boundary;
  8588. unsigned int x;
  8589. int boundaryisquoted = FALSE;
  8590. int found_application_sdp = FALSE;
  8591. int found_end_of_headers = FALSE;
  8592. content_length = sip_get_header(req, "Content-Length");
  8593. if (!ast_strlen_zero(content_length)) {
  8594. if (sscanf(content_length, "%30u", &x) != 1) {
  8595. ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
  8596. return 0;
  8597. }
  8598. /* Content-Length of zero means there can't possibly be an
  8599. SDP here, even if the Content-Type says there is */
  8600. if (x == 0)
  8601. return 0;
  8602. }
  8603. content_type = sip_get_header(req, "Content-Type");
  8604. /* if the body contains only SDP, this is easy */
  8605. if (!strncasecmp(content_type, "application/sdp", 15)) {
  8606. req->sdp_start = 0;
  8607. req->sdp_count = req->lines;
  8608. return req->lines ? 1 : 0;
  8609. }
  8610. /* if it's not multipart/mixed, there cannot be an SDP */
  8611. if (strncasecmp(content_type, "multipart/mixed", 15))
  8612. return 0;
  8613. /* if there is no boundary marker, it's invalid */
  8614. if ((search = strcasestr(content_type, ";boundary=")))
  8615. search += 10;
  8616. else if ((search = strcasestr(content_type, "; boundary=")))
  8617. search += 11;
  8618. else
  8619. return 0;
  8620. if (ast_strlen_zero(search))
  8621. return 0;
  8622. /* If the boundary is quoted with ", remove quote */
  8623. if (*search == '\"') {
  8624. search++;
  8625. boundaryisquoted = TRUE;
  8626. }
  8627. /* make a duplicate of the string, with two extra characters
  8628. at the beginning */
  8629. boundary = ast_strdupa(search - 2);
  8630. boundary[0] = boundary[1] = '-';
  8631. /* Remove final quote */
  8632. if (boundaryisquoted)
  8633. boundary[strlen(boundary) - 1] = '\0';
  8634. /* search for the boundary marker, the empty line delimiting headers from
  8635. sdp part and the end boundry if it exists */
  8636. for (x = 0; x < (req->lines); x++) {
  8637. const char *line = REQ_OFFSET_TO_STR(req, line[x]);
  8638. if (!strncasecmp(line, boundary, strlen(boundary))){
  8639. if (found_application_sdp && found_end_of_headers) {
  8640. req->sdp_count = (x - 1) - req->sdp_start;
  8641. return 1;
  8642. }
  8643. found_application_sdp = FALSE;
  8644. }
  8645. if (!strcasecmp(line, "Content-Type: application/sdp"))
  8646. found_application_sdp = TRUE;
  8647. if (ast_strlen_zero(line)) {
  8648. if (found_application_sdp && !found_end_of_headers){
  8649. req->sdp_start = x;
  8650. found_end_of_headers = TRUE;
  8651. }
  8652. }
  8653. }
  8654. if (found_application_sdp && found_end_of_headers) {
  8655. req->sdp_count = x - req->sdp_start;
  8656. return TRUE;
  8657. }
  8658. return FALSE;
  8659. }
  8660. /*! \brief Change hold state for a call */
  8661. static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
  8662. {
  8663. if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD))) {
  8664. sip_peer_hold(dialog, holdstate);
  8665. }
  8666. append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", ast_str_buffer(req->data));
  8667. if (!holdstate) { /* Put off remote hold */
  8668. ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
  8669. return;
  8670. }
  8671. /* No address for RTP, we're on hold */
  8672. /* Ensure hold flags are cleared so that overlapping flags do not conflict */
  8673. ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
  8674. if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
  8675. ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
  8676. else if (sendonly == 2) /* Inactive stream */
  8677. ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
  8678. else
  8679. ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
  8680. return;
  8681. }
  8682. /*! \internal
  8683. * \brief Returns whether or not the address is null or ANY / unspecified (0.0.0.0 or ::)
  8684. * \retval TRUE if the address is null or any
  8685. * \retval FALSE if the address it not null or any
  8686. * \note In some circumstances, calls should be placed on hold if either of these conditions exist.
  8687. */
  8688. static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
  8689. {
  8690. return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
  8691. }
  8692. /*! \brief Check the media stream list to see if the given type already exists */
  8693. static int has_media_stream(struct sip_pvt *p, enum media_type m)
  8694. {
  8695. struct offered_media *offer = NULL;
  8696. AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
  8697. if (m == offer->type) {
  8698. return 1;
  8699. }
  8700. }
  8701. return 0;
  8702. }
  8703. /*! \brief Process SIP SDP offer, select formats and activate media channels
  8704. If offer is rejected, we will not change any properties of the call
  8705. Return 0 on success, a negative value on errors.
  8706. Must be called after find_sdp().
  8707. */
  8708. static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
  8709. {
  8710. int res = 0;
  8711. /* Iterators for SDP parsing */
  8712. int start = req->sdp_start;
  8713. int next = start;
  8714. int iterator = start;
  8715. /* Temporary vars for SDP parsing */
  8716. char type = '\0';
  8717. const char *value = NULL;
  8718. const char *m = NULL; /* SDP media offer */
  8719. const char *nextm = NULL;
  8720. int len = -1;
  8721. struct offered_media *offer;
  8722. /* Host information */
  8723. struct ast_sockaddr sessionsa;
  8724. struct ast_sockaddr audiosa;
  8725. struct ast_sockaddr videosa;
  8726. struct ast_sockaddr textsa;
  8727. struct ast_sockaddr imagesa;
  8728. struct ast_sockaddr *sa = NULL; /*!< RTP audio destination IP address */
  8729. struct ast_sockaddr *vsa = NULL; /*!< RTP video destination IP address */
  8730. struct ast_sockaddr *tsa = NULL; /*!< RTP text destination IP address */
  8731. struct ast_sockaddr *isa = NULL; /*!< UDPTL image destination IP address */
  8732. int portno = -1; /*!< RTP audio destination port number */
  8733. int vportno = -1; /*!< RTP video destination port number */
  8734. int tportno = -1; /*!< RTP text destination port number */
  8735. int udptlportno = -1; /*!< UDPTL image destination port number */
  8736. /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
  8737. struct ast_format_cap *peercapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  8738. struct ast_format_cap *vpeercapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  8739. struct ast_format_cap *tpeercapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  8740. int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
  8741. struct ast_rtp_codecs newaudiortp = AST_RTP_CODECS_NULL_INIT;
  8742. struct ast_rtp_codecs newvideortp = AST_RTP_CODECS_NULL_INIT;
  8743. struct ast_rtp_codecs newtextrtp = AST_RTP_CODECS_NULL_INIT;
  8744. struct ast_format_cap *newjointcapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT); /* Negotiated capability */
  8745. struct ast_format_cap *newpeercapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  8746. int newnoncodeccapability;
  8747. const char *codecs;
  8748. unsigned int codec;
  8749. /* SRTP */
  8750. int secure_audio = FALSE;
  8751. int secure_video = FALSE;
  8752. /* Others */
  8753. int sendonly = -1;
  8754. unsigned int numberofports;
  8755. int last_rtpmap_codec = 0;
  8756. int red_data_pt[10]; /* For T.140 RED */
  8757. int red_num_gen = 0; /* For T.140 RED */
  8758. char red_fmtp[100] = "empty"; /* For T.140 RED */
  8759. int debug = sip_debug_test_pvt(p);
  8760. /* START UNKNOWN */
  8761. struct ast_str *codec_buf = ast_str_alloca(64);
  8762. struct ast_format *tmp_fmt;
  8763. /* END UNKNOWN */
  8764. /* Initial check */
  8765. if (!p->rtp) {
  8766. ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
  8767. res = -1;
  8768. goto process_sdp_cleanup;
  8769. }
  8770. if (!peercapability || !vpeercapability || !tpeercapability || !newpeercapability || !newjointcapability) {
  8771. res = -1;
  8772. goto process_sdp_cleanup;
  8773. }
  8774. if (ast_rtp_codecs_payloads_initialize(&newaudiortp) || ast_rtp_codecs_payloads_initialize(&newvideortp) ||
  8775. ast_rtp_codecs_payloads_initialize(&newtextrtp)) {
  8776. res = -1;
  8777. goto process_sdp_cleanup;
  8778. }
  8779. /* Update our last rtprx when we receive an SDP, too */
  8780. p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
  8781. offered_media_list_destroy(p);
  8782. /* Scan for the first media stream (m=) line to limit scanning of globals */
  8783. nextm = get_sdp_iterate(&next, req, "m");
  8784. if (ast_strlen_zero(nextm)) {
  8785. ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
  8786. res = -1;
  8787. goto process_sdp_cleanup;
  8788. }
  8789. /* Scan session level SDP parameters (lines before first media stream) */
  8790. while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
  8791. int processed = FALSE;
  8792. switch (type) {
  8793. case 'o':
  8794. /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
  8795. * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
  8796. */
  8797. if (!process_sdp_o(value, p)) {
  8798. res = (p->session_modify == FALSE) ? 0 : -1;
  8799. goto process_sdp_cleanup;
  8800. }
  8801. processed = TRUE;
  8802. break;
  8803. case 'c':
  8804. if (process_sdp_c(value, &sessionsa)) {
  8805. processed = TRUE;
  8806. sa = &sessionsa;
  8807. vsa = sa;
  8808. tsa = sa;
  8809. isa = sa;
  8810. }
  8811. break;
  8812. case 'a':
  8813. if (process_sdp_a_sendonly(value, &sendonly)) {
  8814. processed = TRUE;
  8815. }
  8816. else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
  8817. processed = TRUE;
  8818. else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
  8819. processed = TRUE;
  8820. else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
  8821. processed = TRUE;
  8822. else if (process_sdp_a_image(value, p))
  8823. processed = TRUE;
  8824. if (process_sdp_a_ice(value, p, p->rtp)) {
  8825. processed = TRUE;
  8826. }
  8827. if (process_sdp_a_ice(value, p, p->vrtp)) {
  8828. processed = TRUE;
  8829. }
  8830. if (process_sdp_a_ice(value, p, p->trtp)) {
  8831. processed = TRUE;
  8832. }
  8833. if (process_sdp_a_dtls(value, p, p->rtp)) {
  8834. processed = TRUE;
  8835. if (p->srtp) {
  8836. ast_set_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK);
  8837. }
  8838. }
  8839. if (process_sdp_a_dtls(value, p, p->vrtp)) {
  8840. processed = TRUE;
  8841. if (p->vsrtp) {
  8842. ast_set_flag(p->vsrtp, AST_SRTP_CRYPTO_OFFER_OK);
  8843. }
  8844. }
  8845. if (process_sdp_a_dtls(value, p, p->trtp)) {
  8846. processed = TRUE;
  8847. if (p->tsrtp) {
  8848. ast_set_flag(p->tsrtp, AST_SRTP_CRYPTO_OFFER_OK);
  8849. }
  8850. }
  8851. break;
  8852. }
  8853. ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
  8854. }
  8855. /* default: novideo and notext set */
  8856. p->novideo = TRUE;
  8857. p->notext = TRUE;
  8858. /* Scan media stream (m=) specific parameters loop */
  8859. while (!ast_strlen_zero(nextm)) {
  8860. int audio = FALSE;
  8861. int video = FALSE;
  8862. int image = FALSE;
  8863. int text = FALSE;
  8864. int processed_crypto = FALSE;
  8865. char protocol[18] = {0,};
  8866. unsigned int x;
  8867. struct ast_rtp_engine_dtls *dtls;
  8868. numberofports = 0;
  8869. len = -1;
  8870. start = next;
  8871. m = nextm;
  8872. iterator = next;
  8873. nextm = get_sdp_iterate(&next, req, "m");
  8874. if (!(offer = ast_calloc(1, sizeof(*offer)))) {
  8875. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer list\n");
  8876. res = -1;
  8877. goto process_sdp_cleanup;
  8878. }
  8879. AST_LIST_INSERT_TAIL(&p->offered_media, offer, next);
  8880. offer->type = SDP_UNKNOWN;
  8881. /* Check for 'audio' media offer */
  8882. if (strncmp(m, "audio ", 6) == 0) {
  8883. if ((sscanf(m, "audio %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
  8884. (sscanf(m, "audio %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
  8885. codecs = m + len;
  8886. /* produce zero-port m-line since it may be needed later
  8887. * length is "m=audio 0 " + protocol + " " + codecs + "\r\n\0" */
  8888. if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
  8889. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  8890. res = -1;
  8891. goto process_sdp_cleanup;
  8892. }
  8893. /* guaranteed to be exactly the right length */
  8894. sprintf(offer->decline_m_line, "m=audio 0 %s %s\r\n", protocol, codecs);
  8895. if (x == 0) {
  8896. ast_debug(1, "Ignoring audio media offer because port number is zero\n");
  8897. continue;
  8898. }
  8899. if (has_media_stream(p, SDP_AUDIO)) {
  8900. ast_log(LOG_WARNING, "Declining non-primary audio stream: %s\n", m);
  8901. continue;
  8902. }
  8903. /* Check number of ports offered for stream */
  8904. if (numberofports > 1) {
  8905. ast_log(LOG_WARNING, "%u ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
  8906. }
  8907. if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  8908. if (req->method != SIP_RESPONSE) {
  8909. ast_log(LOG_NOTICE, "Received SAVPF profle in audio offer but AVPF is not enabled, enabling: %s\n", m);
  8910. secure_audio = 1;
  8911. ast_set_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
  8912. }
  8913. else {
  8914. ast_log(LOG_WARNING, "Received SAVPF profle in audio answer but AVPF is not enabled: %s\n", m);
  8915. continue;
  8916. }
  8917. } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  8918. if (req->method != SIP_RESPONSE) {
  8919. ast_log(LOG_NOTICE, "Received SAVP profle in audio offer but AVPF is enabled, disabling: %s\n", m);
  8920. secure_audio = 1;
  8921. ast_clear_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
  8922. }
  8923. else {
  8924. ast_log(LOG_WARNING, "Received SAVP profile in audio offer but AVPF is enabled: %s\n", m);
  8925. continue;
  8926. }
  8927. } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
  8928. secure_audio = 1;
  8929. processed_crypto = 1;
  8930. if (p->srtp) {
  8931. ast_set_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK);
  8932. }
  8933. } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
  8934. secure_audio = 1;
  8935. } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  8936. if (req->method != SIP_RESPONSE) {
  8937. ast_log(LOG_NOTICE, "Received AVPF profile in audio offer but AVPF is not enabled, enabling: %s\n", m);
  8938. ast_set_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
  8939. }
  8940. else {
  8941. ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
  8942. continue;
  8943. }
  8944. } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  8945. if (req->method != SIP_RESPONSE) {
  8946. ast_log(LOG_NOTICE, "Received AVP profile in audio answer but AVPF is enabled, disabling: %s\n", m);
  8947. ast_clear_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
  8948. }
  8949. else {
  8950. ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
  8951. continue;
  8952. }
  8953. } else if ((!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) &&
  8954. (!(dtls = ast_rtp_instance_get_dtls(p->rtp)) || !dtls->active(p->rtp))) {
  8955. ast_log(LOG_WARNING, "Received UDP/TLS in audio offer but DTLS is not enabled: %s\n", m);
  8956. continue;
  8957. } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
  8958. ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
  8959. continue;
  8960. }
  8961. audio = TRUE;
  8962. offer->type = SDP_AUDIO;
  8963. portno = x;
  8964. /* Scan through the RTP payload types specified in a "m=" line: */
  8965. for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
  8966. if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
  8967. ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
  8968. res = -1;
  8969. goto process_sdp_cleanup;
  8970. }
  8971. if (debug) {
  8972. ast_verbose("Found RTP audio format %u\n", codec);
  8973. }
  8974. ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
  8975. }
  8976. } else {
  8977. ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
  8978. res = -1;
  8979. goto process_sdp_cleanup;
  8980. }
  8981. }
  8982. /* Check for 'video' media offer */
  8983. else if (strncmp(m, "video ", 6) == 0) {
  8984. if ((sscanf(m, "video %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
  8985. (sscanf(m, "video %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
  8986. codecs = m + len;
  8987. /* produce zero-port m-line since it may be needed later
  8988. * length is "m=video 0 " + protocol + " " + codecs + "\r\n\0" */
  8989. if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
  8990. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  8991. res = -1;
  8992. goto process_sdp_cleanup;
  8993. }
  8994. /* guaranteed to be exactly the right length */
  8995. sprintf(offer->decline_m_line, "m=video 0 %s %s\r\n", protocol, codecs);
  8996. if (x == 0) {
  8997. ast_debug(1, "Ignoring video stream offer because port number is zero\n");
  8998. continue;
  8999. }
  9000. /* Check number of ports offered for stream */
  9001. if (numberofports > 1) {
  9002. ast_log(LOG_WARNING, "%u ports offered for video stream, not supported by Asterisk. Will try anyway...\n", numberofports);
  9003. }
  9004. if (has_media_stream(p, SDP_VIDEO)) {
  9005. ast_log(LOG_WARNING, "Declining non-primary video stream: %s\n", m);
  9006. continue;
  9007. }
  9008. if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9009. ast_log(LOG_WARNING, "Received SAVPF profle in video offer but AVPF is not enabled: %s\n", m);
  9010. continue;
  9011. } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9012. ast_log(LOG_WARNING, "Received SAVP profile in video offer but AVPF is enabled: %s\n", m);
  9013. continue;
  9014. } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
  9015. secure_video = 1;
  9016. processed_crypto = 1;
  9017. if (p->vsrtp || (p->vsrtp = ast_sdp_srtp_alloc())) {
  9018. ast_set_flag(p->vsrtp, AST_SRTP_CRYPTO_OFFER_OK);
  9019. }
  9020. } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
  9021. secure_video = 1;
  9022. } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9023. ast_log(LOG_WARNING, "Received AVPF profile in video offer but AVPF is not enabled: %s\n", m);
  9024. continue;
  9025. } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9026. ast_log(LOG_WARNING, "Received AVP profile in video offer but AVPF is enabled: %s\n", m);
  9027. continue;
  9028. } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
  9029. ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
  9030. continue;
  9031. }
  9032. video = TRUE;
  9033. p->novideo = FALSE;
  9034. offer->type = SDP_VIDEO;
  9035. vportno = x;
  9036. /* Scan through the RTP payload types specified in a "m=" line: */
  9037. for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
  9038. if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
  9039. ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
  9040. res = -1;
  9041. goto process_sdp_cleanup;
  9042. }
  9043. if (debug) {
  9044. ast_verbose("Found RTP video format %u\n", codec);
  9045. }
  9046. ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
  9047. }
  9048. } else {
  9049. ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
  9050. res = -1;
  9051. goto process_sdp_cleanup;
  9052. }
  9053. }
  9054. /* Check for 'text' media offer */
  9055. else if (strncmp(m, "text ", 5) == 0) {
  9056. if ((sscanf(m, "text %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
  9057. (sscanf(m, "text %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
  9058. codecs = m + len;
  9059. /* produce zero-port m-line since it may be needed later
  9060. * length is "m=text 0 " + protocol + " " + codecs + "\r\n\0" */
  9061. if (!(offer->decline_m_line = ast_malloc(9 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
  9062. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  9063. res = -1;
  9064. goto process_sdp_cleanup;
  9065. }
  9066. /* guaranteed to be exactly the right length */
  9067. sprintf(offer->decline_m_line, "m=text 0 %s %s\r\n", protocol, codecs);
  9068. if (x == 0) {
  9069. ast_debug(1, "Ignoring text stream offer because port number is zero\n");
  9070. continue;
  9071. }
  9072. /* Check number of ports offered for stream */
  9073. if (numberofports > 1) {
  9074. ast_log(LOG_WARNING, "%u ports offered for text stream, not supported by Asterisk. Will try anyway...\n", numberofports);
  9075. }
  9076. if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9077. ast_log(LOG_WARNING, "Received AVPF profile in text offer but AVPF is not enabled: %s\n", m);
  9078. continue;
  9079. } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9080. ast_log(LOG_WARNING, "Received AVP profile in text offer but AVPF is enabled: %s\n", m);
  9081. continue;
  9082. } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
  9083. ast_log(LOG_WARNING, "Unknown RTP profile in text offer: %s\n", m);
  9084. continue;
  9085. }
  9086. if (has_media_stream(p, SDP_TEXT)) {
  9087. ast_log(LOG_WARNING, "Declining non-primary text stream: %s\n", m);
  9088. continue;
  9089. }
  9090. text = TRUE;
  9091. p->notext = FALSE;
  9092. offer->type = SDP_TEXT;
  9093. tportno = x;
  9094. /* Scan through the RTP payload types specified in a "m=" line: */
  9095. for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
  9096. if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
  9097. ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
  9098. res = -1;
  9099. goto process_sdp_cleanup;
  9100. }
  9101. if (debug) {
  9102. ast_verbose("Found RTP text format %u\n", codec);
  9103. }
  9104. ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
  9105. }
  9106. } else {
  9107. ast_log(LOG_WARNING, "Rejecting text stream offer due to invalid or unsupported syntax: %s\n", m);
  9108. res = -1;
  9109. goto process_sdp_cleanup;
  9110. }
  9111. }
  9112. /* Check for 'image' media offer */
  9113. else if (strncmp(m, "image ", 6) == 0) {
  9114. if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
  9115. (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
  9116. /* produce zero-port m-line since it may be needed later
  9117. * length is "m=image 0 udptl t38" + "\r\n\0" */
  9118. if (!(offer->decline_m_line = ast_malloc(22))) {
  9119. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  9120. res = -1;
  9121. goto process_sdp_cleanup;
  9122. }
  9123. /* guaranteed to be exactly the right length */
  9124. strcpy(offer->decline_m_line, "m=image 0 udptl t38\r\n");
  9125. if (x == 0) {
  9126. ast_debug(1, "Ignoring image stream offer because port number is zero\n");
  9127. continue;
  9128. }
  9129. if (initialize_udptl(p)) {
  9130. ast_log(LOG_WARNING, "Failed to initialize UDPTL, declining image stream\n");
  9131. continue;
  9132. }
  9133. if (has_media_stream(p, SDP_IMAGE)) {
  9134. ast_log(LOG_WARNING, "Declining non-primary image stream: %s\n", m);
  9135. continue;
  9136. }
  9137. image = TRUE;
  9138. if (debug) {
  9139. ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
  9140. }
  9141. offer->type = SDP_IMAGE;
  9142. udptlportno = x;
  9143. if (p->t38.state != T38_ENABLED) {
  9144. memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
  9145. /* default EC to none, the remote end should
  9146. * respond with the EC they want to use */
  9147. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
  9148. }
  9149. } else if (sscanf(m, "image %30u %17s t38%n", &x, protocol, &len) == 2 && len > 0) {
  9150. ast_log(LOG_WARNING, "Declining image stream due to unsupported transport: %s\n", m);
  9151. /* produce zero-port m-line since this is guaranteed to be declined
  9152. * length is "m=image 0 strlen(protocol) t38" + "\r\n\0" */
  9153. if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 7))) {
  9154. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  9155. res = -1;
  9156. goto process_sdp_cleanup;
  9157. }
  9158. /* guaranteed to be exactly the right length */
  9159. sprintf(offer->decline_m_line, "m=image 0 %s t38\r\n", protocol);
  9160. continue;
  9161. } else {
  9162. ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
  9163. res = -1;
  9164. goto process_sdp_cleanup;
  9165. }
  9166. } else {
  9167. char type[20] = {0,};
  9168. if ((sscanf(m, "%19s %30u/%30u %n", type, &x, &numberofports, &len) == 3 && len > 0) ||
  9169. (sscanf(m, "%19s %30u %n", type, &x, &len) == 2 && len > 0)) {
  9170. /* produce zero-port m-line since it may be needed later
  9171. * length is "m=" + type + " 0 " + remainder + "\r\n\0" */
  9172. if (!(offer->decline_m_line = ast_malloc(2 + strlen(type) + 3 + strlen(m + len) + 3))) {
  9173. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  9174. res = -1;
  9175. goto process_sdp_cleanup;
  9176. }
  9177. /* guaranteed to be long enough */
  9178. sprintf(offer->decline_m_line, "m=%s 0 %s\r\n", type, m + len);
  9179. continue;
  9180. } else {
  9181. ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
  9182. res = -1;
  9183. goto process_sdp_cleanup;
  9184. }
  9185. }
  9186. /* Media stream specific parameters */
  9187. while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
  9188. int processed = FALSE;
  9189. switch (type) {
  9190. case 'c':
  9191. if (audio) {
  9192. if (process_sdp_c(value, &audiosa)) {
  9193. processed = TRUE;
  9194. sa = &audiosa;
  9195. }
  9196. } else if (video) {
  9197. if (process_sdp_c(value, &videosa)) {
  9198. processed = TRUE;
  9199. vsa = &videosa;
  9200. }
  9201. } else if (text) {
  9202. if (process_sdp_c(value, &textsa)) {
  9203. processed = TRUE;
  9204. tsa = &textsa;
  9205. }
  9206. } else if (image) {
  9207. if (process_sdp_c(value, &imagesa)) {
  9208. processed = TRUE;
  9209. isa = &imagesa;
  9210. }
  9211. }
  9212. break;
  9213. case 'a':
  9214. /* Audio specific scanning */
  9215. if (audio) {
  9216. if (process_sdp_a_ice(value, p, p->rtp)) {
  9217. processed = TRUE;
  9218. } else if (process_sdp_a_dtls(value, p, p->rtp)) {
  9219. processed_crypto = TRUE;
  9220. processed = TRUE;
  9221. if (p->srtp) {
  9222. ast_set_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK);
  9223. }
  9224. } else if (process_sdp_a_sendonly(value, &sendonly)) {
  9225. processed = TRUE;
  9226. } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
  9227. processed_crypto = TRUE;
  9228. processed = TRUE;
  9229. } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
  9230. processed = TRUE;
  9231. }
  9232. }
  9233. /* Video specific scanning */
  9234. else if (video) {
  9235. if (process_sdp_a_ice(value, p, p->vrtp)) {
  9236. processed = TRUE;
  9237. } else if (process_sdp_a_dtls(value, p, p->vrtp)) {
  9238. processed_crypto = TRUE;
  9239. processed = TRUE;
  9240. if (p->vsrtp) {
  9241. ast_set_flag(p->vsrtp, AST_SRTP_CRYPTO_OFFER_OK);
  9242. }
  9243. } else if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
  9244. processed_crypto = TRUE;
  9245. processed = TRUE;
  9246. } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
  9247. processed = TRUE;
  9248. }
  9249. }
  9250. /* Text (T.140) specific scanning */
  9251. else if (text) {
  9252. if (process_sdp_a_ice(value, p, p->trtp)) {
  9253. processed = TRUE;
  9254. } else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
  9255. processed = TRUE;
  9256. } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
  9257. processed_crypto = TRUE;
  9258. processed = TRUE;
  9259. }
  9260. }
  9261. /* Image (T.38 FAX) specific scanning */
  9262. else if (image) {
  9263. if (process_sdp_a_image(value, p))
  9264. processed = TRUE;
  9265. }
  9266. break;
  9267. }
  9268. ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
  9269. (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
  9270. type, value,
  9271. (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
  9272. }
  9273. /* Ensure crypto lines are provided where necessary */
  9274. if (audio && secure_audio && !processed_crypto) {
  9275. ast_log(LOG_WARNING, "Rejecting secure audio stream without encryption details: %s\n", m);
  9276. res = -1;
  9277. goto process_sdp_cleanup;
  9278. } else if (video && secure_video && !processed_crypto) {
  9279. ast_log(LOG_WARNING, "Rejecting secure video stream without encryption details: %s\n", m);
  9280. res = -1;
  9281. goto process_sdp_cleanup;
  9282. }
  9283. }
  9284. /* Sanity checks */
  9285. if (!sa && !vsa && !tsa && !isa) {
  9286. ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
  9287. res = -1;
  9288. goto process_sdp_cleanup;
  9289. }
  9290. if ((portno == -1) &&
  9291. (vportno == -1) &&
  9292. (tportno == -1) &&
  9293. (udptlportno == -1)) {
  9294. ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
  9295. res = -1;
  9296. goto process_sdp_cleanup;
  9297. }
  9298. if (p->srtp && p->udptl && udptlportno != -1) {
  9299. ast_debug(1, "Terminating SRTP due to T.38 UDPTL\n");
  9300. ast_sdp_srtp_destroy(p->srtp);
  9301. p->srtp = NULL;
  9302. }
  9303. if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK)))) {
  9304. ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
  9305. res = -1;
  9306. goto process_sdp_cleanup;
  9307. }
  9308. if (!secure_audio && p->srtp) {
  9309. ast_log(LOG_WARNING, "Failed to receive SDP offer/answer with required SRTP crypto attributes for audio\n");
  9310. res = -1;
  9311. goto process_sdp_cleanup;
  9312. }
  9313. if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, AST_SRTP_CRYPTO_OFFER_OK)))) {
  9314. ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
  9315. res = -1;
  9316. goto process_sdp_cleanup;
  9317. }
  9318. if (!p->novideo && !secure_video && p->vsrtp) {
  9319. ast_log(LOG_WARNING, "Failed to receive SDP offer/answer with required SRTP crypto attributes for video\n");
  9320. res = -1;
  9321. goto process_sdp_cleanup;
  9322. }
  9323. if (!(secure_audio || secure_video || (p->udptl && udptlportno != -1)) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
  9324. ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
  9325. res = -1;
  9326. goto process_sdp_cleanup;
  9327. }
  9328. if (udptlportno == -1) {
  9329. change_t38_state(p, T38_DISABLED);
  9330. }
  9331. /* Now gather all of the codecs that we are asked for: */
  9332. ast_rtp_codecs_payload_formats(&newaudiortp, peercapability, &peernoncodeccapability);
  9333. ast_rtp_codecs_payload_formats(&newvideortp, vpeercapability, &vpeernoncodeccapability);
  9334. ast_rtp_codecs_payload_formats(&newtextrtp, tpeercapability, &tpeernoncodeccapability);
  9335. ast_format_cap_append_from_cap(newpeercapability, peercapability, AST_MEDIA_TYPE_AUDIO);
  9336. ast_format_cap_append_from_cap(newpeercapability, vpeercapability, AST_MEDIA_TYPE_VIDEO);
  9337. ast_format_cap_append_from_cap(newpeercapability, tpeercapability, AST_MEDIA_TYPE_TEXT);
  9338. ast_format_cap_get_compatible(p->caps, newpeercapability, newjointcapability);
  9339. if (!ast_format_cap_count(newjointcapability) && udptlportno == -1) {
  9340. ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
  9341. /* Do NOT Change current setting */
  9342. res = -1;
  9343. goto process_sdp_cleanup;
  9344. }
  9345. newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
  9346. if (debug) {
  9347. /* shame on whoever coded this.... */
  9348. struct ast_str *cap_buf = ast_str_alloca(64);
  9349. struct ast_str *peer_buf = ast_str_alloca(64);
  9350. struct ast_str *vpeer_buf = ast_str_alloca(64);
  9351. struct ast_str *tpeer_buf = ast_str_alloca(64);
  9352. struct ast_str *joint_buf = ast_str_alloca(64);
  9353. ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
  9354. ast_format_cap_get_names(p->caps, &cap_buf),
  9355. ast_format_cap_get_names(peercapability, &peer_buf),
  9356. ast_format_cap_get_names(vpeercapability, &vpeer_buf),
  9357. ast_format_cap_get_names(tpeercapability, &tpeer_buf),
  9358. ast_format_cap_get_names(newjointcapability, &joint_buf));
  9359. }
  9360. if (debug) {
  9361. struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
  9362. struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
  9363. struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
  9364. ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
  9365. ast_rtp_lookup_mime_multiple2(s1, NULL, p->noncodeccapability, 0, 0),
  9366. ast_rtp_lookup_mime_multiple2(s2, NULL, peernoncodeccapability, 0, 0),
  9367. ast_rtp_lookup_mime_multiple2(s3, NULL, newnoncodeccapability, 0, 0));
  9368. }
  9369. if (portno != -1 || vportno != -1 || tportno != -1) {
  9370. /* We are now ready to change the sip session and RTP structures with the offered codecs, since
  9371. they are acceptable */
  9372. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  9373. ast_format_cap_append_from_cap(p->jointcaps, newjointcapability, AST_MEDIA_TYPE_UNKNOWN); /* Our joint codec profile for this call */
  9374. ast_format_cap_remove_by_type(p->peercaps, AST_MEDIA_TYPE_UNKNOWN);
  9375. ast_format_cap_append_from_cap(p->peercaps, newpeercapability, AST_MEDIA_TYPE_UNKNOWN); /* The other side's capability in latest offer */
  9376. p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
  9377. /* respond with single most preferred joint codec, limiting the other side's choice */
  9378. if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
  9379. unsigned int framing;
  9380. tmp_fmt = ast_format_cap_get_format(p->jointcaps, 0);
  9381. framing = ast_format_cap_get_format_framing(p->jointcaps, tmp_fmt);
  9382. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  9383. ast_format_cap_append(p->jointcaps, tmp_fmt, framing);
  9384. ao2_ref(tmp_fmt, -1);
  9385. }
  9386. }
  9387. /* Setup audio address and port */
  9388. if (p->rtp) {
  9389. if (sa && portno > 0) {
  9390. start_ice(p->rtp, (req->method != SIP_RESPONSE) ? 0 : 1);
  9391. ast_sockaddr_set_port(sa, portno);
  9392. ast_rtp_instance_set_remote_address(p->rtp, sa);
  9393. if (debug) {
  9394. ast_verbose("Peer audio RTP is at port %s\n",
  9395. ast_sockaddr_stringify(sa));
  9396. }
  9397. ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
  9398. /* Ensure RTCP is enabled since it may be inactive
  9399. if we're coming back from a T.38 session */
  9400. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
  9401. /* Ensure audio RTCP reads are enabled */
  9402. if (p->owner) {
  9403. ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
  9404. }
  9405. if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
  9406. ast_clear_flag(&p->flags[0], SIP_DTMF);
  9407. if (newnoncodeccapability & AST_RTP_DTMF) {
  9408. /* XXX Would it be reasonable to drop the DSP at this point? XXX */
  9409. ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
  9410. /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
  9411. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
  9412. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  9413. } else {
  9414. ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
  9415. }
  9416. }
  9417. } else if (udptlportno > 0) {
  9418. if (debug)
  9419. ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
  9420. /* Prevent audio RTCP reads */
  9421. if (p->owner) {
  9422. ast_channel_set_fd(p->owner, 1, -1);
  9423. }
  9424. /* Silence RTCP while audio RTP is inactive */
  9425. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
  9426. } else {
  9427. ast_rtp_instance_stop(p->rtp);
  9428. if (debug)
  9429. ast_verbose("Peer doesn't provide audio\n");
  9430. }
  9431. }
  9432. /* Setup video address and port */
  9433. if (p->vrtp) {
  9434. if (vsa && vportno > 0) {
  9435. start_ice(p->vrtp, (req->method != SIP_RESPONSE) ? 0 : 1);
  9436. ast_sockaddr_set_port(vsa, vportno);
  9437. ast_rtp_instance_set_remote_address(p->vrtp, vsa);
  9438. if (debug) {
  9439. ast_verbose("Peer video RTP is at port %s\n",
  9440. ast_sockaddr_stringify(vsa));
  9441. }
  9442. ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
  9443. } else {
  9444. ast_rtp_instance_stop(p->vrtp);
  9445. if (debug)
  9446. ast_verbose("Peer doesn't provide video\n");
  9447. }
  9448. }
  9449. /* Setup text address and port */
  9450. if (p->trtp) {
  9451. if (tsa && tportno > 0) {
  9452. start_ice(p->trtp, (req->method != SIP_RESPONSE) ? 0 : 1);
  9453. ast_sockaddr_set_port(tsa, tportno);
  9454. ast_rtp_instance_set_remote_address(p->trtp, tsa);
  9455. if (debug) {
  9456. ast_verbose("Peer T.140 RTP is at port %s\n",
  9457. ast_sockaddr_stringify(tsa));
  9458. }
  9459. if (ast_format_cap_iscompatible_format(p->jointcaps, ast_format_t140_red) != AST_FORMAT_CMP_NOT_EQUAL) {
  9460. p->red = 1;
  9461. ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
  9462. } else {
  9463. p->red = 0;
  9464. }
  9465. ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
  9466. } else {
  9467. ast_rtp_instance_stop(p->trtp);
  9468. if (debug)
  9469. ast_verbose("Peer doesn't provide T.140\n");
  9470. }
  9471. }
  9472. /* Setup image address and port */
  9473. if (p->udptl) {
  9474. if (isa && udptlportno > 0) {
  9475. if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
  9476. ast_rtp_instance_get_remote_address(p->rtp, isa);
  9477. if (!ast_sockaddr_isnull(isa) && debug) {
  9478. ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
  9479. }
  9480. }
  9481. ast_sockaddr_set_port(isa, udptlportno);
  9482. ast_udptl_set_peer(p->udptl, isa);
  9483. if (debug)
  9484. ast_debug(1, "Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
  9485. /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
  9486. if (!ast_udptl_get_far_max_datagram(p->udptl)) {
  9487. /* setting to zero will force a default if none was provided by the SDP */
  9488. ast_udptl_set_far_max_datagram(p->udptl, 0);
  9489. }
  9490. /* Remote party offers T38, we need to update state */
  9491. if ((t38action == SDP_T38_ACCEPT) &&
  9492. (p->t38.state == T38_LOCAL_REINVITE)) {
  9493. change_t38_state(p, T38_ENABLED);
  9494. } else if ((t38action == SDP_T38_INITIATE) &&
  9495. p->owner && p->lastinvite) {
  9496. change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
  9497. /* If fax detection is enabled then send us off to the fax extension */
  9498. if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
  9499. ast_channel_lock(p->owner);
  9500. if (strcmp(ast_channel_exten(p->owner), "fax")) {
  9501. const char *target_context = S_OR(ast_channel_macrocontext(p->owner), ast_channel_context(p->owner));
  9502. ast_channel_unlock(p->owner);
  9503. if (ast_exists_extension(p->owner, target_context, "fax", 1,
  9504. S_COR(ast_channel_caller(p->owner)->id.number.valid, ast_channel_caller(p->owner)->id.number.str, NULL))) {
  9505. ast_verb(2, "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", ast_channel_name(p->owner));
  9506. pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", ast_channel_exten(p->owner));
  9507. if (ast_async_goto(p->owner, target_context, "fax", 1)) {
  9508. ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(p->owner), target_context);
  9509. }
  9510. } else {
  9511. ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
  9512. }
  9513. } else {
  9514. ast_channel_unlock(p->owner);
  9515. }
  9516. }
  9517. }
  9518. } else {
  9519. change_t38_state(p, T38_DISABLED);
  9520. ast_udptl_stop(p->udptl);
  9521. if (debug)
  9522. ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
  9523. }
  9524. }
  9525. if ((portno == -1) && (p->t38.state != T38_DISABLED) && (p->t38.state != T38_REJECTED)) {
  9526. ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
  9527. res = 0;
  9528. goto process_sdp_cleanup;
  9529. }
  9530. /* Ok, we're going with this offer */
  9531. ast_debug(2, "We're settling with these formats: %s\n", ast_format_cap_get_names(p->jointcaps, &codec_buf));
  9532. if (!p->owner) { /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
  9533. res = 0;
  9534. goto process_sdp_cleanup;
  9535. }
  9536. ast_debug(4, "We have an owner, now see if we need to change this call\n");
  9537. if (ast_format_cap_has_type(p->jointcaps, AST_MEDIA_TYPE_AUDIO)) {
  9538. struct ast_format_cap *caps;
  9539. unsigned int framing;
  9540. if (debug) {
  9541. struct ast_str *cap_buf = ast_str_alloca(64);
  9542. struct ast_str *joint_buf = ast_str_alloca(64);
  9543. ast_debug(1, "Setting native formats after processing SDP. peer joint formats %s, old nativeformats %s\n",
  9544. ast_format_cap_get_names(p->jointcaps, &joint_buf),
  9545. ast_format_cap_get_names(ast_channel_nativeformats(p->owner), &cap_buf));
  9546. }
  9547. caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  9548. if (caps) {
  9549. tmp_fmt = ast_format_cap_get_format(p->jointcaps, 0);
  9550. framing = ast_format_cap_get_format_framing(p->jointcaps, tmp_fmt);
  9551. ast_format_cap_append(caps, tmp_fmt, framing);
  9552. ast_format_cap_append_from_cap(caps, vpeercapability, AST_MEDIA_TYPE_VIDEO);
  9553. ast_format_cap_append_from_cap(caps, tpeercapability, AST_MEDIA_TYPE_TEXT);
  9554. ast_channel_nativeformats_set(p->owner, caps);
  9555. ao2_ref(caps, -1);
  9556. ao2_ref(tmp_fmt, -1);
  9557. }
  9558. ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
  9559. ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
  9560. }
  9561. if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && (!ast_sockaddr_isnull(sa) || !ast_sockaddr_isnull(vsa) || !ast_sockaddr_isnull(tsa) || !ast_sockaddr_isnull(isa)) && (!sendonly || sendonly == -1)) {
  9562. if (!ast_test_flag(&p->flags[2], SIP_PAGE3_DISCARD_REMOTE_HOLD_RETRIEVAL)) {
  9563. ast_queue_unhold(p->owner);
  9564. }
  9565. /* Activate a re-invite */
  9566. ast_queue_frame(p->owner, &ast_null_frame);
  9567. change_hold_state(p, req, FALSE, sendonly);
  9568. } else if ((sockaddr_is_null_or_any(sa) && sockaddr_is_null_or_any(vsa) && sockaddr_is_null_or_any(tsa) && sockaddr_is_null_or_any(isa)) || (sendonly && sendonly != -1)) {
  9569. if (!ast_test_flag(&p->flags[2], SIP_PAGE3_DISCARD_REMOTE_HOLD_RETRIEVAL)) {
  9570. ast_queue_hold(p->owner, p->mohsuggest);
  9571. }
  9572. if (sendonly)
  9573. ast_rtp_instance_stop(p->rtp);
  9574. /* RTCP needs to go ahead, even if we're on hold!!! */
  9575. /* Activate a re-invite */
  9576. ast_queue_frame(p->owner, &ast_null_frame);
  9577. change_hold_state(p, req, TRUE, sendonly);
  9578. }
  9579. process_sdp_cleanup:
  9580. if (res) {
  9581. offered_media_list_destroy(p);
  9582. }
  9583. ast_rtp_codecs_payloads_destroy(&newtextrtp);
  9584. ast_rtp_codecs_payloads_destroy(&newvideortp);
  9585. ast_rtp_codecs_payloads_destroy(&newaudiortp);
  9586. ao2_cleanup(peercapability);
  9587. ao2_cleanup(vpeercapability);
  9588. ao2_cleanup(tpeercapability);
  9589. ao2_cleanup(newjointcapability);
  9590. ao2_cleanup(newpeercapability);
  9591. return res;
  9592. }
  9593. static int process_sdp_o(const char *o, struct sip_pvt *p)
  9594. {
  9595. char *o_copy;
  9596. char *token;
  9597. int64_t rua_version;
  9598. /* Store the SDP version number of remote UA. This will allow us to
  9599. distinguish between session modifications and session refreshes. If
  9600. the remote UA does not send an incremented SDP version number in a
  9601. subsequent RE-INVITE then that means its not changing media session.
  9602. The RE-INVITE may have been sent to update connected party, remote
  9603. target or to refresh the session (Session-Timers). Asterisk must not
  9604. change media session and increment its own version number in answer
  9605. SDP in this case. */
  9606. p->session_modify = TRUE;
  9607. if (ast_strlen_zero(o)) {
  9608. ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
  9609. return FALSE;
  9610. }
  9611. o_copy = ast_strdupa(o);
  9612. token = strsep(&o_copy, " "); /* Skip username */
  9613. if (!o_copy) {
  9614. ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
  9615. return FALSE;
  9616. }
  9617. token = strsep(&o_copy, " "); /* Skip session-id */
  9618. if (!o_copy) {
  9619. ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
  9620. return FALSE;
  9621. }
  9622. token = strsep(&o_copy, " "); /* Version */
  9623. if (!o_copy) {
  9624. ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
  9625. return FALSE;
  9626. }
  9627. if (!sscanf(token, "%30" SCNd64, &rua_version)) {
  9628. ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
  9629. return FALSE;
  9630. }
  9631. /* we need to check the SDP version number the other end sent us;
  9632. * our rules for deciding what to accept are a bit complex.
  9633. *
  9634. * 1) if 'ignoresdpversion' has been set for this dialog, then
  9635. * we will just accept whatever they sent and assume it is
  9636. * a modification of the session, even if it is not
  9637. * 2) otherwise, if this is the first SDP we've seen from them
  9638. * we accept it
  9639. * 3) otherwise, if the new SDP version number is higher than the
  9640. * old one, we accept it
  9641. * 4) otherwise, if this SDP is in response to us requesting a switch
  9642. * to T.38, we accept the SDP, but also generate a warning message
  9643. * that this peer should have the 'ignoresdpversion' option set,
  9644. * because it is not following the SDP offer/answer RFC; if we did
  9645. * not request a switch to T.38, then we stop parsing the SDP, as it
  9646. * has not changed from the previous version
  9647. */
  9648. if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
  9649. (p->sessionversion_remote < 0) ||
  9650. (p->sessionversion_remote < rua_version)) {
  9651. p->sessionversion_remote = rua_version;
  9652. } else {
  9653. if (p->t38.state == T38_LOCAL_REINVITE) {
  9654. p->sessionversion_remote = rua_version;
  9655. ast_log(LOG_WARNING, "Call %s responded to our T.38 reinvite without changing SDP version; 'ignoresdpversion' should be set for this peer.\n", p->callid);
  9656. } else {
  9657. p->session_modify = FALSE;
  9658. ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
  9659. return FALSE;
  9660. }
  9661. }
  9662. return TRUE;
  9663. }
  9664. static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
  9665. {
  9666. char proto[4], host[258];
  9667. int af;
  9668. /* Check for Media-description-level-address */
  9669. if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
  9670. if (!strcmp("IP4", proto)) {
  9671. af = AF_INET;
  9672. } else if (!strcmp("IP6", proto)) {
  9673. af = AF_INET6;
  9674. } else {
  9675. ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
  9676. return FALSE;
  9677. }
  9678. if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
  9679. ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
  9680. return FALSE;
  9681. }
  9682. return TRUE;
  9683. } else {
  9684. ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
  9685. return FALSE;
  9686. }
  9687. return FALSE;
  9688. }
  9689. static int process_sdp_a_sendonly(const char *a, int *sendonly)
  9690. {
  9691. int found = FALSE;
  9692. if (!strcasecmp(a, "sendonly")) {
  9693. if (*sendonly == -1)
  9694. *sendonly = 1;
  9695. found = TRUE;
  9696. } else if (!strcasecmp(a, "inactive")) {
  9697. if (*sendonly == -1)
  9698. *sendonly = 2;
  9699. found = TRUE;
  9700. } else if (!strcasecmp(a, "sendrecv")) {
  9701. if (*sendonly == -1)
  9702. *sendonly = 0;
  9703. found = TRUE;
  9704. }
  9705. return found;
  9706. }
  9707. static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
  9708. {
  9709. struct ast_rtp_engine_ice *ice;
  9710. int found = FALSE;
  9711. char ufrag[256], pwd[256], foundation[32], transport[4], address[46], cand_type[6], relay_address[46] = "";
  9712. struct ast_rtp_engine_ice_candidate candidate = { 0, };
  9713. unsigned int port, relay_port = 0;
  9714. if (!instance || !(ice = ast_rtp_instance_get_ice(instance))) {
  9715. return found;
  9716. }
  9717. if (sscanf(a, "ice-ufrag: %255s", ufrag) == 1) {
  9718. ice->set_authentication(instance, ufrag, NULL);
  9719. found = TRUE;
  9720. } else if (sscanf(a, "ice-pwd: %255s", pwd) == 1) {
  9721. ice->set_authentication(instance, NULL, pwd);
  9722. found = TRUE;
  9723. } else if (sscanf(a, "candidate: %31s %30u %3s %30u %23s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport, (unsigned *)&candidate.priority,
  9724. address, &port, cand_type, relay_address, &relay_port) >= 7) {
  9725. candidate.foundation = foundation;
  9726. candidate.transport = transport;
  9727. ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
  9728. ast_sockaddr_set_port(&candidate.address, port);
  9729. if (!strcasecmp(cand_type, "host")) {
  9730. candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
  9731. } else if (!strcasecmp(cand_type, "srflx")) {
  9732. candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
  9733. } else if (!strcasecmp(cand_type, "relay")) {
  9734. candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
  9735. } else {
  9736. return found;
  9737. }
  9738. if (!ast_strlen_zero(relay_address)) {
  9739. ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
  9740. }
  9741. if (relay_port) {
  9742. ast_sockaddr_set_port(&candidate.relay_address, relay_port);
  9743. }
  9744. ice->add_remote_candidate(instance, &candidate);
  9745. found = TRUE;
  9746. } else if (!strcasecmp(a, "ice-lite")) {
  9747. ice->ice_lite(instance);
  9748. found = TRUE;
  9749. }
  9750. return found;
  9751. }
  9752. static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
  9753. {
  9754. struct ast_rtp_engine_dtls *dtls;
  9755. int found = FALSE;
  9756. char value[256], hash[32];
  9757. if (!instance || !p->dtls_cfg.enabled || !(dtls = ast_rtp_instance_get_dtls(instance))) {
  9758. return found;
  9759. }
  9760. if (sscanf(a, "setup: %255s", value) == 1) {
  9761. found = TRUE;
  9762. if (!strcasecmp(value, "active")) {
  9763. dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTIVE);
  9764. } else if (!strcasecmp(value, "passive")) {
  9765. dtls->set_setup(instance, AST_RTP_DTLS_SETUP_PASSIVE);
  9766. } else if (!strcasecmp(value, "actpass")) {
  9767. dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTPASS);
  9768. } else if (!strcasecmp(value, "holdconn")) {
  9769. dtls->set_setup(instance, AST_RTP_DTLS_SETUP_HOLDCONN);
  9770. } else {
  9771. ast_log(LOG_WARNING, "Unsupported setup attribute value '%s' received on dialog '%s'\n",
  9772. value, p->callid);
  9773. }
  9774. } else if (sscanf(a, "connection: %255s", value) == 1) {
  9775. found = TRUE;
  9776. if (!strcasecmp(value, "new")) {
  9777. dtls->reset(instance);
  9778. } else if (!strcasecmp(value, "existing")) {
  9779. /* Since they want to just use what already exists we go on as if nothing happened */
  9780. } else {
  9781. ast_log(LOG_WARNING, "Unsupported connection attribute value '%s' received on dialog '%s'\n",
  9782. value, p->callid);
  9783. }
  9784. } else if (sscanf(a, "fingerprint: %31s %255s", hash, value) == 2) {
  9785. found = TRUE;
  9786. if (!strcasecmp(hash, "sha-1")) {
  9787. dtls->set_fingerprint(instance, AST_RTP_DTLS_HASH_SHA1, value);
  9788. } else if (!strcasecmp(hash, "sha-256")) {
  9789. dtls->set_fingerprint(instance, AST_RTP_DTLS_HASH_SHA256, value);
  9790. } else {
  9791. ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s' received on dialog '%s'\n",
  9792. hash, p->callid);
  9793. }
  9794. }
  9795. return found;
  9796. }
  9797. static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
  9798. {
  9799. int found = FALSE;
  9800. unsigned int codec;
  9801. char mimeSubtype[128];
  9802. char fmtp_string[256];
  9803. unsigned int sample_rate;
  9804. int debug = sip_debug_test_pvt(p);
  9805. if (!strncasecmp(a, "ptime", 5)) {
  9806. char *tmp = strrchr(a, ':');
  9807. long int framing = 0;
  9808. if (tmp) {
  9809. tmp++;
  9810. framing = strtol(tmp, NULL, 10);
  9811. if (framing == LONG_MIN || framing == LONG_MAX) {
  9812. framing = 0;
  9813. ast_debug(1, "Can't read framing from SDP: %s\n", a);
  9814. }
  9815. }
  9816. if (framing && p->autoframing) {
  9817. ast_debug(1, "Setting framing to %ld\n", framing);
  9818. ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(p->rtp), framing);
  9819. }
  9820. found = TRUE;
  9821. } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
  9822. /* We have a rtpmap to handle */
  9823. if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
  9824. if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
  9825. ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
  9826. if (debug)
  9827. ast_verbose("Found audio description format %s for ID %u\n", mimeSubtype, codec);
  9828. //found_rtpmap_codecs[last_rtpmap_codec] = codec;
  9829. (*last_rtpmap_codec)++;
  9830. found = TRUE;
  9831. } else {
  9832. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  9833. if (debug)
  9834. ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
  9835. }
  9836. } else {
  9837. if (debug)
  9838. ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
  9839. }
  9840. } else if (sscanf(a, "fmtp: %30u %255[^\t\n]", &codec, fmtp_string) == 2) {
  9841. struct ast_format *format;
  9842. if ((format = ast_rtp_codecs_get_payload_format(newaudiortp, codec))) {
  9843. unsigned int bit_rate;
  9844. struct ast_format *format_parsed;
  9845. format_parsed = ast_format_parse_sdp_fmtp(format, fmtp_string);
  9846. if (format_parsed) {
  9847. ast_rtp_codecs_payload_replace_format(newaudiortp, codec, format_parsed);
  9848. ao2_replace(format, format_parsed);
  9849. ao2_ref(format_parsed, -1);
  9850. found = TRUE;
  9851. } else {
  9852. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  9853. }
  9854. if (ast_format_cmp(format, ast_format_siren7) == AST_FORMAT_CMP_EQUAL) {
  9855. if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
  9856. if (bit_rate != 32000) {
  9857. ast_log(LOG_WARNING, "Got Siren7 offer at %u bps, but only 32000 bps supported; ignoring.\n", bit_rate);
  9858. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  9859. } else {
  9860. found = TRUE;
  9861. }
  9862. }
  9863. } else if (ast_format_cmp(format, ast_format_siren14) == AST_FORMAT_CMP_EQUAL) {
  9864. if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
  9865. if (bit_rate != 48000) {
  9866. ast_log(LOG_WARNING, "Got Siren14 offer at %u bps, but only 48000 bps supported; ignoring.\n", bit_rate);
  9867. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  9868. } else {
  9869. found = TRUE;
  9870. }
  9871. }
  9872. } else if (ast_format_cmp(format, ast_format_g719) == AST_FORMAT_CMP_EQUAL) {
  9873. if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
  9874. if (bit_rate != 64000) {
  9875. ast_log(LOG_WARNING, "Got G.719 offer at %u bps, but only 64000 bps supported; ignoring.\n", bit_rate);
  9876. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  9877. } else {
  9878. found = TRUE;
  9879. }
  9880. }
  9881. }
  9882. ao2_ref(format, -1);
  9883. }
  9884. }
  9885. return found;
  9886. }
  9887. static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
  9888. {
  9889. int found = FALSE;
  9890. unsigned int codec;
  9891. char mimeSubtype[128];
  9892. unsigned int sample_rate;
  9893. int debug = sip_debug_test_pvt(p);
  9894. char fmtp_string[256];
  9895. if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
  9896. /* We have a rtpmap to handle */
  9897. if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
  9898. /* Note: should really look at the '#chans' params too */
  9899. if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)
  9900. || !strncasecmp(mimeSubtype, "VP8", 3)) {
  9901. if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
  9902. if (debug)
  9903. ast_verbose("Found video description format %s for ID %u\n", mimeSubtype, codec);
  9904. //found_rtpmap_codecs[last_rtpmap_codec] = codec;
  9905. (*last_rtpmap_codec)++;
  9906. found = TRUE;
  9907. } else {
  9908. ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
  9909. if (debug)
  9910. ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
  9911. }
  9912. }
  9913. } else {
  9914. if (debug)
  9915. ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
  9916. }
  9917. } else if (sscanf(a, "fmtp: %30u %255[^\t\n]", &codec, fmtp_string) == 2) {
  9918. struct ast_format *format;
  9919. if ((format = ast_rtp_codecs_get_payload_format(newvideortp, codec))) {
  9920. struct ast_format *format_parsed;
  9921. format_parsed = ast_format_parse_sdp_fmtp(format, fmtp_string);
  9922. if (format_parsed) {
  9923. ast_rtp_codecs_payload_replace_format(newvideortp, codec, format_parsed);
  9924. ao2_replace(format, format_parsed);
  9925. ao2_ref(format_parsed, -1);
  9926. found = TRUE;
  9927. } else {
  9928. ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
  9929. }
  9930. ao2_ref(format, -1);
  9931. }
  9932. }
  9933. return found;
  9934. }
  9935. static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec)
  9936. {
  9937. int found = FALSE;
  9938. unsigned int codec;
  9939. char mimeSubtype[128];
  9940. unsigned int sample_rate;
  9941. char *red_cp;
  9942. int debug = sip_debug_test_pvt(p);
  9943. if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
  9944. /* We have a rtpmap to handle */
  9945. if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
  9946. if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
  9947. if (p->trtp) {
  9948. /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
  9949. ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
  9950. found = TRUE;
  9951. }
  9952. } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
  9953. if (p->trtp) {
  9954. ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
  9955. sprintf(red_fmtp, "fmtp:%u ", codec);
  9956. if (debug)
  9957. ast_verbose("RED submimetype has payload type: %u\n", codec);
  9958. found = TRUE;
  9959. }
  9960. }
  9961. } else {
  9962. if (debug)
  9963. ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
  9964. }
  9965. } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
  9966. /* count numbers of generations in fmtp */
  9967. red_cp = &red_fmtp[strlen(red_fmtp)];
  9968. strncpy(red_fmtp, a, 100);
  9969. sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
  9970. red_cp = strtok(red_cp, "/");
  9971. while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
  9972. sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
  9973. red_cp = strtok(NULL, "/");
  9974. }
  9975. red_cp = red_fmtp;
  9976. found = TRUE;
  9977. }
  9978. return found;
  9979. }
  9980. static int process_sdp_a_image(const char *a, struct sip_pvt *p)
  9981. {
  9982. int found = FALSE;
  9983. char s[256];
  9984. unsigned int x;
  9985. char *attrib = ast_strdupa(a);
  9986. char *pos;
  9987. if (initialize_udptl(p)) {
  9988. return found;
  9989. }
  9990. /* Due to a typo in an IANA registration of one of the T.38 attributes,
  9991. * RFC5347 section 2.5.2 recommends that all T.38 attributes be parsed in
  9992. * a case insensitive manner. Hence, the importance of proof reading (and
  9993. * code reviews).
  9994. */
  9995. for (pos = attrib; *pos; ++pos) {
  9996. *pos = tolower(*pos);
  9997. }
  9998. if ((sscanf(attrib, "t38faxmaxbuffer:%30u", &x) == 1)) {
  9999. ast_debug(3, "MaxBufferSize:%u\n", x);
  10000. found = TRUE;
  10001. } else if ((sscanf(attrib, "t38maxbitrate:%30u", &x) == 1) || (sscanf(attrib, "t38faxmaxrate:%30u", &x) == 1)) {
  10002. ast_debug(3, "T38MaxBitRate: %u\n", x);
  10003. switch (x) {
  10004. case 14400:
  10005. p->t38.their_parms.rate = AST_T38_RATE_14400;
  10006. break;
  10007. case 12000:
  10008. p->t38.their_parms.rate = AST_T38_RATE_12000;
  10009. break;
  10010. case 9600:
  10011. p->t38.their_parms.rate = AST_T38_RATE_9600;
  10012. break;
  10013. case 7200:
  10014. p->t38.their_parms.rate = AST_T38_RATE_7200;
  10015. break;
  10016. case 4800:
  10017. p->t38.their_parms.rate = AST_T38_RATE_4800;
  10018. break;
  10019. case 2400:
  10020. p->t38.their_parms.rate = AST_T38_RATE_2400;
  10021. break;
  10022. }
  10023. found = TRUE;
  10024. } else if ((sscanf(attrib, "t38faxversion:%30u", &x) == 1)) {
  10025. ast_debug(3, "FaxVersion: %u\n", x);
  10026. p->t38.their_parms.version = x;
  10027. found = TRUE;
  10028. } else if ((sscanf(attrib, "t38faxmaxdatagram:%30u", &x) == 1) || (sscanf(attrib, "t38maxdatagram:%30u", &x) == 1)) {
  10029. /* override the supplied value if the configuration requests it */
  10030. if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
  10031. ast_debug(1, "Overriding T38FaxMaxDatagram '%u' with '%d'\n", x, p->t38_maxdatagram);
  10032. x = p->t38_maxdatagram;
  10033. }
  10034. ast_debug(3, "FaxMaxDatagram: %u\n", x);
  10035. ast_udptl_set_far_max_datagram(p->udptl, x);
  10036. found = TRUE;
  10037. } else if ((strncmp(attrib, "t38faxfillbitremoval", sizeof("t38faxfillbitremoval") - 1) == 0)) {
  10038. if (sscanf(attrib, "t38faxfillbitremoval:%30u", &x) == 1) {
  10039. ast_debug(3, "FillBitRemoval: %u\n", x);
  10040. if (x == 1) {
  10041. p->t38.their_parms.fill_bit_removal = TRUE;
  10042. }
  10043. } else {
  10044. ast_debug(3, "FillBitRemoval\n");
  10045. p->t38.their_parms.fill_bit_removal = TRUE;
  10046. }
  10047. found = TRUE;
  10048. } else if ((strncmp(attrib, "t38faxtranscodingmmr", sizeof("t38faxtranscodingmmr") - 1) == 0)) {
  10049. if (sscanf(attrib, "t38faxtranscodingmmr:%30u", &x) == 1) {
  10050. ast_debug(3, "Transcoding MMR: %u\n", x);
  10051. if (x == 1) {
  10052. p->t38.their_parms.transcoding_mmr = TRUE;
  10053. }
  10054. } else {
  10055. ast_debug(3, "Transcoding MMR\n");
  10056. p->t38.their_parms.transcoding_mmr = TRUE;
  10057. }
  10058. found = TRUE;
  10059. } else if ((strncmp(attrib, "t38faxtranscodingjbig", sizeof("t38faxtranscodingjbig") - 1) == 0)) {
  10060. if (sscanf(attrib, "t38faxtranscodingjbig:%30u", &x) == 1) {
  10061. ast_debug(3, "Transcoding JBIG: %u\n", x);
  10062. if (x == 1) {
  10063. p->t38.their_parms.transcoding_jbig = TRUE;
  10064. }
  10065. } else {
  10066. ast_debug(3, "Transcoding JBIG\n");
  10067. p->t38.their_parms.transcoding_jbig = TRUE;
  10068. }
  10069. found = TRUE;
  10070. } else if ((sscanf(attrib, "t38faxratemanagement:%255s", s) == 1)) {
  10071. ast_debug(3, "RateManagement: %s\n", s);
  10072. if (!strcasecmp(s, "localTCF"))
  10073. p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
  10074. else if (!strcasecmp(s, "transferredTCF"))
  10075. p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
  10076. found = TRUE;
  10077. } else if ((sscanf(attrib, "t38faxudpec:%255s", s) == 1)) {
  10078. ast_debug(3, "UDP EC: %s\n", s);
  10079. if (!strcasecmp(s, "t38UDPRedundancy")) {
  10080. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
  10081. } else if (!strcasecmp(s, "t38UDPFEC")) {
  10082. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
  10083. } else {
  10084. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
  10085. }
  10086. found = TRUE;
  10087. }
  10088. return found;
  10089. }
  10090. /*! \brief Add "Supported" header to sip message. Since some options may
  10091. * be disabled in the config, the sip_pvt must be inspected to determine what
  10092. * is supported for this dialog. */
  10093. static int add_supported(struct sip_pvt *pvt, struct sip_request *req)
  10094. {
  10095. char supported_value[SIPBUFSIZE];
  10096. int res;
  10097. sprintf(supported_value, "replaces%s%s",
  10098. (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) ? ", timer" : "",
  10099. ast_test_flag(&pvt->flags[0], SIP_USEPATH) ? ", path" : "");
  10100. res = add_header(req, "Supported", supported_value);
  10101. return res;
  10102. }
  10103. /*! \brief Add header to SIP message */
  10104. static int add_header(struct sip_request *req, const char *var, const char *value)
  10105. {
  10106. if (req->headers == SIP_MAX_HEADERS) {
  10107. ast_log(LOG_WARNING, "Out of SIP header space\n");
  10108. return -1;
  10109. }
  10110. if (req->lines) {
  10111. ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
  10112. return -1;
  10113. }
  10114. if (sip_cfg.compactheaders) {
  10115. var = find_alias(var, var);
  10116. }
  10117. ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
  10118. req->header[req->headers] = ast_str_strlen(req->data);
  10119. req->headers++;
  10120. return 0;
  10121. }
  10122. /*!
  10123. * \pre dialog is assumed to be locked while calling this function
  10124. * \brief Add 'Max-Forwards' header to SIP message
  10125. */
  10126. static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
  10127. {
  10128. char clen[10];
  10129. snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
  10130. return add_header(req, "Max-Forwards", clen);
  10131. }
  10132. /*! \brief Add 'Content-Length' header and content to SIP message */
  10133. static int finalize_content(struct sip_request *req)
  10134. {
  10135. char clen[10];
  10136. if (req->lines) {
  10137. ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
  10138. return -1;
  10139. }
  10140. snprintf(clen, sizeof(clen), "%zu", ast_str_strlen(req->content));
  10141. add_header(req, "Content-Length", clen);
  10142. if (ast_str_strlen(req->content)) {
  10143. ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
  10144. }
  10145. req->lines = ast_str_strlen(req->content) ? 1 : 0;
  10146. return 0;
  10147. }
  10148. /*! \brief Add content (not header) to SIP message */
  10149. static int add_content(struct sip_request *req, const char *line)
  10150. {
  10151. if (req->lines) {
  10152. ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
  10153. return -1;
  10154. }
  10155. ast_str_append(&req->content, 0, "%s", line);
  10156. return 0;
  10157. }
  10158. /*! \brief Copy one header field from one request to another */
  10159. static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
  10160. {
  10161. const char *tmp = sip_get_header(orig, field);
  10162. if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
  10163. return add_header(req, field, tmp);
  10164. ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
  10165. return -1;
  10166. }
  10167. /*! \brief Copy all headers from one request to another */
  10168. static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
  10169. {
  10170. int start = 0;
  10171. int copied = 0;
  10172. for (;;) {
  10173. const char *tmp = __get_header(orig, field, &start);
  10174. if (ast_strlen_zero(tmp))
  10175. break;
  10176. /* Add what we're responding to */
  10177. add_header(req, field, tmp);
  10178. copied++;
  10179. }
  10180. return copied ? 0 : -1;
  10181. }
  10182. /*! \brief Copy SIP VIA Headers from the request to the response
  10183. \note If the client indicates that it wishes to know the port we received from,
  10184. it adds ;rport without an argument to the topmost via header. We need to
  10185. add the port number (from our point of view) to that parameter.
  10186. \verbatim
  10187. We always add ;received=<ip address> to the topmost via header.
  10188. \endverbatim
  10189. Received: RFC 3261, rport RFC 3581 */
  10190. static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
  10191. {
  10192. int copied = 0;
  10193. int start = 0;
  10194. for (;;) {
  10195. char new[512];
  10196. const char *oh = __get_header(orig, field, &start);
  10197. if (ast_strlen_zero(oh))
  10198. break;
  10199. if (!copied) { /* Only check for empty rport in topmost via header */
  10200. char leftmost[512], *others, *rport;
  10201. /* Only work on leftmost value */
  10202. ast_copy_string(leftmost, oh, sizeof(leftmost));
  10203. others = strchr(leftmost, ',');
  10204. if (others)
  10205. *others++ = '\0';
  10206. /* Find ;rport; (empty request) */
  10207. rport = strstr(leftmost, ";rport");
  10208. if (rport && *(rport+6) == '=')
  10209. rport = NULL; /* We already have a parameter to rport */
  10210. if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
  10211. /* We need to add received port - rport */
  10212. char *end;
  10213. rport = strstr(leftmost, ";rport");
  10214. if (rport) {
  10215. end = strchr(rport + 1, ';');
  10216. if (end)
  10217. memmove(rport, end, strlen(end) + 1);
  10218. else
  10219. *rport = '\0';
  10220. }
  10221. /* Add rport to first VIA header if requested */
  10222. snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
  10223. leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
  10224. ast_sockaddr_port(&p->recv),
  10225. others ? "," : "", others ? others : "");
  10226. } else {
  10227. /* We should *always* add a received to the topmost via */
  10228. snprintf(new, sizeof(new), "%s;received=%s%s%s",
  10229. leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
  10230. others ? "," : "", others ? others : "");
  10231. }
  10232. oh = new; /* the header to copy */
  10233. } /* else add the following via headers untouched */
  10234. add_header(req, field, oh);
  10235. copied++;
  10236. }
  10237. if (!copied) {
  10238. ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
  10239. return -1;
  10240. }
  10241. return 0;
  10242. }
  10243. /*! \brief Add route header into request per learned route */
  10244. static void add_route(struct sip_request *req, struct sip_route *route, int skip)
  10245. {
  10246. struct ast_str *r;
  10247. if (sip_route_empty(route)) {
  10248. return;
  10249. }
  10250. if ((r = sip_route_list(route, 0, skip))) {
  10251. if (ast_str_strlen(r)) {
  10252. add_header(req, "Route", ast_str_buffer(r));
  10253. }
  10254. ast_free(r);
  10255. }
  10256. }
  10257. /*! \brief Set destination from SIP URI
  10258. *
  10259. * Parse uri to h (host) and port - uri is already just the part inside the <>
  10260. * general form we are expecting is \verbatim sip[s]:username[:password][;parameter]@host[:port][;...] \endverbatim
  10261. * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
  10262. * for SIP: uri's
  10263. *
  10264. * If there's a sips: uri scheme, TLS will be required.
  10265. */
  10266. static void set_destination(struct sip_pvt *p, const char *uri)
  10267. {
  10268. char *trans, *maddr, hostname[256];
  10269. const char *h;
  10270. int hn;
  10271. int debug=sip_debug_test_pvt(p);
  10272. int tls_on = FALSE;
  10273. if (debug)
  10274. ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
  10275. if ((trans = strcasestr(uri, ";transport="))) {
  10276. trans += strlen(";transport=");
  10277. if (!strncasecmp(trans, "ws", 2)) {
  10278. if (debug)
  10279. ast_verbose("set_destination: URI is for WebSocket, we can't set destination\n");
  10280. return;
  10281. }
  10282. }
  10283. /* Find and parse hostname */
  10284. h = strchr(uri, '@');
  10285. if (h)
  10286. ++h;
  10287. else {
  10288. h = uri;
  10289. if (!strncasecmp(h, "sip:", 4)) {
  10290. h += 4;
  10291. } else if (!strncasecmp(h, "sips:", 5)) {
  10292. h += 5;
  10293. tls_on = TRUE;
  10294. }
  10295. }
  10296. hn = strcspn(h, ";>") + 1;
  10297. if (hn > sizeof(hostname))
  10298. hn = sizeof(hostname);
  10299. ast_copy_string(hostname, h, hn);
  10300. /* XXX bug here if string has been trimmed to sizeof(hostname) */
  10301. h += hn - 1;
  10302. /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
  10303. * otherwise, just look for A records */
  10304. if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
  10305. ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
  10306. return;
  10307. }
  10308. /* Got the hostname - but maybe there's a "maddr=" to override address? */
  10309. maddr = strstr(h, "maddr=");
  10310. if (maddr) {
  10311. int port;
  10312. maddr += 6;
  10313. hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  10314. "0123456789-.:[]") + 1;
  10315. if (hn > sizeof(hostname))
  10316. hn = sizeof(hostname);
  10317. ast_copy_string(hostname, maddr, hn);
  10318. port = ast_sockaddr_port(&p->sa);
  10319. /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
  10320. * NAPTR/SRV, otherwise, just look for A records */
  10321. if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
  10322. ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
  10323. return;
  10324. }
  10325. ast_sockaddr_set_port(&p->sa, port);
  10326. }
  10327. if (!ast_sockaddr_port(&p->sa)) {
  10328. ast_sockaddr_set_port(&p->sa, tls_on ?
  10329. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  10330. }
  10331. if (debug) {
  10332. ast_verbose("set_destination: set destination to %s\n",
  10333. ast_sockaddr_stringify(&p->sa));
  10334. }
  10335. }
  10336. /*! \brief Initialize SIP response, based on SIP request */
  10337. static int init_resp(struct sip_request *resp, const char *msg)
  10338. {
  10339. /* Initialize a response */
  10340. memset(resp, 0, sizeof(*resp));
  10341. resp->method = SIP_RESPONSE;
  10342. if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
  10343. goto e_return;
  10344. if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
  10345. goto e_free_data;
  10346. resp->header[0] = 0;
  10347. ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
  10348. resp->headers++;
  10349. return 0;
  10350. e_free_data:
  10351. ast_free(resp->data);
  10352. resp->data = NULL;
  10353. e_return:
  10354. return -1;
  10355. }
  10356. /*! \brief Initialize SIP request */
  10357. static int init_req(struct sip_request *req, int sipmethod, const char *recip)
  10358. {
  10359. /* Initialize a request */
  10360. memset(req, 0, sizeof(*req));
  10361. if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
  10362. goto e_return;
  10363. if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
  10364. goto e_free_data;
  10365. req->method = sipmethod;
  10366. req->header[0] = 0;
  10367. ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
  10368. req->headers++;
  10369. return 0;
  10370. e_free_data:
  10371. ast_free(req->data);
  10372. req->data = NULL;
  10373. e_return:
  10374. return -1;
  10375. }
  10376. /*! \brief Deinitialize SIP response/request */
  10377. static void deinit_req(struct sip_request *req)
  10378. {
  10379. if (req->data) {
  10380. ast_free(req->data);
  10381. req->data = NULL;
  10382. }
  10383. if (req->content) {
  10384. ast_free(req->content);
  10385. req->content = NULL;
  10386. }
  10387. }
  10388. /*! \brief Test if this response needs a contact header */
  10389. static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
  10390. /* Requirements for Contact header inclusion in responses generated
  10391. * from the header tables found in the following RFCs. Where the
  10392. * Contact header was marked mandatory (m) or optional (o) this
  10393. * function returns 1.
  10394. *
  10395. * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
  10396. * - RFC 2976 (INFO)
  10397. * - RFC 3262 (PRACK)
  10398. * - RFC 3265 (SUBSCRIBE, NOTIFY)
  10399. * - RFC 3311 (UPDATE)
  10400. * - RFC 3428 (MESSAGE)
  10401. * - RFC 3515 (REFER)
  10402. * - RFC 3903 (PUBLISH)
  10403. */
  10404. switch (method) {
  10405. /* 1xx, 2xx, 3xx, 485 */
  10406. case SIP_INVITE:
  10407. case SIP_UPDATE:
  10408. case SIP_SUBSCRIBE:
  10409. case SIP_NOTIFY:
  10410. if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
  10411. return 1;
  10412. break;
  10413. /* 2xx, 3xx, 485 */
  10414. case SIP_REGISTER:
  10415. case SIP_OPTIONS:
  10416. if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
  10417. return 1;
  10418. break;
  10419. /* 3xx, 485 */
  10420. case SIP_BYE:
  10421. case SIP_PRACK:
  10422. case SIP_MESSAGE:
  10423. case SIP_PUBLISH:
  10424. if (msg[0] == '3' || !strncmp(msg, "485", 3))
  10425. return 1;
  10426. break;
  10427. /* 2xx, 3xx, 4xx, 5xx, 6xx */
  10428. case SIP_REFER:
  10429. if (msg[0] >= '2' && msg[0] <= '6')
  10430. return 1;
  10431. break;
  10432. /* contact will not be included for everything else */
  10433. case SIP_ACK:
  10434. case SIP_CANCEL:
  10435. case SIP_INFO:
  10436. case SIP_PING:
  10437. default:
  10438. return 0;
  10439. }
  10440. return 0;
  10441. }
  10442. /*! \brief Prepare SIP response packet */
  10443. static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
  10444. {
  10445. char newto[256];
  10446. const char *ot;
  10447. init_resp(resp, msg);
  10448. copy_via_headers(p, resp, req, "Via");
  10449. if (msg[0] == '1' || msg[0] == '2')
  10450. copy_all_header(resp, req, "Record-Route");
  10451. copy_header(resp, req, "From");
  10452. ot = sip_get_header(req, "To");
  10453. if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
  10454. /* Add the proper tag if we don't have it already. If they have specified
  10455. their tag, use it. Otherwise, use our own tag */
  10456. if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
  10457. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
  10458. else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
  10459. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
  10460. else
  10461. ast_copy_string(newto, ot, sizeof(newto));
  10462. ot = newto;
  10463. }
  10464. add_header(resp, "To", ot);
  10465. copy_header(resp, req, "Call-ID");
  10466. copy_header(resp, req, "CSeq");
  10467. if (!ast_strlen_zero(global_useragent))
  10468. add_header(resp, "Server", global_useragent);
  10469. add_header(resp, "Allow", ALLOWED_METHODS);
  10470. add_supported(p, resp);
  10471. /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
  10472. if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE) {
  10473. char se_hdr[256];
  10474. snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
  10475. p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
  10476. add_header(resp, "Session-Expires", se_hdr);
  10477. /* RFC 2048, Section 9
  10478. * If the refresher parameter in the Session-Expires header field in the
  10479. * 2xx response has a value of 'uac', the UAS MUST place a Require
  10480. * header field into the response with the value 'timer'.
  10481. * ...
  10482. * If the refresher parameter in
  10483. * the 2xx response has a value of 'uas' and the Supported header field
  10484. * in the request contained the value 'timer', the UAS SHOULD place a
  10485. * Require header field into the response with the value 'timer'
  10486. */
  10487. if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_THEM ||
  10488. (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US &&
  10489. p->stimer->st_active_peer_ua == TRUE)) {
  10490. resp->reqsipoptions |= SIP_OPT_TIMER;
  10491. }
  10492. }
  10493. if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
  10494. /* For registration responses, we also need expiry and
  10495. contact info */
  10496. add_expires(resp, p->expiry);
  10497. if (p->expiry) { /* Only add contact if we have an expiry time */
  10498. char contact[SIPBUFSIZE];
  10499. const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
  10500. char *brackets = strchr(contact_uri, '<');
  10501. snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
  10502. add_header(resp, "Contact", contact); /* Not when we unregister */
  10503. }
  10504. if (p->method == SIP_REGISTER && ast_test_flag(&p->flags[0], SIP_USEPATH)) {
  10505. copy_header(resp, req, "Path");
  10506. }
  10507. } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
  10508. add_header(resp, "Contact", p->our_contact);
  10509. }
  10510. if (!ast_strlen_zero(p->url)) {
  10511. add_header(resp, "Access-URL", p->url);
  10512. ast_string_field_set(p, url, NULL);
  10513. }
  10514. /* default to routing the response to the address where the request
  10515. * came from. Since we don't have a transport layer, we do this here.
  10516. * The process_via() function will update the port to either the port
  10517. * specified in the via header or the default port later on (per RFC
  10518. * 3261 section 18.2.2).
  10519. */
  10520. p->sa = p->recv;
  10521. if (process_via(p, req)) {
  10522. ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
  10523. }
  10524. return 0;
  10525. }
  10526. /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
  10527. static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
  10528. {
  10529. struct sip_request *orig = &p->initreq;
  10530. char stripped[80];
  10531. char tmp[80];
  10532. char newto[256];
  10533. const char *c;
  10534. const char *ot, *of;
  10535. int is_strict = FALSE; /*!< Strict routing flag */
  10536. int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING); /* Session direction */
  10537. snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
  10538. if (!seqno) {
  10539. p->ocseq++;
  10540. seqno = p->ocseq;
  10541. }
  10542. /* A CANCEL must have the same branch as the INVITE that it is canceling. */
  10543. if (sipmethod == SIP_CANCEL) {
  10544. p->branch = p->invite_branch;
  10545. build_via(p);
  10546. } else if (newbranch && (sipmethod == SIP_INVITE)) {
  10547. p->branch ^= ast_random();
  10548. p->invite_branch = p->branch;
  10549. build_via(p);
  10550. } else if (newbranch) {
  10551. p->branch ^= ast_random();
  10552. build_via(p);
  10553. }
  10554. /* Check for strict or loose router */
  10555. if (sip_route_is_strict(&p->route)) {
  10556. is_strict = TRUE;
  10557. if (sipdebug)
  10558. ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
  10559. }
  10560. if (sipmethod == SIP_CANCEL) {
  10561. c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2); /* Use original URI */
  10562. } else if (sipmethod == SIP_ACK) {
  10563. /* Use URI from Contact: in 200 OK (if INVITE)
  10564. (we only have the contacturi on INVITEs) */
  10565. if (!ast_strlen_zero(p->okcontacturi)) {
  10566. c = is_strict ? sip_route_first_uri(&p->route) : p->okcontacturi;
  10567. } else {
  10568. c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
  10569. }
  10570. } else if (!ast_strlen_zero(p->okcontacturi)) {
  10571. /* Use for BYE or REINVITE */
  10572. c = is_strict ? sip_route_first_uri(&p->route) : p->okcontacturi;
  10573. } else if (!ast_strlen_zero(p->uri)) {
  10574. c = p->uri;
  10575. } else {
  10576. char *n;
  10577. /* We have no URI, use To: or From: header as URI (depending on direction) */
  10578. ast_copy_string(stripped, sip_get_header(orig, is_outbound ? "To" : "From"),
  10579. sizeof(stripped));
  10580. n = get_in_brackets(stripped);
  10581. c = remove_uri_parameters(n);
  10582. }
  10583. init_req(req, sipmethod, c);
  10584. snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
  10585. add_header(req, "Via", p->via);
  10586. /*
  10587. * Use the learned route set unless this is a CANCEL or an ACK for a non-2xx
  10588. * final response. For a CANCEL or ACK, we have to send to the same destination
  10589. * as the original INVITE.
  10590. * Send UPDATE to the same destination as CANCEL, if call is not in final state.
  10591. */
  10592. if (!sip_route_empty(&p->route) &&
  10593. !(sipmethod == SIP_CANCEL ||
  10594. (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)) ||
  10595. (sipmethod == SIP_UPDATE && (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)))) {
  10596. if (p->socket.type != AST_TRANSPORT_UDP && p->socket.tcptls_session) {
  10597. /* For TCP/TLS sockets that are connected we won't need
  10598. * to do any hostname/IP lookups */
  10599. } else if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
  10600. /* For NATed traffic, we ignore the contact/route and
  10601. * simply send to the received-from address. No need
  10602. * for lookups. */
  10603. } else {
  10604. set_destination(p, sip_route_first_uri(&p->route));
  10605. }
  10606. add_route(req, &p->route, is_strict ? 1 : 0);
  10607. }
  10608. add_max_forwards(p, req);
  10609. ot = sip_get_header(orig, "To");
  10610. of = sip_get_header(orig, "From");
  10611. /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
  10612. as our original request, including tag (or presumably lack thereof) */
  10613. if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
  10614. /* Add the proper tag if we don't have it already. If they have specified
  10615. their tag, use it. Otherwise, use our own tag */
  10616. if (is_outbound && !ast_strlen_zero(p->theirtag))
  10617. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
  10618. else if (!is_outbound)
  10619. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
  10620. else
  10621. snprintf(newto, sizeof(newto), "%s", ot);
  10622. ot = newto;
  10623. }
  10624. if (is_outbound) {
  10625. add_header(req, "From", of);
  10626. add_header(req, "To", ot);
  10627. } else {
  10628. add_header(req, "From", ot);
  10629. add_header(req, "To", of);
  10630. }
  10631. /* Do not add Contact for MESSAGE, BYE and Cancel requests */
  10632. if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
  10633. add_header(req, "Contact", p->our_contact);
  10634. copy_header(req, orig, "Call-ID");
  10635. add_header(req, "CSeq", tmp);
  10636. if (!ast_strlen_zero(global_useragent))
  10637. add_header(req, "User-Agent", global_useragent);
  10638. if (!ast_strlen_zero(p->url)) {
  10639. add_header(req, "Access-URL", p->url);
  10640. ast_string_field_set(p, url, NULL);
  10641. }
  10642. /* Add Session-Timers related headers if the feature is active for this session.
  10643. An exception to this behavior is the ACK request. Since Asterisk never requires
  10644. session-timers support from a remote end-point (UAS) in an INVITE, it must
  10645. not send 'Require: timer' header in the ACK request.
  10646. This should only be added in the INVITE transactions, not MESSAGE or REFER or other
  10647. in-dialog messages.
  10648. */
  10649. if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
  10650. && sipmethod == SIP_INVITE) {
  10651. char se_hdr[256];
  10652. snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
  10653. p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
  10654. add_header(req, "Session-Expires", se_hdr);
  10655. snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
  10656. add_header(req, "Min-SE", se_hdr);
  10657. }
  10658. return 0;
  10659. }
  10660. /*! \brief Base transmit response function */
  10661. static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
  10662. {
  10663. struct sip_request resp;
  10664. uint32_t seqno = 0;
  10665. if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
  10666. ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
  10667. return -1;
  10668. }
  10669. respprep(&resp, p, msg, req);
  10670. if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
  10671. && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
  10672. && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
  10673. ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  10674. add_rpid(&resp, p);
  10675. }
  10676. if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
  10677. add_cc_call_info_to_response(p, &resp);
  10678. }
  10679. /* If we are sending a 302 Redirect we can add a diversion header if the redirect information is set */
  10680. if (!strncmp(msg, "302", 3)) {
  10681. add_diversion(&resp, p);
  10682. }
  10683. /* If we are cancelling an incoming invite for some reason, add information
  10684. about the reason why we are doing this in clear text */
  10685. if (p->method == SIP_INVITE && msg[0] != '1') {
  10686. char buf[20];
  10687. if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
  10688. int hangupcause = 0;
  10689. if (p->owner && ast_channel_hangupcause(p->owner)) {
  10690. hangupcause = ast_channel_hangupcause(p->owner);
  10691. } else if (p->hangupcause) {
  10692. hangupcause = p->hangupcause;
  10693. } else {
  10694. int respcode;
  10695. if (sscanf(msg, "%30d ", &respcode))
  10696. hangupcause = hangup_sip2cause(respcode);
  10697. }
  10698. if (hangupcause) {
  10699. sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
  10700. add_header(&resp, "Reason", buf);
  10701. }
  10702. }
  10703. if (p->owner && ast_channel_hangupcause(p->owner)) {
  10704. add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(ast_channel_hangupcause(p->owner)));
  10705. snprintf(buf, sizeof(buf), "%d", ast_channel_hangupcause(p->owner));
  10706. add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
  10707. }
  10708. }
  10709. return send_response(p, &resp, reliable, seqno);
  10710. }
  10711. static int transmit_response_with_sip_etag(struct sip_pvt *p, const char *msg, const struct sip_request *req, struct sip_esc_entry *esc_entry, int need_new_etag)
  10712. {
  10713. struct sip_request resp;
  10714. if (need_new_etag) {
  10715. create_new_sip_etag(esc_entry, 1);
  10716. }
  10717. respprep(&resp, p, msg, req);
  10718. add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
  10719. return send_response(p, &resp, 0, 0);
  10720. }
  10721. static int temp_pvt_init(void *data)
  10722. {
  10723. struct sip_pvt *p = data;
  10724. p->do_history = 0; /* XXX do we need it ? isn't already all 0 ? */
  10725. return ast_string_field_init(p, 512);
  10726. }
  10727. static void temp_pvt_cleanup(void *data)
  10728. {
  10729. struct sip_pvt *p = data;
  10730. ast_string_field_free_memory(p);
  10731. ast_free(data);
  10732. }
  10733. /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
  10734. static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
  10735. {
  10736. struct sip_pvt *p = NULL;
  10737. if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
  10738. ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
  10739. return -1;
  10740. }
  10741. /* XXX the structure may be dirty from previous usage.
  10742. * Here we should state clearly how we should reinitialize it
  10743. * before using it.
  10744. * E.g. certainly the threadstorage should be left alone,
  10745. * but other thihngs such as flags etc. maybe need cleanup ?
  10746. */
  10747. /* Initialize the bare minimum */
  10748. p->method = intended_method;
  10749. if (!addr) {
  10750. ast_sockaddr_copy(&p->ourip, &internip);
  10751. } else {
  10752. ast_sockaddr_copy(&p->sa, addr);
  10753. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  10754. }
  10755. p->branch = ast_random();
  10756. make_our_tag(p);
  10757. p->ocseq = INITIAL_CSEQ;
  10758. if (useglobal_nat && addr) {
  10759. ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
  10760. ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT);
  10761. ast_sockaddr_copy(&p->recv, addr);
  10762. check_via(p, req);
  10763. }
  10764. ast_string_field_set(p, fromdomain, default_fromdomain);
  10765. p->fromdomainport = default_fromdomainport;
  10766. build_via(p);
  10767. ast_string_field_set(p, callid, callid);
  10768. copy_socket_data(&p->socket, &req->socket);
  10769. /* Use this temporary pvt structure to send the message */
  10770. __transmit_response(p, msg, req, XMIT_UNRELIABLE);
  10771. /* Free the string fields, but not the pool space */
  10772. ast_string_field_init(p, 0);
  10773. return 0;
  10774. }
  10775. /*! \brief Transmit response, no retransmits */
  10776. static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
  10777. {
  10778. return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
  10779. }
  10780. /*! \brief Transmit response, no retransmits */
  10781. static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
  10782. {
  10783. struct sip_request resp;
  10784. respprep(&resp, p, msg, req);
  10785. add_date(&resp);
  10786. add_header(&resp, "Unsupported", unsupported);
  10787. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  10788. }
  10789. /*! \brief Transmit 422 response with Min-SE header (Session-Timers) */
  10790. static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
  10791. {
  10792. struct sip_request resp;
  10793. char minse_str[20];
  10794. respprep(&resp, p, msg, req);
  10795. add_date(&resp);
  10796. snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
  10797. add_header(&resp, "Min-SE", minse_str);
  10798. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  10799. }
  10800. /*! \brief Transmit response, Make sure you get an ACK
  10801. This is only used for responses to INVITEs, where we need to make sure we get an ACK
  10802. */
  10803. static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
  10804. {
  10805. return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
  10806. }
  10807. /*! \brief Add date header to SIP message */
  10808. static void add_date(struct sip_request *req)
  10809. {
  10810. char tmp[256];
  10811. struct tm tm;
  10812. time_t t = time(NULL);
  10813. gmtime_r(&t, &tm);
  10814. strftime(tmp, sizeof(tmp), "%a, %d %b %Y %T GMT", &tm);
  10815. add_header(req, "Date", tmp);
  10816. }
  10817. /*! \brief Add Expires header to SIP message */
  10818. static void add_expires(struct sip_request *req, int expires)
  10819. {
  10820. char tmp[32];
  10821. snprintf(tmp, sizeof(tmp), "%d", expires);
  10822. add_header(req, "Expires", tmp);
  10823. }
  10824. /*! \brief Append Retry-After header field when transmitting response */
  10825. static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
  10826. {
  10827. struct sip_request resp;
  10828. respprep(&resp, p, msg, req);
  10829. add_header(&resp, "Retry-After", seconds);
  10830. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  10831. }
  10832. /*! \brief Add date before transmitting response */
  10833. static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
  10834. {
  10835. struct sip_request resp;
  10836. respprep(&resp, p, msg, req);
  10837. add_date(&resp);
  10838. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  10839. }
  10840. /*! \brief Append Accept header, content length before transmitting response */
  10841. static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
  10842. {
  10843. struct sip_request resp;
  10844. respprep(&resp, p, msg, req);
  10845. add_header(&resp, "Accept", "application/sdp");
  10846. return send_response(p, &resp, reliable, 0);
  10847. }
  10848. /*! \brief Append Min-Expires header, content length before transmitting response */
  10849. static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minexpires)
  10850. {
  10851. struct sip_request resp;
  10852. char tmp[32];
  10853. snprintf(tmp, sizeof(tmp), "%d", minexpires);
  10854. respprep(&resp, p, msg, req);
  10855. add_header(&resp, "Min-Expires", tmp);
  10856. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  10857. }
  10858. /*! \brief Respond with authorization request */
  10859. static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *nonce, enum xmittype reliable, const char *header, int stale)
  10860. {
  10861. struct sip_request resp;
  10862. char tmp[512];
  10863. uint32_t seqno = 0;
  10864. if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
  10865. ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
  10866. return -1;
  10867. }
  10868. /* Choose Realm */
  10869. get_realm(p, req);
  10870. /* Stale means that they sent us correct authentication, but
  10871. based it on an old challenge (nonce) */
  10872. snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, nonce, stale ? ", stale=true" : "");
  10873. respprep(&resp, p, msg, req);
  10874. add_header(&resp, header, tmp);
  10875. append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
  10876. return send_response(p, &resp, reliable, seqno);
  10877. }
  10878. /*!
  10879. \brief Extract domain from SIP To/From header
  10880. \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
  10881. \note TODO: Such code is all over SIP channel, there is a sense to organize
  10882. this patern in one function
  10883. */
  10884. static int get_domain(const char *str, char *domain, int len)
  10885. {
  10886. char tmpf[256];
  10887. char *a, *from;
  10888. *domain = '\0';
  10889. ast_copy_string(tmpf, str, sizeof(tmpf));
  10890. from = get_in_brackets(tmpf);
  10891. if (!ast_strlen_zero(from)) {
  10892. if (strncasecmp(from, "sip:", 4)) {
  10893. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
  10894. return -1;
  10895. }
  10896. from += 4;
  10897. } else
  10898. from = NULL;
  10899. if (from) {
  10900. int bracket = 0;
  10901. /* Strip any params or options from user */
  10902. if ((a = strchr(from, ';')))
  10903. *a = '\0';
  10904. /* Strip port from domain if present */
  10905. for (a = from; *a != '\0'; ++a) {
  10906. if (*a == ':' && bracket == 0) {
  10907. *a = '\0';
  10908. break;
  10909. } else if (*a == '[') {
  10910. ++bracket;
  10911. } else if (*a == ']') {
  10912. --bracket;
  10913. }
  10914. }
  10915. if ((a = strchr(from, '@'))) {
  10916. *a = '\0';
  10917. ast_copy_string(domain, a + 1, len);
  10918. } else
  10919. ast_copy_string(domain, from, len);
  10920. }
  10921. return ast_strlen_zero(domain);
  10922. }
  10923. /*!
  10924. \brief Choose realm based on From header and then To header or use globaly configured realm.
  10925. Realm from From/To header should be listed among served domains in config file: domain=...
  10926. */
  10927. static void get_realm(struct sip_pvt *p, const struct sip_request *req)
  10928. {
  10929. char domain[MAXHOSTNAMELEN];
  10930. if (!ast_strlen_zero(p->realm))
  10931. return;
  10932. if (sip_cfg.domainsasrealm &&
  10933. !AST_LIST_EMPTY(&domain_list))
  10934. {
  10935. /* Check From header first */
  10936. if (!get_domain(sip_get_header(req, "From"), domain, sizeof(domain))) {
  10937. if (check_sip_domain(domain, NULL, 0)) {
  10938. ast_string_field_set(p, realm, domain);
  10939. return;
  10940. }
  10941. }
  10942. /* Check To header */
  10943. if (!get_domain(sip_get_header(req, "To"), domain, sizeof(domain))) {
  10944. if (check_sip_domain(domain, NULL, 0)) {
  10945. ast_string_field_set(p, realm, domain);
  10946. return;
  10947. }
  10948. }
  10949. }
  10950. /* Use default realm from config file */
  10951. ast_string_field_set(p, realm, sip_cfg.realm);
  10952. }
  10953. /*!
  10954. * \internal
  10955. *
  10956. * \arg msg Only use a string constant for the msg, here, it is shallow copied
  10957. *
  10958. * \note assumes the sip_pvt is locked.
  10959. */
  10960. static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
  10961. {
  10962. int res;
  10963. if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
  10964. p->last_provisional = msg;
  10965. update_provisional_keepalive(p, with_sdp);
  10966. }
  10967. return res;
  10968. }
  10969. /*!
  10970. * \internal
  10971. * \brief Destroy all additional MESSAGE headers.
  10972. *
  10973. * \param pvt SIP private dialog struct.
  10974. *
  10975. * \return Nothing
  10976. */
  10977. static void destroy_msg_headers(struct sip_pvt *pvt)
  10978. {
  10979. struct sip_msg_hdr *doomed;
  10980. while ((doomed = AST_LIST_REMOVE_HEAD(&pvt->msg_headers, next))) {
  10981. ast_free(doomed);
  10982. }
  10983. }
  10984. /*!
  10985. * \internal
  10986. * \brief Add a MESSAGE header to the dialog.
  10987. *
  10988. * \param pvt SIP private dialog struct.
  10989. * \param hdr_name Name of header for MESSAGE.
  10990. * \param hdr_value Value of header for MESSAGE.
  10991. *
  10992. * \return Nothing
  10993. */
  10994. static void add_msg_header(struct sip_pvt *pvt, const char *hdr_name, const char *hdr_value)
  10995. {
  10996. size_t hdr_len_name;
  10997. size_t hdr_len_value;
  10998. struct sip_msg_hdr *node;
  10999. char *pos;
  11000. hdr_len_name = strlen(hdr_name) + 1;
  11001. hdr_len_value = strlen(hdr_value) + 1;
  11002. node = ast_calloc(1, sizeof(*node) + hdr_len_name + hdr_len_value);
  11003. if (!node) {
  11004. return;
  11005. }
  11006. pos = node->stuff;
  11007. node->name = pos;
  11008. strcpy(pos, hdr_name);
  11009. pos += hdr_len_name;
  11010. node->value = pos;
  11011. strcpy(pos, hdr_value);
  11012. AST_LIST_INSERT_TAIL(&pvt->msg_headers, node, next);
  11013. }
  11014. /*! \brief Add text body to SIP message */
  11015. static int add_text(struct sip_request *req, struct sip_pvt *p)
  11016. {
  11017. const char *content_type = NULL;
  11018. struct sip_msg_hdr *node;
  11019. /* Add any additional MESSAGE headers. */
  11020. AST_LIST_TRAVERSE(&p->msg_headers, node, next) {
  11021. if (!strcasecmp(node->name, "Content-Type")) {
  11022. /* Save content type */
  11023. content_type = node->value;
  11024. } else {
  11025. add_header(req, node->name, node->value);
  11026. }
  11027. }
  11028. if (ast_strlen_zero(content_type)) {
  11029. /* "Content-Type" not set - use default value */
  11030. content_type = "text/plain;charset=UTF-8";
  11031. }
  11032. add_header(req, "Content-Type", content_type);
  11033. /* XXX Convert \n's to \r\n's XXX */
  11034. add_content(req, p->msg_body);
  11035. return 0;
  11036. }
  11037. /*! \brief Add DTMF INFO tone to sip message
  11038. Mode = 0 for application/dtmf-relay (Cisco)
  11039. 1 for application/dtmf
  11040. */
  11041. static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
  11042. {
  11043. char tmp[256];
  11044. int event;
  11045. if (mode) {
  11046. /* Application/dtmf short version used by some implementations */
  11047. if ('0' <= digit && digit <= '9') {
  11048. event = digit - '0';
  11049. } else if (digit == '*') {
  11050. event = 10;
  11051. } else if (digit == '#') {
  11052. event = 11;
  11053. } else if ('A' <= digit && digit <= 'D') {
  11054. event = 12 + digit - 'A';
  11055. } else if ('a' <= digit && digit <= 'd') {
  11056. event = 12 + digit - 'a';
  11057. } else {
  11058. /* Unknown digit */
  11059. event = 0;
  11060. }
  11061. snprintf(tmp, sizeof(tmp), "%d\r\n", event);
  11062. add_header(req, "Content-Type", "application/dtmf");
  11063. add_content(req, tmp);
  11064. } else {
  11065. /* Application/dtmf-relay as documented by Cisco */
  11066. snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
  11067. add_header(req, "Content-Type", "application/dtmf-relay");
  11068. add_content(req, tmp);
  11069. }
  11070. return 0;
  11071. }
  11072. /*!
  11073. * \pre if p->owner exists, it must be locked
  11074. * \brief Add Remote-Party-ID header to SIP message
  11075. */
  11076. static int add_rpid(struct sip_request *req, struct sip_pvt *p)
  11077. {
  11078. struct ast_str *tmp = ast_str_alloca(256);
  11079. char tmp2[256];
  11080. char lid_name_buf[128];
  11081. char *lid_num;
  11082. char *lid_name;
  11083. int lid_pres;
  11084. const char *fromdomain;
  11085. const char *privacy = NULL;
  11086. const char *screen = NULL;
  11087. struct ast_party_id connected_id;
  11088. const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
  11089. if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
  11090. return 0;
  11091. }
  11092. if (!p->owner) {
  11093. return 0;
  11094. }
  11095. connected_id = ast_channel_connected_effective_id(p->owner);
  11096. lid_num = S_COR(connected_id.number.valid, connected_id.number.str, NULL);
  11097. if (!lid_num) {
  11098. return 0;
  11099. }
  11100. lid_name = S_COR(connected_id.name.valid, connected_id.name.str, NULL);
  11101. if (!lid_name) {
  11102. lid_name = lid_num;
  11103. }
  11104. ast_escape_quoted(lid_name, lid_name_buf, sizeof(lid_name_buf));
  11105. lid_pres = ast_party_id_presentation(&connected_id);
  11106. if (((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) &&
  11107. (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_NO)) {
  11108. /* If pres is not allowed and we don't trust the peer, we don't apply an RPID header */
  11109. return 0;
  11110. }
  11111. fromdomain = p->fromdomain;
  11112. if (!fromdomain ||
  11113. ((ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_YES) &&
  11114. !strcmp("anonymous.invalid", fromdomain))) {
  11115. /* If the fromdomain is NULL or if it was set to anonymous.invalid due to privacy settings and we trust the peer,
  11116. * use the host IP address */
  11117. fromdomain = ast_sockaddr_stringify_host_remote(&p->ourip);
  11118. }
  11119. lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), ast_uri_sip_user);
  11120. if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
  11121. if (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) != SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY) {
  11122. /* trust_id_outbound = yes - Always give full information even if it's private, but append a privacy header
  11123. * When private data is included */
  11124. ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name_buf, lid_num, fromdomain);
  11125. if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  11126. add_header(req, "Privacy", "id");
  11127. }
  11128. } else {
  11129. /* trust_id_outbound = legacy - behave in a non RFC-3325 compliant manner and send anonymized data when
  11130. * when handling private data. */
  11131. if ((lid_pres & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
  11132. ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name_buf, lid_num, fromdomain);
  11133. } else {
  11134. ast_str_set(&tmp, -1, "%s", anonymous_string);
  11135. }
  11136. }
  11137. add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
  11138. } else {
  11139. ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name_buf, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
  11140. switch (lid_pres) {
  11141. case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
  11142. case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
  11143. privacy = "off";
  11144. screen = "no";
  11145. break;
  11146. case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
  11147. case AST_PRES_ALLOWED_NETWORK_NUMBER:
  11148. privacy = "off";
  11149. screen = "yes";
  11150. break;
  11151. case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
  11152. case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
  11153. privacy = "full";
  11154. screen = "no";
  11155. break;
  11156. case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
  11157. case AST_PRES_PROHIB_NETWORK_NUMBER:
  11158. privacy = "full";
  11159. screen = "yes";
  11160. break;
  11161. case AST_PRES_NUMBER_NOT_AVAILABLE:
  11162. break;
  11163. default:
  11164. if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  11165. privacy = "full";
  11166. }
  11167. else
  11168. privacy = "off";
  11169. screen = "no";
  11170. break;
  11171. }
  11172. if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
  11173. ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
  11174. }
  11175. add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
  11176. }
  11177. return 0;
  11178. }
  11179. /*! \brief add XML encoded media control with update
  11180. \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
  11181. static int add_vidupdate(struct sip_request *req)
  11182. {
  11183. const char *xml_is_a_huge_waste_of_space =
  11184. "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
  11185. " <media_control>\r\n"
  11186. " <vc_primitive>\r\n"
  11187. " <to_encoder>\r\n"
  11188. " <picture_fast_update>\r\n"
  11189. " </picture_fast_update>\r\n"
  11190. " </to_encoder>\r\n"
  11191. " </vc_primitive>\r\n"
  11192. " </media_control>\r\n";
  11193. add_header(req, "Content-Type", "application/media_control+xml");
  11194. add_content(req, xml_is_a_huge_waste_of_space);
  11195. return 0;
  11196. }
  11197. /*! \brief Add ICE attributes to SDP */
  11198. static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
  11199. {
  11200. struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
  11201. const char *username, *password;
  11202. struct ao2_container *candidates;
  11203. struct ao2_iterator i;
  11204. struct ast_rtp_engine_ice_candidate *candidate;
  11205. /* If no ICE support is present we can't very well add the attributes */
  11206. if (!ice || !(candidates = ice->get_local_candidates(instance))) {
  11207. return;
  11208. }
  11209. if ((username = ice->get_ufrag(instance))) {
  11210. ast_str_append(a_buf, 0, "a=ice-ufrag:%s\r\n", username);
  11211. }
  11212. if ((password = ice->get_password(instance))) {
  11213. ast_str_append(a_buf, 0, "a=ice-pwd:%s\r\n", password);
  11214. }
  11215. i = ao2_iterator_init(candidates, 0);
  11216. while ((candidate = ao2_iterator_next(&i))) {
  11217. ast_str_append(a_buf, 0, "a=candidate:%s %u %s %d ", candidate->foundation, candidate->id, candidate->transport, candidate->priority);
  11218. ast_str_append(a_buf, 0, "%s ", ast_sockaddr_stringify_host(&candidate->address));
  11219. ast_str_append(a_buf, 0, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
  11220. if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
  11221. ast_str_append(a_buf, 0, "host");
  11222. } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
  11223. ast_str_append(a_buf, 0, "srflx");
  11224. } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
  11225. ast_str_append(a_buf, 0, "relay");
  11226. }
  11227. if (!ast_sockaddr_isnull(&candidate->relay_address)) {
  11228. ast_str_append(a_buf, 0, " raddr %s ", ast_sockaddr_stringify_host(&candidate->relay_address));
  11229. ast_str_append(a_buf, 0, "rport %s", ast_sockaddr_stringify_port(&candidate->relay_address));
  11230. }
  11231. ast_str_append(a_buf, 0, "\r\n");
  11232. ao2_ref(candidate, -1);
  11233. }
  11234. ao2_iterator_destroy(&i);
  11235. ao2_ref(candidates, -1);
  11236. }
  11237. /*! \brief Start ICE negotiation on an RTP instance */
  11238. static void start_ice(struct ast_rtp_instance *instance, int offer)
  11239. {
  11240. struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
  11241. if (!ice) {
  11242. return;
  11243. }
  11244. /* If we are the offerer then we are the controlling agent, otherwise they are */
  11245. ice->set_role(instance, offer ? AST_RTP_ICE_ROLE_CONTROLLING : AST_RTP_ICE_ROLE_CONTROLLED);
  11246. ice->start(instance);
  11247. }
  11248. /*! \brief Add DTLS attributes to SDP */
  11249. static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
  11250. {
  11251. struct ast_rtp_engine_dtls *dtls;
  11252. enum ast_rtp_dtls_hash hash;
  11253. const char *fingerprint;
  11254. if (!instance || !(dtls = ast_rtp_instance_get_dtls(instance)) || !dtls->active(instance)) {
  11255. return;
  11256. }
  11257. switch (dtls->get_connection(instance)) {
  11258. case AST_RTP_DTLS_CONNECTION_NEW:
  11259. ast_str_append(a_buf, 0, "a=connection:new\r\n");
  11260. break;
  11261. case AST_RTP_DTLS_CONNECTION_EXISTING:
  11262. ast_str_append(a_buf, 0, "a=connection:existing\r\n");
  11263. break;
  11264. default:
  11265. break;
  11266. }
  11267. switch (dtls->get_setup(instance)) {
  11268. case AST_RTP_DTLS_SETUP_ACTIVE:
  11269. ast_str_append(a_buf, 0, "a=setup:active\r\n");
  11270. break;
  11271. case AST_RTP_DTLS_SETUP_PASSIVE:
  11272. ast_str_append(a_buf, 0, "a=setup:passive\r\n");
  11273. break;
  11274. case AST_RTP_DTLS_SETUP_ACTPASS:
  11275. ast_str_append(a_buf, 0, "a=setup:actpass\r\n");
  11276. break;
  11277. case AST_RTP_DTLS_SETUP_HOLDCONN:
  11278. ast_str_append(a_buf, 0, "a=setup:holdconn\r\n");
  11279. break;
  11280. default:
  11281. break;
  11282. }
  11283. hash = dtls->get_fingerprint_hash(instance);
  11284. fingerprint = dtls->get_fingerprint(instance);
  11285. if (fingerprint && (hash == AST_RTP_DTLS_HASH_SHA1 || hash == AST_RTP_DTLS_HASH_SHA256)) {
  11286. ast_str_append(a_buf, 0, "a=fingerprint:%s %s\r\n", hash == AST_RTP_DTLS_HASH_SHA1 ? "SHA-1" : "SHA-256",
  11287. fingerprint);
  11288. }
  11289. }
  11290. /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
  11291. static void add_codec_to_sdp(const struct sip_pvt *p,
  11292. struct ast_format *format,
  11293. struct ast_str **m_buf,
  11294. struct ast_str **a_buf,
  11295. int debug,
  11296. int *min_packet_size,
  11297. int *max_packet_size)
  11298. {
  11299. int rtp_code;
  11300. const char *mime;
  11301. unsigned int rate, framing;
  11302. if (debug)
  11303. ast_verbose("Adding codec %s to SDP\n", ast_format_get_name(format));
  11304. if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, format, 0)) == -1) ||
  11305. !(mime = ast_rtp_lookup_mime_subtype2(1, format, 0, ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0)) ||
  11306. !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
  11307. return;
  11308. }
  11309. ast_str_append(m_buf, 0, " %d", rtp_code);
  11310. /* Opus mandates 2 channels in rtpmap */
  11311. if (ast_format_cmp(format, ast_format_opus) == AST_FORMAT_CMP_EQUAL) {
  11312. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u/2\r\n", rtp_code, mime, rate);
  11313. } else {
  11314. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code, mime, rate);
  11315. }
  11316. ast_format_generate_sdp_fmtp(format, rtp_code, a_buf);
  11317. framing = ast_format_cap_get_format_framing(p->caps, format);
  11318. if (ast_format_cmp(format, ast_format_g729) == AST_FORMAT_CMP_EQUAL) {
  11319. /* Indicate that we don't support VAD (G.729 annex B) */
  11320. ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
  11321. } else if (ast_format_cmp(format, ast_format_g723) == AST_FORMAT_CMP_EQUAL) {
  11322. /* Indicate that we don't support VAD (G.723.1 annex A) */
  11323. ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
  11324. } else if (ast_format_cmp(format, ast_format_ilbc) == AST_FORMAT_CMP_EQUAL) {
  11325. /* Add information about us using only 20/30 ms packetization */
  11326. ast_str_append(a_buf, 0, "a=fmtp:%d mode=%u\r\n", rtp_code, framing);
  11327. } else if (ast_format_cmp(format, ast_format_siren7) == AST_FORMAT_CMP_EQUAL) {
  11328. /* Indicate that we only expect 32Kbps */
  11329. ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
  11330. } else if (ast_format_cmp(format, ast_format_siren14) == AST_FORMAT_CMP_EQUAL) {
  11331. /* Indicate that we only expect 48Kbps */
  11332. ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
  11333. } else if (ast_format_cmp(format, ast_format_g719) == AST_FORMAT_CMP_EQUAL) {
  11334. /* Indicate that we only expect 64Kbps */
  11335. ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
  11336. }
  11337. if (max_packet_size && ast_format_get_maximum_ms(format) &&
  11338. (ast_format_get_maximum_ms(format) < *max_packet_size)) {
  11339. *max_packet_size = ast_format_get_maximum_ms(format);
  11340. }
  11341. if (framing && (framing < *min_packet_size)) {
  11342. *min_packet_size = framing;
  11343. }
  11344. /* Our first codec packetization processed cannot be zero */
  11345. if ((*min_packet_size) == 0 && framing) {
  11346. *min_packet_size = framing;
  11347. }
  11348. if ((*max_packet_size) == 0 && ast_format_get_maximum_ms(format)) {
  11349. *max_packet_size = ast_format_get_maximum_ms(format);
  11350. }
  11351. }
  11352. /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
  11353. /* This is different to the audio one now so we can add more caps later */
  11354. static void add_vcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
  11355. struct ast_str **m_buf, struct ast_str **a_buf,
  11356. int debug, int *min_packet_size)
  11357. {
  11358. int rtp_code;
  11359. const char *subtype;
  11360. unsigned int rate;
  11361. if (!p->vrtp)
  11362. return;
  11363. if (debug)
  11364. ast_verbose("Adding video codec %s to SDP\n", ast_format_get_name(format));
  11365. if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, format, 0)) == -1) ||
  11366. !(subtype = ast_rtp_lookup_mime_subtype2(1, format, 0, 0)) ||
  11367. !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
  11368. return;
  11369. }
  11370. ast_str_append(m_buf, 0, " %d", rtp_code);
  11371. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code, subtype, rate);
  11372. /* VP8: add RTCP FIR support */
  11373. if (ast_format_cmp(format, ast_format_vp8) == AST_FORMAT_CMP_EQUAL) {
  11374. ast_str_append(a_buf, 0, "a=rtcp-fb:* ccm fir\r\n");
  11375. }
  11376. ast_format_generate_sdp_fmtp(format, rtp_code, a_buf);
  11377. }
  11378. /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
  11379. static void add_tcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
  11380. struct ast_str **m_buf, struct ast_str **a_buf,
  11381. int debug, int *min_packet_size)
  11382. {
  11383. int rtp_code;
  11384. if (!p->trtp)
  11385. return;
  11386. if (debug)
  11387. ast_verbose("Adding text codec %s to SDP\n", ast_format_get_name(format));
  11388. if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, format, 0)) == -1)
  11389. return;
  11390. ast_str_append(m_buf, 0, " %d", rtp_code);
  11391. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
  11392. ast_rtp_lookup_mime_subtype2(1, format, 0, 0),
  11393. ast_rtp_lookup_sample_rate2(1, format, 0));
  11394. /* Add fmtp code here */
  11395. if (ast_format_cmp(format, ast_format_t140_red) == AST_FORMAT_CMP_EQUAL) {
  11396. int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, ast_format_t140, 0);
  11397. ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
  11398. t140code,
  11399. t140code,
  11400. t140code);
  11401. }
  11402. }
  11403. /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
  11404. static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
  11405. {
  11406. switch (rate) {
  11407. case AST_T38_RATE_2400:
  11408. return 2400;
  11409. case AST_T38_RATE_4800:
  11410. return 4800;
  11411. case AST_T38_RATE_7200:
  11412. return 7200;
  11413. case AST_T38_RATE_9600:
  11414. return 9600;
  11415. case AST_T38_RATE_12000:
  11416. return 12000;
  11417. case AST_T38_RATE_14400:
  11418. return 14400;
  11419. default:
  11420. return 0;
  11421. }
  11422. }
  11423. /*! \brief Add RFC 2833 DTMF offer to SDP */
  11424. static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
  11425. struct ast_str **m_buf, struct ast_str **a_buf,
  11426. int debug)
  11427. {
  11428. int rtp_code;
  11429. if (debug)
  11430. ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", (unsigned)format, ast_rtp_lookup_mime_subtype2(0, NULL, format, 0));
  11431. if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, NULL, format)) == -1)
  11432. return;
  11433. ast_str_append(m_buf, 0, " %d", rtp_code);
  11434. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
  11435. ast_rtp_lookup_mime_subtype2(0, NULL, format, 0),
  11436. ast_rtp_lookup_sample_rate2(0, NULL, format));
  11437. if (format == AST_RTP_DTMF) /* Indicate we support DTMF and FLASH... */
  11438. ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
  11439. }
  11440. /*! \brief Set all IP media addresses for this call
  11441. \note called from add_sdp()
  11442. */
  11443. static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
  11444. struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
  11445. struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
  11446. struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
  11447. {
  11448. int use_externip = 0;
  11449. /* First, get our address */
  11450. ast_rtp_instance_get_local_address(p->rtp, addr);
  11451. if (p->vrtp) {
  11452. ast_rtp_instance_get_local_address(p->vrtp, vaddr);
  11453. }
  11454. if (p->trtp) {
  11455. ast_rtp_instance_get_local_address(p->trtp, taddr);
  11456. }
  11457. /* If our real IP differs from the local address returned by the RTP engine, use it. */
  11458. /* The premise is that if we are already using that IP to communicate with the client, */
  11459. /* we should be using it for RTP too. */
  11460. use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
  11461. /* Now, try to figure out where we want them to send data */
  11462. /* Is this a re-invite to move the media out, then use the original offer from caller */
  11463. if (!ast_sockaddr_isnull(&p->redirip)) { /* If we have a redirection IP, use it */
  11464. ast_sockaddr_copy(dest, &p->redirip);
  11465. } else {
  11466. /*
  11467. * Audio Destination IP:
  11468. *
  11469. * 1. Specifically configured media address.
  11470. * 2. Local address as specified by the RTP engine.
  11471. * 3. The local IP as defined by chan_sip.
  11472. *
  11473. * Audio Destination Port:
  11474. *
  11475. * 1. Provided by the RTP engine.
  11476. */
  11477. ast_sockaddr_copy(dest,
  11478. !ast_sockaddr_isnull(&media_address) ? &media_address :
  11479. !ast_sockaddr_is_any(addr) && !use_externip ? addr :
  11480. &p->ourip);
  11481. ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
  11482. }
  11483. if (needvideo) {
  11484. /* Determine video destination */
  11485. if (!ast_sockaddr_isnull(&p->vredirip)) {
  11486. ast_sockaddr_copy(vdest, &p->vredirip);
  11487. } else {
  11488. /*
  11489. * Video Destination IP:
  11490. *
  11491. * 1. Specifically configured media address.
  11492. * 2. Local address as specified by the RTP engine.
  11493. * 3. The local IP as defined by chan_sip.
  11494. *
  11495. * Video Destination Port:
  11496. *
  11497. * 1. Provided by the RTP engine.
  11498. */
  11499. ast_sockaddr_copy(vdest,
  11500. !ast_sockaddr_isnull(&media_address) ? &media_address :
  11501. !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr :
  11502. &p->ourip);
  11503. ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
  11504. }
  11505. }
  11506. if (needtext) {
  11507. /* Determine text destination */
  11508. if (!ast_sockaddr_isnull(&p->tredirip)) {
  11509. ast_sockaddr_copy(tdest, &p->tredirip);
  11510. } else {
  11511. /*
  11512. * Text Destination IP:
  11513. *
  11514. * 1. Specifically configured media address.
  11515. * 2. Local address as specified by the RTP engine.
  11516. * 3. The local IP as defined by chan_sip.
  11517. *
  11518. * Text Destination Port:
  11519. *
  11520. * 1. Provided by the RTP engine.
  11521. */
  11522. ast_sockaddr_copy(tdest,
  11523. !ast_sockaddr_isnull(&media_address) ? &media_address :
  11524. !ast_sockaddr_is_any(taddr) && !use_externip ? taddr :
  11525. &p->ourip);
  11526. ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
  11527. }
  11528. }
  11529. }
  11530. static char *crypto_get_attrib(struct ast_sdp_srtp *srtp, int dtls_enabled, int default_taglen_32)
  11531. {
  11532. char *a_crypto;
  11533. const char *orig_crypto;
  11534. if (!srtp || dtls_enabled) {
  11535. return NULL;
  11536. }
  11537. orig_crypto = ast_sdp_srtp_get_attrib(srtp, dtls_enabled, default_taglen_32);
  11538. if (ast_strlen_zero(orig_crypto)) {
  11539. return NULL;
  11540. }
  11541. if (ast_asprintf(&a_crypto, "a=crypto:%s\r\n", orig_crypto) == -1) {
  11542. return NULL;
  11543. }
  11544. return a_crypto;
  11545. }
  11546. /*! \brief Add Session Description Protocol message
  11547. If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
  11548. is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
  11549. without modifying the media session in any way.
  11550. */
  11551. static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
  11552. {
  11553. struct ast_format_cap *alreadysent = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  11554. struct ast_format_cap *tmpcap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  11555. int res = AST_SUCCESS;
  11556. int doing_directmedia = FALSE;
  11557. struct ast_sockaddr addr = { {0,} };
  11558. struct ast_sockaddr vaddr = { {0,} };
  11559. struct ast_sockaddr taddr = { {0,} };
  11560. struct ast_sockaddr udptladdr = { {0,} };
  11561. struct ast_sockaddr dest = { {0,} };
  11562. struct ast_sockaddr vdest = { {0,} };
  11563. struct ast_sockaddr tdest = { {0,} };
  11564. struct ast_sockaddr udptldest = { {0,} };
  11565. /* SDP fields */
  11566. struct offered_media *offer;
  11567. char *version = "v=0\r\n"; /* Protocol version */
  11568. char subject[256]; /* Subject of the session */
  11569. char owner[256]; /* Session owner/creator */
  11570. char connection[256]; /* Connection data */
  11571. char *session_time = "t=0 0\r\n"; /* Time the session is active */
  11572. char bandwidth[256] = ""; /* Max bitrate */
  11573. char *hold = "";
  11574. struct ast_str *m_audio = ast_str_alloca(256); /* Media declaration line for audio */
  11575. struct ast_str *m_video = ast_str_alloca(256); /* Media declaration line for video */
  11576. struct ast_str *m_text = ast_str_alloca(256); /* Media declaration line for text */
  11577. struct ast_str *m_modem = ast_str_alloca(256); /* Media declaration line for modem */
  11578. struct ast_str *a_audio = ast_str_create(256); /* Attributes for audio */
  11579. struct ast_str *a_video = ast_str_create(256); /* Attributes for video */
  11580. struct ast_str *a_text = ast_str_create(256); /* Attributes for text */
  11581. struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
  11582. RAII_VAR(char *, a_crypto, NULL, ast_free);
  11583. RAII_VAR(char *, v_a_crypto, NULL, ast_free);
  11584. RAII_VAR(char *, t_a_crypto, NULL, ast_free);
  11585. int x;
  11586. struct ast_format *tmp_fmt;
  11587. int needaudio = FALSE;
  11588. int needvideo = FALSE;
  11589. int needtext = FALSE;
  11590. int debug = sip_debug_test_pvt(p);
  11591. int min_audio_packet_size = 0;
  11592. int max_audio_packet_size = 0;
  11593. int min_video_packet_size = 0;
  11594. int min_text_packet_size = 0;
  11595. struct ast_str *codec_buf = ast_str_alloca(64);
  11596. /* Set the SDP session name */
  11597. snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
  11598. if (!alreadysent || !tmpcap) {
  11599. res = AST_FAILURE;
  11600. goto add_sdp_cleanup;
  11601. }
  11602. if (!p->rtp) {
  11603. ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
  11604. res = AST_FAILURE;
  11605. goto add_sdp_cleanup;
  11606. }
  11607. /* XXX We should not change properties in the SIP dialog until
  11608. we have acceptance of the offer if this is a re-invite */
  11609. /* Set RTP Session ID and version */
  11610. if (!p->sessionid) {
  11611. p->sessionid = (int)ast_random();
  11612. p->sessionversion = p->sessionid;
  11613. } else {
  11614. if (oldsdp == FALSE)
  11615. p->sessionversion++;
  11616. }
  11617. if (add_audio) {
  11618. doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && (ast_format_cap_count(p->redircaps))) ? TRUE : FALSE;
  11619. if (doing_directmedia) {
  11620. ast_format_cap_get_compatible(p->jointcaps, p->redircaps, tmpcap);
  11621. ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_format_cap_get_names(tmpcap, &codec_buf));
  11622. } else {
  11623. ast_format_cap_append_from_cap(tmpcap, p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  11624. }
  11625. /* Check if we need audio */
  11626. if (ast_format_cap_has_type(tmpcap, AST_MEDIA_TYPE_AUDIO)
  11627. || ast_format_cap_has_type(p->caps, AST_MEDIA_TYPE_AUDIO)) {
  11628. needaudio = TRUE;
  11629. }
  11630. /* Check if we need video in this call */
  11631. if ((ast_format_cap_has_type(tmpcap, AST_MEDIA_TYPE_VIDEO)) && !p->novideo) {
  11632. if (doing_directmedia && !ast_format_cap_has_type(tmpcap, AST_MEDIA_TYPE_VIDEO)) {
  11633. ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
  11634. } else if (p->vrtp) {
  11635. needvideo = TRUE;
  11636. ast_debug(2, "This call needs video offers!\n");
  11637. } else {
  11638. ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
  11639. }
  11640. }
  11641. /* Check if we need text in this call */
  11642. if ((ast_format_cap_has_type(p->jointcaps, AST_MEDIA_TYPE_TEXT)) && !p->notext) {
  11643. if (sipdebug_text)
  11644. ast_verbose("We think we can do text\n");
  11645. if (p->trtp) {
  11646. if (sipdebug_text) {
  11647. ast_verbose("And we have a text rtp object\n");
  11648. }
  11649. needtext = TRUE;
  11650. ast_debug(2, "This call needs text offers! \n");
  11651. } else {
  11652. ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
  11653. }
  11654. }
  11655. /* XXX note, Video and Text are negated - 'true' means 'no' */
  11656. ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n",
  11657. ast_format_cap_get_names(tmpcap, &codec_buf),
  11658. p->novideo ? "True" : "False", p->notext ? "True" : "False");
  11659. ast_debug(1, "** Our prefcodec: %s \n", ast_format_cap_get_names(p->prefcaps, &codec_buf));
  11660. }
  11661. get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
  11662. snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
  11663. ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
  11664. p->sessionid, p->sessionversion,
  11665. (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
  11666. "IP6" : "IP4",
  11667. ast_sockaddr_stringify_addr_remote(&dest));
  11668. snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
  11669. (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
  11670. "IP6" : "IP4",
  11671. ast_sockaddr_stringify_addr_remote(&dest));
  11672. if (add_audio) {
  11673. if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
  11674. hold = "a=recvonly\r\n";
  11675. doing_directmedia = FALSE;
  11676. } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
  11677. hold = "a=inactive\r\n";
  11678. doing_directmedia = FALSE;
  11679. } else {
  11680. hold = "a=sendrecv\r\n";
  11681. }
  11682. if (debug) {
  11683. ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
  11684. }
  11685. /* Ok, we need video. Let's add what we need for video and set codecs.
  11686. Video is handled differently than audio since we can not transcode. */
  11687. if (needvideo) {
  11688. v_a_crypto = crypto_get_attrib(p->vsrtp, p->dtls_cfg.enabled,
  11689. ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32));
  11690. ast_str_append(&m_video, 0, "m=video %d %s", ast_sockaddr_port(&vdest),
  11691. ast_sdp_get_rtp_profile(v_a_crypto ? 1 : 0, p->vrtp,
  11692. ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF),
  11693. ast_test_flag(&p->flags[2], SIP_PAGE3_FORCE_AVP)));
  11694. /* Build max bitrate string */
  11695. if (p->maxcallbitrate)
  11696. snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
  11697. if (debug) {
  11698. ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
  11699. }
  11700. if (!doing_directmedia) {
  11701. if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
  11702. add_ice_to_sdp(p->vrtp, &a_video);
  11703. }
  11704. add_dtls_to_sdp(p->vrtp, &a_video);
  11705. }
  11706. }
  11707. /* Ok, we need text. Let's add what we need for text and set codecs.
  11708. Text is handled differently than audio since we can not transcode. */
  11709. if (needtext) {
  11710. if (sipdebug_text)
  11711. ast_verbose("Lets set up the text sdp\n");
  11712. t_a_crypto = crypto_get_attrib(p->tsrtp, p->dtls_cfg.enabled,
  11713. ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32));
  11714. ast_str_append(&m_text, 0, "m=text %d %s", ast_sockaddr_port(&tdest),
  11715. ast_sdp_get_rtp_profile(t_a_crypto ? 1 : 0, p->trtp,
  11716. ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF),
  11717. ast_test_flag(&p->flags[2], SIP_PAGE3_FORCE_AVP)));
  11718. if (debug) { /* XXX should I use tdest below ? */
  11719. ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
  11720. }
  11721. if (!doing_directmedia) {
  11722. if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
  11723. add_ice_to_sdp(p->trtp, &a_text);
  11724. }
  11725. add_dtls_to_sdp(p->trtp, &a_text);
  11726. }
  11727. }
  11728. /* Start building generic SDP headers */
  11729. /* We break with the "recommendation" and send our IP, in order that our
  11730. peer doesn't have to ast_gethostbyname() us */
  11731. a_crypto = crypto_get_attrib(p->srtp, p->dtls_cfg.enabled,
  11732. ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32));
  11733. ast_str_append(&m_audio, 0, "m=audio %d %s", ast_sockaddr_port(&dest),
  11734. ast_sdp_get_rtp_profile(a_crypto ? 1 : 0, p->rtp,
  11735. ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF),
  11736. ast_test_flag(&p->flags[2], SIP_PAGE3_FORCE_AVP)));
  11737. /* Now, start adding audio codecs. These are added in this order:
  11738. - First what was requested by the calling channel
  11739. - Then our mutually shared capabilities, determined previous in tmpcap
  11740. - Then preferences in order from sip.conf device config for this peer/user
  11741. */
  11742. /* Unless otherwise configured, the prefcaps is added before the peer's
  11743. * configured codecs.
  11744. */
  11745. if (!ast_test_flag(&p->flags[2], SIP_PAGE3_IGNORE_PREFCAPS)) {
  11746. for (x = 0; x < ast_format_cap_count(p->prefcaps); x++) {
  11747. tmp_fmt = ast_format_cap_get_format(p->prefcaps, x);
  11748. if ((ast_format_get_type(tmp_fmt) != AST_MEDIA_TYPE_AUDIO) ||
  11749. (ast_format_cap_iscompatible_format(tmpcap, tmp_fmt) == AST_FORMAT_CMP_NOT_EQUAL)) {
  11750. ao2_ref(tmp_fmt, -1);
  11751. continue;
  11752. }
  11753. add_codec_to_sdp(p, tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size, &max_audio_packet_size);
  11754. ast_format_cap_append(alreadysent, tmp_fmt, 0);
  11755. ao2_ref(tmp_fmt, -1);
  11756. }
  11757. }
  11758. /* Now send any other common codecs */
  11759. for (x = 0; x < ast_format_cap_count(tmpcap); x++) {
  11760. tmp_fmt = ast_format_cap_get_format(tmpcap, x);
  11761. if (ast_format_cap_iscompatible_format(alreadysent, tmp_fmt) != AST_FORMAT_CMP_NOT_EQUAL) {
  11762. ao2_ref(tmp_fmt, -1);
  11763. continue;
  11764. }
  11765. if (ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_AUDIO) {
  11766. add_codec_to_sdp(p, tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size, &max_audio_packet_size);
  11767. } else if (needvideo && ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_VIDEO) {
  11768. add_vcodec_to_sdp(p, tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
  11769. } else if (needtext && ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_TEXT) {
  11770. add_tcodec_to_sdp(p, tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
  11771. }
  11772. ast_format_cap_append(alreadysent, tmp_fmt, 0);
  11773. ao2_ref(tmp_fmt, -1);
  11774. }
  11775. /* Finally our remaining audio/video codecs */
  11776. for (x = 0; x < ast_format_cap_count(p->caps); x++) {
  11777. tmp_fmt = ast_format_cap_get_format(p->caps, x);
  11778. if (ast_format_cap_iscompatible_format(alreadysent, tmp_fmt) != AST_FORMAT_CMP_NOT_EQUAL) {
  11779. ao2_ref(tmp_fmt, -1);
  11780. continue;
  11781. }
  11782. if (ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_AUDIO) {
  11783. add_codec_to_sdp(p, tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size, &max_audio_packet_size);
  11784. } else if (needvideo && ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_VIDEO) {
  11785. add_vcodec_to_sdp(p, tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
  11786. } else if (needtext && ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_TEXT) {
  11787. add_tcodec_to_sdp(p, tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
  11788. }
  11789. ast_format_cap_append(alreadysent, tmp_fmt, 0);
  11790. ao2_ref(tmp_fmt, -1);
  11791. }
  11792. /* Now add DTMF RFC2833 telephony-event as a codec */
  11793. for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
  11794. if (!(p->jointnoncodeccapability & x))
  11795. continue;
  11796. add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
  11797. }
  11798. ast_debug(3, "-- Done with adding codecs to SDP\n");
  11799. if (!p->owner || ast_channel_timingfd(p->owner) == -1) {
  11800. ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
  11801. }
  11802. if (min_audio_packet_size) {
  11803. ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
  11804. }
  11805. /* XXX don't think you can have ptime for video */
  11806. if (min_video_packet_size) {
  11807. ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
  11808. }
  11809. /* XXX don't think you can have ptime for text */
  11810. if (min_text_packet_size) {
  11811. ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
  11812. }
  11813. if (max_audio_packet_size) {
  11814. ast_str_append(&a_audio, 0, "a=maxptime:%d\r\n", max_audio_packet_size);
  11815. }
  11816. if (!doing_directmedia) {
  11817. if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
  11818. add_ice_to_sdp(p->rtp, &a_audio);
  11819. }
  11820. add_dtls_to_sdp(p->rtp, &a_audio);
  11821. }
  11822. }
  11823. if (add_t38) {
  11824. /* Our T.38 end is */
  11825. ast_udptl_get_us(p->udptl, &udptladdr);
  11826. /* We don't use directmedia for T.38, so keep the destination the same as our IP address. */
  11827. ast_sockaddr_copy(&udptldest, &p->ourip);
  11828. ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
  11829. if (debug) {
  11830. ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
  11831. }
  11832. /* We break with the "recommendation" and send our IP, in order that our
  11833. peer doesn't have to ast_gethostbyname() us */
  11834. ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
  11835. if (ast_sockaddr_cmp(&udptldest, &dest)) {
  11836. ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
  11837. (ast_sockaddr_is_ipv6(&udptldest) && !ast_sockaddr_is_ipv4_mapped(&udptldest)) ?
  11838. "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
  11839. }
  11840. ast_str_append(&a_modem, 0, "a=T38FaxVersion:%u\r\n", p->t38.our_parms.version);
  11841. ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%u\r\n", t38_get_rate(p->t38.our_parms.rate));
  11842. if (p->t38.our_parms.fill_bit_removal) {
  11843. ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
  11844. }
  11845. if (p->t38.our_parms.transcoding_mmr) {
  11846. ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
  11847. }
  11848. if (p->t38.our_parms.transcoding_jbig) {
  11849. ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
  11850. }
  11851. switch (p->t38.our_parms.rate_management) {
  11852. case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
  11853. ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
  11854. break;
  11855. case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
  11856. ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
  11857. break;
  11858. }
  11859. ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
  11860. switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
  11861. case UDPTL_ERROR_CORRECTION_NONE:
  11862. break;
  11863. case UDPTL_ERROR_CORRECTION_FEC:
  11864. ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
  11865. break;
  11866. case UDPTL_ERROR_CORRECTION_REDUNDANCY:
  11867. ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
  11868. break;
  11869. }
  11870. }
  11871. if (needaudio)
  11872. ast_str_append(&m_audio, 0, "\r\n");
  11873. if (needvideo)
  11874. ast_str_append(&m_video, 0, "\r\n");
  11875. if (needtext)
  11876. ast_str_append(&m_text, 0, "\r\n");
  11877. add_header(resp, "Content-Type", "application/sdp");
  11878. add_content(resp, version);
  11879. add_content(resp, owner);
  11880. add_content(resp, subject);
  11881. add_content(resp, connection);
  11882. /* only if video response is appropriate */
  11883. if (needvideo) {
  11884. add_content(resp, bandwidth);
  11885. }
  11886. add_content(resp, session_time);
  11887. /* if this is a response to an invite, order our offers properly */
  11888. if (!AST_LIST_EMPTY(&p->offered_media)) {
  11889. AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
  11890. switch (offer->type) {
  11891. case SDP_AUDIO:
  11892. if (needaudio) {
  11893. add_content(resp, ast_str_buffer(m_audio));
  11894. add_content(resp, ast_str_buffer(a_audio));
  11895. add_content(resp, hold);
  11896. if (a_crypto) {
  11897. add_content(resp, a_crypto);
  11898. }
  11899. } else {
  11900. add_content(resp, offer->decline_m_line);
  11901. }
  11902. break;
  11903. case SDP_VIDEO:
  11904. if (needvideo) { /* only if video response is appropriate */
  11905. add_content(resp, ast_str_buffer(m_video));
  11906. add_content(resp, ast_str_buffer(a_video));
  11907. add_content(resp, hold); /* Repeat hold for the video stream */
  11908. if (v_a_crypto) {
  11909. add_content(resp, v_a_crypto);
  11910. }
  11911. } else {
  11912. add_content(resp, offer->decline_m_line);
  11913. }
  11914. break;
  11915. case SDP_TEXT:
  11916. if (needtext) { /* only if text response is appropriate */
  11917. add_content(resp, ast_str_buffer(m_text));
  11918. add_content(resp, ast_str_buffer(a_text));
  11919. add_content(resp, hold); /* Repeat hold for the text stream */
  11920. if (t_a_crypto) {
  11921. add_content(resp, t_a_crypto);
  11922. }
  11923. } else {
  11924. add_content(resp, offer->decline_m_line);
  11925. }
  11926. break;
  11927. case SDP_IMAGE:
  11928. if (add_t38) {
  11929. add_content(resp, ast_str_buffer(m_modem));
  11930. add_content(resp, ast_str_buffer(a_modem));
  11931. } else {
  11932. add_content(resp, offer->decline_m_line);
  11933. }
  11934. break;
  11935. case SDP_UNKNOWN:
  11936. add_content(resp, offer->decline_m_line);
  11937. break;
  11938. }
  11939. }
  11940. } else {
  11941. /* generate new SDP from scratch, no offers */
  11942. if (needaudio) {
  11943. add_content(resp, ast_str_buffer(m_audio));
  11944. add_content(resp, ast_str_buffer(a_audio));
  11945. add_content(resp, hold);
  11946. if (a_crypto) {
  11947. add_content(resp, a_crypto);
  11948. }
  11949. }
  11950. if (needvideo) { /* only if video response is appropriate */
  11951. add_content(resp, ast_str_buffer(m_video));
  11952. add_content(resp, ast_str_buffer(a_video));
  11953. add_content(resp, hold); /* Repeat hold for the video stream */
  11954. if (v_a_crypto) {
  11955. add_content(resp, v_a_crypto);
  11956. }
  11957. }
  11958. if (needtext) { /* only if text response is appropriate */
  11959. add_content(resp, ast_str_buffer(m_text));
  11960. add_content(resp, ast_str_buffer(a_text));
  11961. add_content(resp, hold); /* Repeat hold for the text stream */
  11962. if (t_a_crypto) {
  11963. add_content(resp, t_a_crypto);
  11964. }
  11965. }
  11966. if (add_t38) {
  11967. add_content(resp, ast_str_buffer(m_modem));
  11968. add_content(resp, ast_str_buffer(a_modem));
  11969. }
  11970. }
  11971. /* Update lastrtprx when we send our SDP */
  11972. p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
  11973. /*
  11974. * We unlink this dialog and link again into the
  11975. * dialogs_rtpcheck container so its not in there twice.
  11976. */
  11977. ao2_lock(dialogs_rtpcheck);
  11978. ao2_t_unlink(dialogs_rtpcheck, p, "unlink pvt into dialogs_rtpcheck container");
  11979. ao2_t_link(dialogs_rtpcheck, p, "link pvt into dialogs_rtpcheck container");
  11980. ao2_unlock(dialogs_rtpcheck);
  11981. ast_debug(3, "Done building SDP. Settling with this capability: %s\n",
  11982. ast_format_cap_get_names(tmpcap, &codec_buf));
  11983. add_sdp_cleanup:
  11984. ast_free(a_text);
  11985. ast_free(a_video);
  11986. ast_free(a_audio);
  11987. ao2_cleanup(alreadysent);
  11988. ao2_cleanup(tmpcap);
  11989. return res;
  11990. }
  11991. /*! \brief Used for 200 OK and 183 early media */
  11992. static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
  11993. {
  11994. struct sip_request resp;
  11995. uint32_t seqno;
  11996. if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
  11997. ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
  11998. return -1;
  11999. }
  12000. respprep(&resp, p, msg, req);
  12001. if (p->udptl) {
  12002. add_sdp(&resp, p, 0, 0, 1);
  12003. } else
  12004. ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
  12005. if (retrans && !p->pendinginvite)
  12006. p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
  12007. return send_response(p, &resp, retrans, seqno);
  12008. }
  12009. /*! \brief copy SIP request (mostly used to save request for responses) */
  12010. static void copy_request(struct sip_request *dst, const struct sip_request *src)
  12011. {
  12012. /* XXX this function can encounter memory allocation errors, perhaps it
  12013. * should return a value */
  12014. struct ast_str *duplicate = dst->data;
  12015. struct ast_str *duplicate_content = dst->content;
  12016. /* copy the entire request then restore the original data and content
  12017. * members from the dst request */
  12018. *dst = *src;
  12019. dst->data = duplicate;
  12020. dst->content = duplicate_content;
  12021. /* copy the data into the dst request */
  12022. if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
  12023. return;
  12024. }
  12025. ast_str_copy_string(&dst->data, src->data);
  12026. /* copy the content into the dst request (if it exists) */
  12027. if (src->content) {
  12028. if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
  12029. return;
  12030. }
  12031. ast_str_copy_string(&dst->content, src->content);
  12032. }
  12033. }
  12034. static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
  12035. {
  12036. char uri[SIPBUFSIZE];
  12037. struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
  12038. struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
  12039. struct sip_cc_agent_pvt *agent_pvt;
  12040. if (!agent) {
  12041. /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
  12042. * agent? Oh well, we'll just warn and return without adding the header.
  12043. */
  12044. ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
  12045. return;
  12046. }
  12047. agent_pvt = agent->private_data;
  12048. if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
  12049. ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
  12050. } else {
  12051. generate_uri(p, uri, sizeof(uri));
  12052. ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
  12053. }
  12054. /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
  12055. * to be more accurate. This parameter has no bearing on the actual operation
  12056. * of the feature; it's just there for informational purposes.
  12057. */
  12058. ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
  12059. add_header(resp, "Call-Info", ast_str_buffer(header));
  12060. ao2_ref(agent, -1);
  12061. }
  12062. /*! \brief Used for 200 OK and 183 early media
  12063. \return Will return XMIT_ERROR for network errors.
  12064. */
  12065. static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid)
  12066. {
  12067. struct sip_request resp;
  12068. uint32_t seqno;
  12069. if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
  12070. ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
  12071. return -1;
  12072. }
  12073. respprep(&resp, p, msg, req);
  12074. if (rpid == TRUE) {
  12075. add_rpid(&resp, p);
  12076. }
  12077. if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
  12078. add_cc_call_info_to_response(p, &resp);
  12079. }
  12080. if (p->rtp) {
  12081. if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  12082. ast_debug(1, "Setting framing from config on incoming call\n");
  12083. ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(p->rtp), ast_format_cap_get_framing(p->caps));
  12084. }
  12085. ast_rtp_instance_activate(p->rtp);
  12086. try_suggested_sip_codec(p);
  12087. if (p->t38.state == T38_ENABLED) {
  12088. add_sdp(&resp, p, oldsdp, TRUE, TRUE);
  12089. } else {
  12090. add_sdp(&resp, p, oldsdp, TRUE, FALSE);
  12091. }
  12092. } else
  12093. ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
  12094. if (reliable && !p->pendinginvite)
  12095. p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
  12096. add_required_respheader(&resp);
  12097. return send_response(p, &resp, reliable, seqno);
  12098. }
  12099. /*! \brief Parse first line of incoming SIP request */
  12100. static int determine_firstline_parts(struct sip_request *req)
  12101. {
  12102. char *e = ast_skip_blanks(ast_str_buffer(req->data)); /* there shouldn't be any */
  12103. char *local_rlpart1;
  12104. if (!*e)
  12105. return -1;
  12106. req->rlpart1 = e - ast_str_buffer(req->data); /* method or protocol */
  12107. local_rlpart1 = e;
  12108. e = ast_skip_nonblanks(e);
  12109. if (*e)
  12110. *e++ = '\0';
  12111. /* Get URI or status code */
  12112. e = ast_skip_blanks(e);
  12113. if ( !*e )
  12114. return -1;
  12115. ast_trim_blanks(e);
  12116. if (!strcasecmp(local_rlpart1, "SIP/2.0") ) { /* We have a response */
  12117. if (strlen(e) < 3) /* status code is 3 digits */
  12118. return -1;
  12119. req->rlpart2 = e - ast_str_buffer(req->data);
  12120. } else { /* We have a request */
  12121. if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
  12122. ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
  12123. e++;
  12124. if (!*e)
  12125. return -1;
  12126. }
  12127. req->rlpart2 = e - ast_str_buffer(req->data); /* URI */
  12128. e = ast_skip_nonblanks(e);
  12129. if (*e)
  12130. *e++ = '\0';
  12131. e = ast_skip_blanks(e);
  12132. if (strcasecmp(e, "SIP/2.0") ) {
  12133. ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
  12134. return -1;
  12135. }
  12136. }
  12137. return 1;
  12138. }
  12139. /*! \brief Transmit reinvite with SDP
  12140. \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
  12141. INVITE that opened the SIP dialogue
  12142. We reinvite so that the audio stream (RTP) go directly between
  12143. the SIP UAs. SIP Signalling stays with * in the path.
  12144. If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
  12145. T38 UDPTL transmission on the channel
  12146. If oldsdp is TRUE then the SDP version number is not incremented. This
  12147. is needed for Session-Timers so we can send a re-invite to refresh the
  12148. SIP session without modifying the media session.
  12149. */
  12150. static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
  12151. {
  12152. struct sip_request req;
  12153. reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
  12154. add_header(&req, "Allow", ALLOWED_METHODS);
  12155. add_supported(p, &req);
  12156. if (sipdebug) {
  12157. if (oldsdp == TRUE)
  12158. add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
  12159. else
  12160. add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
  12161. }
  12162. if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
  12163. add_rpid(&req, p);
  12164. if (p->do_history) {
  12165. append_history(p, "ReInv", "Re-invite sent");
  12166. }
  12167. offered_media_list_destroy(p);
  12168. try_suggested_sip_codec(p);
  12169. if (t38version) {
  12170. add_sdp(&req, p, oldsdp, FALSE, TRUE);
  12171. } else {
  12172. add_sdp(&req, p, oldsdp, TRUE, FALSE);
  12173. }
  12174. /* Use this as the basis */
  12175. initialize_initreq(p, &req);
  12176. p->lastinvite = p->ocseq;
  12177. ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
  12178. p->ongoing_reinvite = 1;
  12179. return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  12180. }
  12181. /* \brief Remove URI parameters at end of URI, not in username part though */
  12182. static char *remove_uri_parameters(char *uri)
  12183. {
  12184. char *atsign;
  12185. atsign = strchr(uri, '@'); /* First, locate the at sign */
  12186. if (!atsign) {
  12187. atsign = uri; /* Ok hostname only, let's stick with the rest */
  12188. }
  12189. atsign = strchr(atsign, ';'); /* Locate semi colon */
  12190. if (atsign)
  12191. *atsign = '\0'; /* Kill at the semi colon */
  12192. return uri;
  12193. }
  12194. /*! \brief Check Contact: URI of SIP message */
  12195. static void extract_uri(struct sip_pvt *p, struct sip_request *req)
  12196. {
  12197. char stripped[SIPBUFSIZE];
  12198. char *c;
  12199. ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
  12200. c = get_in_brackets(stripped);
  12201. /* Cut the URI at the at sign after the @, not in the username part */
  12202. c = remove_uri_parameters(c);
  12203. if (!ast_strlen_zero(c)) {
  12204. ast_string_field_set(p, uri, c);
  12205. }
  12206. }
  12207. /*!
  12208. * \brief Determine if, as a UAS, we need to use a SIPS Contact.
  12209. *
  12210. * This uses the rules defined in RFC 3261 section 12.1.1 to
  12211. * determine if a SIPS URI should be used as the Contact header
  12212. * when responding to incoming SIP requests.
  12213. *
  12214. * \param req The incoming SIP request
  12215. * \retval 0 SIPS is not required
  12216. * \retval 1 SIPS is required
  12217. */
  12218. static int uas_sips_contact(struct sip_request *req)
  12219. {
  12220. const char *record_route = sip_get_header(req, "Record-Route");
  12221. if (!strncmp(REQ_OFFSET_TO_STR(req, rlpart2), "sips:", 5)) {
  12222. return 1;
  12223. }
  12224. if (record_route) {
  12225. char *record_route_uri = get_in_brackets(ast_strdupa(record_route));
  12226. if (!strncmp(record_route_uri, "sips:", 5)) {
  12227. return 1;
  12228. }
  12229. } else {
  12230. const char *contact = sip_get_header(req, "Contact");
  12231. char *contact_uri = get_in_brackets(ast_strdupa(contact));
  12232. if (!strncmp(contact_uri, "sips:", 5)) {
  12233. return 1;
  12234. }
  12235. }
  12236. return 0;
  12237. }
  12238. /*!
  12239. * \brief Determine if, as a UAC, we need to use a SIPS Contact.
  12240. *
  12241. * This uses the rules defined in RFC 3621 section 8.1.1.8 to
  12242. * determine if a SIPS URI should be used as the Contact header
  12243. * on our outgoing request.
  12244. *
  12245. * \param req The outgoing SIP request
  12246. * \retval 0 SIPS is not required
  12247. * \retval 1 SIPS is required
  12248. */
  12249. static int uac_sips_contact(struct sip_request *req)
  12250. {
  12251. const char *route = sip_get_header(req, "Route");
  12252. if (!strncmp(REQ_OFFSET_TO_STR(req, rlpart2), "sips:", 5)) {
  12253. return 1;
  12254. }
  12255. if (route) {
  12256. char *route_uri = get_in_brackets(ast_strdupa(route));
  12257. if (!strncmp(route_uri, "sips:", 5)) {
  12258. return 1;
  12259. }
  12260. }
  12261. return 0;
  12262. }
  12263. /*!
  12264. * \brief Build contact header
  12265. *
  12266. * This is the Contact header that we send out in SIP requests and responses
  12267. * involving this sip_pvt.
  12268. *
  12269. * The incoming parameter is used to tell if we are building the request parameter
  12270. * is an incoming SIP request that we are building the Contact header in response to,
  12271. * or if the req parameter is an outbound SIP request that we will later be adding
  12272. * the Contact header to.
  12273. *
  12274. * \param p The sip_pvt where the built Contact will be saved.
  12275. * \param req The request that triggered the creation of a Contact header.
  12276. * \param incoming Indicates if the Contact header is being created for a response to an incoming request
  12277. */
  12278. static void build_contact(struct sip_pvt *p, struct sip_request *req, int incoming)
  12279. {
  12280. char tmp[SIPBUFSIZE];
  12281. char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), ast_uri_sip_user);
  12282. int use_sips;
  12283. if (incoming) {
  12284. use_sips = uas_sips_contact(req);
  12285. } else {
  12286. use_sips = uac_sips_contact(req);
  12287. }
  12288. if (p->socket.type == AST_TRANSPORT_UDP) {
  12289. ast_string_field_build(p, our_contact, "<%s:%s%s%s>", use_sips ? "sips" : "sip",
  12290. user, ast_strlen_zero(user) ? "" : "@",
  12291. ast_sockaddr_stringify_remote(&p->ourip));
  12292. } else {
  12293. ast_string_field_build(p, our_contact, "<%s:%s%s%s;transport=%s>",
  12294. use_sips ? "sips" : "sip", user, ast_strlen_zero(user) ? "" : "@",
  12295. ast_sockaddr_stringify_remote(&p->ourip), sip_get_transport(p->socket.type));
  12296. }
  12297. }
  12298. /*! \brief Initiate new SIP request to peer/user */
  12299. static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
  12300. {
  12301. struct ast_str *invite = ast_str_alloca(256);
  12302. char from[256];
  12303. char to[256];
  12304. char tmp_n[SIPBUFSIZE/2]; /* build a local copy of 'n' if needed */
  12305. char tmp_l[SIPBUFSIZE/2]; /* build a local copy of 'l' if needed */
  12306. const char *l = NULL; /* XXX what is this, exactly ? */
  12307. const char *n = NULL; /* XXX what is this, exactly ? */
  12308. const char *d = NULL; /* domain in from header */
  12309. const char *urioptions = "";
  12310. int ourport;
  12311. int cid_has_name = 1;
  12312. int cid_has_num = 1;
  12313. struct ast_party_id connected_id;
  12314. if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
  12315. const char *s = p->username; /* being a string field, cannot be NULL */
  12316. /* Test p->username against allowed characters in AST_DIGIT_ANY
  12317. If it matches the allowed characters list, then sipuser = ";user=phone"
  12318. If not, then sipuser = ""
  12319. */
  12320. /* + is allowed in first position in a tel: uri */
  12321. if (*s == '+')
  12322. s++;
  12323. for (; *s; s++) {
  12324. if (!strchr(AST_DIGIT_ANYNUM, *s) )
  12325. break;
  12326. }
  12327. /* If we have only digits, add ;user=phone to the uri */
  12328. if (!*s)
  12329. urioptions = ";user=phone";
  12330. }
  12331. snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
  12332. if (ast_strlen_zero(p->fromdomain)) {
  12333. d = ast_sockaddr_stringify_host_remote(&p->ourip);
  12334. }
  12335. if (p->owner) {
  12336. connected_id = ast_channel_connected_effective_id(p->owner);
  12337. if ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
  12338. if (connected_id.number.valid) {
  12339. l = connected_id.number.str;
  12340. }
  12341. if (connected_id.name.valid) {
  12342. n = connected_id.name.str;
  12343. }
  12344. } else {
  12345. /* Even if we are using RPID, we shouldn't leak information in the From if the user wants
  12346. * their callerid restricted */
  12347. l = "anonymous";
  12348. n = CALLERID_UNKNOWN;
  12349. d = FROMDOMAIN_INVALID;
  12350. }
  12351. }
  12352. /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
  12353. * XXX Right now, this logic works because the only place that mwi_from
  12354. * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
  12355. * we might end up putting the mwi_from setting into other types of NOTIFY
  12356. * messages as well.
  12357. */
  12358. if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
  12359. l = p->mwi_from;
  12360. }
  12361. if (ast_strlen_zero(l)) {
  12362. cid_has_num = 0;
  12363. l = default_callerid;
  12364. }
  12365. if (ast_strlen_zero(n)) {
  12366. cid_has_name = 0;
  12367. n = l;
  12368. }
  12369. /* Allow user to be overridden */
  12370. if (!ast_strlen_zero(p->fromuser))
  12371. l = p->fromuser;
  12372. else /* Save for any further attempts */
  12373. ast_string_field_set(p, fromuser, l);
  12374. /* Allow user to be overridden */
  12375. if (!ast_strlen_zero(p->fromname))
  12376. n = p->fromname;
  12377. else /* Save for any further attempts */
  12378. ast_string_field_set(p, fromname, n);
  12379. /* Allow domain to be overridden */
  12380. if (!ast_strlen_zero(p->fromdomain))
  12381. d = p->fromdomain;
  12382. else /* Save for any further attempts */
  12383. ast_string_field_set(p, fromdomain, d);
  12384. ast_copy_string(tmp_l, l, sizeof(tmp_l));
  12385. if (sip_cfg.pedanticsipchecking) {
  12386. ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
  12387. n = tmp_n;
  12388. ast_uri_encode(l, tmp_l, sizeof(tmp_l), ast_uri_sip_user);
  12389. }
  12390. ourport = (p->fromdomainport && (p->fromdomainport != STANDARD_SIP_PORT)) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
  12391. /* If a caller id name was specified, add a display name. */
  12392. if (cid_has_name || !cid_has_num) {
  12393. snprintf(from, sizeof(from), "\"%s\" ", n);
  12394. } else {
  12395. from[0] = '\0';
  12396. }
  12397. if (!sip_standard_port(p->socket.type, ourport)) {
  12398. size_t offset = strlen(from);
  12399. snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s:%d>;tag=%s", tmp_l, d, ourport, p->tag);
  12400. } else {
  12401. size_t offset = strlen(from);
  12402. snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s>;tag=%s", tmp_l, d, p->tag);
  12403. }
  12404. if (!ast_strlen_zero(explicit_uri)) {
  12405. ast_str_set(&invite, 0, "%s", explicit_uri);
  12406. } else {
  12407. /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
  12408. if (!ast_strlen_zero(p->fullcontact)) {
  12409. /* If we have full contact, trust it */
  12410. ast_str_append(&invite, 0, "%s", p->fullcontact);
  12411. } else {
  12412. /* Otherwise, use the username while waiting for registration */
  12413. ast_str_append(&invite, 0, "sip:");
  12414. if (!ast_strlen_zero(p->username)) {
  12415. n = p->username;
  12416. if (sip_cfg.pedanticsipchecking) {
  12417. ast_uri_encode(n, tmp_n, sizeof(tmp_n), ast_uri_sip_user);
  12418. n = tmp_n;
  12419. }
  12420. ast_str_append(&invite, 0, "%s@", n);
  12421. }
  12422. ast_str_append(&invite, 0, "%s", p->tohost);
  12423. if (p->portinuri) {
  12424. ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
  12425. }
  12426. ast_str_append(&invite, 0, "%s", urioptions);
  12427. }
  12428. }
  12429. /* If custom URI options have been provided, append them */
  12430. if (p->options && !ast_strlen_zero(p->options->uri_options))
  12431. ast_str_append(&invite, 0, ";%s", p->options->uri_options);
  12432. /* This is the request URI, which is the next hop of the call
  12433. which may or may not be the destination of the call
  12434. */
  12435. ast_string_field_set(p, uri, ast_str_buffer(invite));
  12436. if (!ast_strlen_zero(p->todnid)) {
  12437. /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
  12438. if (!strchr(p->todnid, '@')) {
  12439. /* We have no domain in the dnid */
  12440. snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
  12441. } else {
  12442. snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
  12443. }
  12444. } else {
  12445. if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
  12446. /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
  12447. snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
  12448. } else if (p->options && p->options->vxml_url) {
  12449. /* If there is a VXML URL append it to the SIP URL */
  12450. snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
  12451. } else {
  12452. snprintf(to, sizeof(to), "<%s>", p->uri);
  12453. }
  12454. }
  12455. init_req(req, sipmethod, p->uri);
  12456. /* now tmp_n is available so reuse it to build the CSeq */
  12457. snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
  12458. add_header(req, "Via", p->via);
  12459. add_max_forwards(p, req);
  12460. /* This will be a no-op most of the time. However, under certain circumstances,
  12461. * NOTIFY messages will use this function for preparing the request and should
  12462. * have Route headers present.
  12463. */
  12464. add_route(req, &p->route, 0);
  12465. add_header(req, "From", from);
  12466. add_header(req, "To", to);
  12467. ast_string_field_set(p, exten, l);
  12468. build_contact(p, req, 0);
  12469. add_header(req, "Contact", p->our_contact);
  12470. add_header(req, "Call-ID", p->callid);
  12471. add_header(req, "CSeq", tmp_n);
  12472. if (!ast_strlen_zero(global_useragent)) {
  12473. add_header(req, "User-Agent", global_useragent);
  12474. }
  12475. }
  12476. /*! \brief Add "Diversion" header to outgoing message
  12477. *
  12478. * We need to add a Diversion header if the owner channel of
  12479. * this dialog has redirecting information associated with it.
  12480. *
  12481. * \param req The request/response to which we will add the header
  12482. * \param pvt The sip_pvt which represents the call-leg
  12483. */
  12484. static void add_diversion(struct sip_request *req, struct sip_pvt *pvt)
  12485. {
  12486. struct ast_party_id diverting_from;
  12487. const char *reason;
  12488. int found_in_table;
  12489. char header_text[256];
  12490. char encoded_number[SIPBUFSIZE/2];
  12491. /* We skip this entirely if the configuration doesn't allow diversion headers */
  12492. if (!sip_cfg.send_diversion) {
  12493. return;
  12494. }
  12495. if (!pvt->owner) {
  12496. return;
  12497. }
  12498. diverting_from = ast_channel_redirecting_effective_from(pvt->owner);
  12499. if (!diverting_from.number.valid
  12500. || ast_strlen_zero(diverting_from.number.str)) {
  12501. return;
  12502. }
  12503. if (sip_cfg.pedanticsipchecking) {
  12504. ast_uri_encode(diverting_from.number.str, encoded_number, sizeof(encoded_number), ast_uri_sip_user);
  12505. } else {
  12506. ast_copy_string(encoded_number, diverting_from.number.str, sizeof(encoded_number));
  12507. }
  12508. reason = sip_reason_code_to_str(&ast_channel_redirecting(pvt->owner)->reason, &found_in_table);
  12509. /* We at least have a number to place in the Diversion header, which is enough */
  12510. if (!diverting_from.name.valid
  12511. || ast_strlen_zero(diverting_from.name.str)) {
  12512. snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s%s%s",
  12513. encoded_number,
  12514. ast_sockaddr_stringify_host_remote(&pvt->ourip),
  12515. found_in_table ? "" : "\"",
  12516. reason,
  12517. found_in_table ? "" : "\"");
  12518. } else {
  12519. char escaped_name[SIPBUFSIZE/2];
  12520. if (sip_cfg.pedanticsipchecking) {
  12521. ast_escape_quoted(diverting_from.name.str, escaped_name, sizeof(escaped_name));
  12522. } else {
  12523. ast_copy_string(escaped_name, diverting_from.name.str, sizeof(escaped_name));
  12524. }
  12525. snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s%s%s",
  12526. escaped_name,
  12527. encoded_number,
  12528. ast_sockaddr_stringify_host_remote(&pvt->ourip),
  12529. found_in_table ? "" : "\"",
  12530. reason,
  12531. found_in_table ? "" : "\"");
  12532. }
  12533. add_header(req, "Diversion", header_text);
  12534. }
  12535. static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
  12536. {
  12537. struct sip_pvt *pvt;
  12538. int expires;
  12539. epa_entry->publish_type = publish_type;
  12540. if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL, 0))) {
  12541. return -1;
  12542. }
  12543. sip_pvt_lock(pvt);
  12544. if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
  12545. sip_pvt_unlock(pvt);
  12546. dialog_unlink_all(pvt);
  12547. dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
  12548. return -1;
  12549. }
  12550. ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
  12551. ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
  12552. expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
  12553. pvt->expiry = expires;
  12554. /* Bump refcount for sip_pvt's reference */
  12555. ao2_ref(epa_entry, +1);
  12556. pvt->epa_entry = epa_entry;
  12557. transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
  12558. sip_pvt_unlock(pvt);
  12559. sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
  12560. dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
  12561. return 0;
  12562. }
  12563. /*!
  12564. * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
  12565. * \param p sip_pvt structure
  12566. * \param sipmethod
  12567. * \param sdp unknown
  12568. * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
  12569. * 2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
  12570. * \param explicit_uri
  12571. */
  12572. static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
  12573. {
  12574. struct sip_request req;
  12575. struct ast_variable *var;
  12576. if (init) {/* Bump branch even on initial requests */
  12577. p->branch ^= ast_random();
  12578. p->invite_branch = p->branch;
  12579. build_via(p);
  12580. }
  12581. if (init > 1) {
  12582. initreqprep(&req, p, sipmethod, explicit_uri);
  12583. } else {
  12584. /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
  12585. reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
  12586. }
  12587. if (p->options && p->options->auth) {
  12588. add_header(&req, p->options->authheader, p->options->auth);
  12589. }
  12590. add_date(&req);
  12591. if (sipmethod == SIP_REFER && p->refer) { /* Call transfer */
  12592. if (!ast_strlen_zero(p->refer->refer_to)) {
  12593. add_header(&req, "Refer-To", p->refer->refer_to);
  12594. }
  12595. if (!ast_strlen_zero(p->refer->referred_by)) {
  12596. add_header(&req, "Referred-By", p->refer->referred_by);
  12597. }
  12598. } else if (sipmethod == SIP_SUBSCRIBE) {
  12599. if (p->subscribed == MWI_NOTIFICATION) {
  12600. add_header(&req, "Event", "message-summary");
  12601. add_header(&req, "Accept", "application/simple-message-summary");
  12602. } else if (p->subscribed == CALL_COMPLETION) {
  12603. add_header(&req, "Event", "call-completion");
  12604. add_header(&req, "Accept", "application/call-completion");
  12605. }
  12606. add_expires(&req, p->expiry);
  12607. }
  12608. /* This new INVITE is part of an attended transfer. Make sure that the
  12609. other end knows and replace the current call with this new call */
  12610. if (p->options && !ast_strlen_zero(p->options->replaces)) {
  12611. add_header(&req, "Replaces", p->options->replaces);
  12612. add_header(&req, "Require", "replaces");
  12613. }
  12614. /* Add Session-Timers related headers */
  12615. if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE
  12616. || (st_get_mode(p, 0) == SESSION_TIMER_MODE_ACCEPT
  12617. && st_get_se(p, FALSE) != DEFAULT_MIN_SE)) {
  12618. char i2astr[10];
  12619. if (!p->stimer->st_interval) {
  12620. p->stimer->st_interval = st_get_se(p, TRUE);
  12621. }
  12622. p->stimer->st_active = TRUE;
  12623. if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
  12624. snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
  12625. add_header(&req, "Session-Expires", i2astr);
  12626. }
  12627. snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
  12628. add_header(&req, "Min-SE", i2astr);
  12629. }
  12630. add_header(&req, "Allow", ALLOWED_METHODS);
  12631. add_supported(p, &req);
  12632. if (p->owner && ((p->options && p->options->addsipheaders)
  12633. || (p->refer && global_refer_addheaders))) {
  12634. struct ast_channel *chan = p->owner; /* The owner channel */
  12635. struct varshead *headp;
  12636. ast_channel_lock(chan);
  12637. headp = ast_channel_varshead(chan);
  12638. if (!headp) {
  12639. ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
  12640. } else {
  12641. const struct ast_var_t *current;
  12642. AST_LIST_TRAVERSE(headp, current, entries) {
  12643. /* SIPADDHEADER: Add SIP header to outgoing call */
  12644. if (!strncmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
  12645. char *content, *end;
  12646. const char *header = ast_var_value(current);
  12647. char *headdup = ast_strdupa(header);
  12648. /* Strip of the starting " (if it's there) */
  12649. if (*headdup == '"') {
  12650. headdup++;
  12651. }
  12652. if ((content = strchr(headdup, ':'))) {
  12653. *content++ = '\0';
  12654. content = ast_skip_blanks(content); /* Skip white space */
  12655. /* Strip the ending " (if it's there) */
  12656. end = content + strlen(content) -1;
  12657. if (*end == '"') {
  12658. *end = '\0';
  12659. }
  12660. add_header(&req, headdup, content);
  12661. if (sipdebug) {
  12662. ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
  12663. }
  12664. }
  12665. }
  12666. }
  12667. }
  12668. ast_channel_unlock(chan);
  12669. }
  12670. if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
  12671. add_rpid(&req, p);
  12672. if (sipmethod == SIP_INVITE) {
  12673. add_diversion(&req, p);
  12674. }
  12675. if (sdp) {
  12676. offered_media_list_destroy(p);
  12677. if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
  12678. ast_debug(1, "T38 is in state %u on channel %s\n", p->t38.state, p->owner ? ast_channel_name(p->owner) : "<none>");
  12679. add_sdp(&req, p, FALSE, FALSE, TRUE);
  12680. } else if (p->rtp) {
  12681. try_suggested_sip_codec(p);
  12682. add_sdp(&req, p, FALSE, TRUE, FALSE);
  12683. }
  12684. } else if (sipmethod == SIP_NOTIFY && p->notify) {
  12685. for (var = p->notify->headers; var; var = var->next) {
  12686. add_header(&req, var->name, var->value);
  12687. }
  12688. if (ast_str_strlen(p->notify->content)) {
  12689. add_content(&req, ast_str_buffer(p->notify->content));
  12690. }
  12691. } else if (sipmethod == SIP_PUBLISH) {
  12692. switch (p->epa_entry->static_data->event) {
  12693. case CALL_COMPLETION:
  12694. add_header(&req, "Event", "call-completion");
  12695. add_expires(&req, p->expiry);
  12696. if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
  12697. add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
  12698. }
  12699. if (!ast_strlen_zero(p->epa_entry->body)) {
  12700. add_header(&req, "Content-Type", "application/pidf+xml");
  12701. add_content(&req, p->epa_entry->body);
  12702. }
  12703. default:
  12704. break;
  12705. }
  12706. }
  12707. if (!p->initreq.headers || init > 2) {
  12708. initialize_initreq(p, &req);
  12709. }
  12710. if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
  12711. p->lastinvite = p->ocseq;
  12712. }
  12713. return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
  12714. }
  12715. /*! \brief Send a subscription or resubscription for MWI */
  12716. static int sip_subscribe_mwi_do(const void *data)
  12717. {
  12718. struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
  12719. if (!mwi) {
  12720. return -1;
  12721. }
  12722. mwi->resub = -1;
  12723. __sip_subscribe_mwi_do(mwi);
  12724. ao2_t_ref(mwi, -1, "unref mwi to balance ast_sched_add");
  12725. return 0;
  12726. }
  12727. static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
  12728. {
  12729. struct sip_registry *reg = data;
  12730. const char *old_str;
  12731. /* This shouldn't happen, but just in case */
  12732. if (ast_sockaddr_isnull(new)) {
  12733. ast_debug(1, "Empty sockaddr change...ignoring!\n");
  12734. return;
  12735. }
  12736. if (!ast_sockaddr_port(new)) {
  12737. ast_sockaddr_set_port(new, reg->portno);
  12738. }
  12739. old_str = ast_strdupa(ast_sockaddr_stringify(old));
  12740. ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
  12741. ast_sockaddr_copy(&reg->us, new);
  12742. }
  12743. static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
  12744. {
  12745. struct sip_peer *peer = data;
  12746. const char *old_str;
  12747. /* This shouldn't happen, but just in case */
  12748. if (ast_sockaddr_isnull(new)) {
  12749. ast_debug(1, "Empty sockaddr change...ignoring!\n");
  12750. return;
  12751. }
  12752. if (!ast_sockaddr_isnull(&peer->addr)) {
  12753. ao2_unlink(peers_by_ip, peer);
  12754. }
  12755. if (!ast_sockaddr_port(new)) {
  12756. ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
  12757. }
  12758. old_str = ast_strdupa(ast_sockaddr_stringify(old));
  12759. ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
  12760. ao2_lock(peer);
  12761. ast_sockaddr_copy(&peer->addr, new);
  12762. ao2_unlock(peer);
  12763. ao2_link(peers_by_ip, peer);
  12764. }
  12765. static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
  12766. {
  12767. struct sip_subscription_mwi *mwi = data;
  12768. const char *old_str;
  12769. /* This shouldn't happen, but just in case */
  12770. if (ast_sockaddr_isnull(new)) {
  12771. ast_debug(1, "Empty sockaddr change...ignoring!\n");
  12772. return;
  12773. }
  12774. old_str = ast_strdupa(ast_sockaddr_stringify(old));
  12775. ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
  12776. ast_sockaddr_copy(&mwi->us, new);
  12777. }
  12778. /*! \brief Actually setup an MWI subscription or resubscribe */
  12779. static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
  12780. {
  12781. /* If we have no DNS manager let's do a lookup */
  12782. if (!mwi->dnsmgr) {
  12783. char transport[MAXHOSTNAMELEN];
  12784. snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
  12785. mwi->us.ss.ss_family = get_address_family_filter(mwi->transport); /* Filter address family */
  12786. ao2_t_ref(mwi, +1, "dnsmgr reference to mwi");
  12787. ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, mwi);
  12788. if (!mwi->dnsmgr) {
  12789. ao2_t_ref(mwi, -1, "dnsmgr disabled, remove reference");
  12790. }
  12791. }
  12792. /* If we already have a subscription up simply send a resubscription */
  12793. if (mwi->call) {
  12794. transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
  12795. return 0;
  12796. }
  12797. /* Create a dialog that we will use for the subscription */
  12798. if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, 0))) {
  12799. return -1;
  12800. }
  12801. ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
  12802. if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
  12803. ast_sockaddr_set_port(&mwi->us, mwi->portno);
  12804. }
  12805. /* Setup the destination of our subscription */
  12806. if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
  12807. dialog_unlink_all(mwi->call);
  12808. mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
  12809. return 0;
  12810. }
  12811. mwi->call->expiry = mwi_expiry;
  12812. if (!mwi->dnsmgr && mwi->portno) {
  12813. ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
  12814. ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
  12815. } else {
  12816. mwi->portno = ast_sockaddr_port(&mwi->call->sa);
  12817. }
  12818. /* Set various other information */
  12819. if (!ast_strlen_zero(mwi->authuser)) {
  12820. ast_string_field_set(mwi->call, peername, mwi->authuser);
  12821. ast_string_field_set(mwi->call, authname, mwi->authuser);
  12822. ast_string_field_set(mwi->call, fromuser, mwi->authuser);
  12823. } else {
  12824. ast_string_field_set(mwi->call, peername, mwi->username);
  12825. ast_string_field_set(mwi->call, authname, mwi->username);
  12826. ast_string_field_set(mwi->call, fromuser, mwi->username);
  12827. }
  12828. ast_string_field_set(mwi->call, username, mwi->username);
  12829. if (!ast_strlen_zero(mwi->secret)) {
  12830. ast_string_field_set(mwi->call, peersecret, mwi->secret);
  12831. }
  12832. set_socket_transport(&mwi->call->socket, mwi->transport);
  12833. mwi->call->socket.port = htons(mwi->portno);
  12834. ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
  12835. build_via(mwi->call);
  12836. /* Change the dialog callid. */
  12837. change_callid_pvt(mwi->call, NULL);
  12838. ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
  12839. /* Associate the call with us */
  12840. mwi->call->mwi = ao2_t_bump(mwi, "Reference mwi from it's call");
  12841. mwi->call->subscribed = MWI_NOTIFICATION;
  12842. /* Actually send the packet */
  12843. transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
  12844. return 0;
  12845. }
  12846. /*!
  12847. * \internal
  12848. * \brief Find the channel that is causing the RINGING update, ref'd
  12849. */
  12850. static struct ast_channel *find_ringing_channel(struct ao2_container *device_state_info, struct sip_pvt *p)
  12851. {
  12852. struct ao2_iterator citer;
  12853. struct ast_device_state_info *device_state;
  12854. struct ast_channel *c = NULL;
  12855. struct timeval tv = {0,};
  12856. /* iterate ringing devices and get the oldest of all causing channels */
  12857. citer = ao2_iterator_init(device_state_info, 0);
  12858. for (; (device_state = ao2_iterator_next(&citer)); ao2_ref(device_state, -1)) {
  12859. if (!device_state->causing_channel || (device_state->device_state != AST_DEVICE_RINGING &&
  12860. device_state->device_state != AST_DEVICE_RINGINUSE)) {
  12861. continue;
  12862. }
  12863. ast_channel_lock(device_state->causing_channel);
  12864. if (ast_tvzero(tv) || ast_tvcmp(ast_channel_creationtime(device_state->causing_channel), tv) < 0) {
  12865. c = device_state->causing_channel;
  12866. tv = ast_channel_creationtime(c);
  12867. }
  12868. ast_channel_unlock(device_state->causing_channel);
  12869. }
  12870. ao2_iterator_destroy(&citer);
  12871. return c ? ast_channel_ref(c) : NULL;
  12872. }
  12873. /* XXX Candidate for moving into its own file */
  12874. static int allow_notify_user_presence(struct sip_pvt *p)
  12875. {
  12876. return (strstr(p->useragent, "Digium")) ? 1 : 0;
  12877. }
  12878. /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
  12879. static void state_notify_build_xml(struct state_notify_data *data, int full, const char *exten, const char *context, struct ast_str **tmp, struct sip_pvt *p, int subscribed, const char *mfrom, const char *mto)
  12880. {
  12881. enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
  12882. const char *statestring = "terminated";
  12883. const char *pidfstate = "--";
  12884. const char *pidfnote ="Ready";
  12885. char hint[AST_MAX_EXTENSION];
  12886. switch (data->state) {
  12887. case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
  12888. statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
  12889. local_state = NOTIFY_INUSE;
  12890. pidfstate = "busy";
  12891. pidfnote = "Ringing";
  12892. break;
  12893. case AST_EXTENSION_RINGING:
  12894. statestring = "early";
  12895. local_state = NOTIFY_INUSE;
  12896. pidfstate = "busy";
  12897. pidfnote = "Ringing";
  12898. break;
  12899. case AST_EXTENSION_INUSE:
  12900. statestring = "confirmed";
  12901. local_state = NOTIFY_INUSE;
  12902. pidfstate = "busy";
  12903. pidfnote = "On the phone";
  12904. break;
  12905. case AST_EXTENSION_BUSY:
  12906. statestring = "confirmed";
  12907. local_state = NOTIFY_CLOSED;
  12908. pidfstate = "busy";
  12909. pidfnote = "On the phone";
  12910. break;
  12911. case AST_EXTENSION_UNAVAILABLE:
  12912. statestring = "terminated";
  12913. local_state = NOTIFY_CLOSED;
  12914. pidfstate = "away";
  12915. pidfnote = "Unavailable";
  12916. break;
  12917. case AST_EXTENSION_ONHOLD:
  12918. statestring = "confirmed";
  12919. local_state = NOTIFY_CLOSED;
  12920. pidfstate = "busy";
  12921. pidfnote = "On hold";
  12922. break;
  12923. case AST_EXTENSION_NOT_INUSE:
  12924. default:
  12925. /* Default setting */
  12926. break;
  12927. }
  12928. /* Check which device/devices we are watching and if they are registered */
  12929. if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
  12930. char *hint2;
  12931. char *individual_hint = NULL;
  12932. int hint_count = 0, unavailable_count = 0;
  12933. /* strip off any possible PRESENCE providers from hint */
  12934. if ((hint2 = strrchr(hint, ','))) {
  12935. *hint2 = '\0';
  12936. }
  12937. hint2 = hint;
  12938. while ((individual_hint = strsep(&hint2, "&"))) {
  12939. hint_count++;
  12940. if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
  12941. unavailable_count++;
  12942. }
  12943. /* If none of the hinted devices are registered, we will
  12944. * override notification and show no availability.
  12945. */
  12946. if (hint_count > 0 && hint_count == unavailable_count) {
  12947. local_state = NOTIFY_CLOSED;
  12948. pidfstate = "away";
  12949. pidfnote = "Not online";
  12950. }
  12951. }
  12952. switch (subscribed) {
  12953. case XPIDF_XML:
  12954. case CPIM_PIDF_XML:
  12955. ast_str_append(tmp, 0,
  12956. "<?xml version=\"1.0\"?>\n"
  12957. "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
  12958. "<presence>\n");
  12959. ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
  12960. ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
  12961. ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
  12962. ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
  12963. ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
  12964. ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
  12965. break;
  12966. case PIDF_XML: /* Eyebeam supports this format */
  12967. ast_str_append(tmp, 0,
  12968. "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
  12969. "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
  12970. ast_str_append(tmp, 0, "<pp:person><status>\n");
  12971. if (pidfstate[0] != '-') {
  12972. ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
  12973. }
  12974. ast_str_append(tmp, 0, "</status></pp:person>\n");
  12975. ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
  12976. ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
  12977. ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
  12978. if (pidfstate[0] == 'b') /* Busy? Still open ... */
  12979. ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
  12980. else
  12981. ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
  12982. if (allow_notify_user_presence(p) && (data->presence_state != AST_PRESENCE_INVALID)
  12983. && (data->presence_state != AST_PRESENCE_NOT_SET)) {
  12984. ast_str_append(tmp, 0, "</tuple>\n");
  12985. ast_str_append(tmp, 0, "<tuple id=\"digium-presence\">\n");
  12986. ast_str_append(tmp, 0, "<status>\n");
  12987. ast_str_append(tmp, 0, "<digium_presence type=\"%s\" subtype=\"%s\">%s</digium_presence>\n",
  12988. ast_presence_state2str(data->presence_state),
  12989. S_OR(data->presence_subtype, ""),
  12990. S_OR(data->presence_message, ""));
  12991. ast_str_append(tmp, 0, "</status>\n");
  12992. ast_test_suite_event_notify("DIGIUM_PRESENCE_SENT",
  12993. "PresenceState: %s\r\n"
  12994. "Subtype: %s\r\n"
  12995. "Message: %s",
  12996. ast_presence_state2str(data->presence_state),
  12997. S_OR(data->presence_subtype, ""),
  12998. S_OR(data->presence_message, ""));
  12999. }
  13000. ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
  13001. break;
  13002. case DIALOG_INFO_XML: /* SNOM subscribes in this format */
  13003. ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
  13004. ast_str_append(tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%u\" state=\"%s\" entity=\"%s\">\n", p->dialogver, full ? "full" : "partial", mto);
  13005. if (data->state > 0 && (data->state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
  13006. /* Twice the extension length should be enough for XML encoding */
  13007. char local_display[AST_MAX_EXTENSION * 2];
  13008. char remote_display[AST_MAX_EXTENSION * 2];
  13009. char *local_target = ast_strdupa(mto);
  13010. /* It may seem odd to base the remote_target on the To header here,
  13011. * but testing by reporters on issue ASTERISK-16735 found that basing
  13012. * on the From header would cause ringing state hints to not work
  13013. * properly on certain SNOM devices. If you are using notifycid properly
  13014. * (i.e. in the same extension and context as the dialed call) then this
  13015. * should not be an issue since the data will be overwritten shortly
  13016. * with channel caller ID
  13017. */
  13018. char *remote_target = ast_strdupa(mto);
  13019. ast_xml_escape(exten, local_display, sizeof(local_display));
  13020. ast_xml_escape(exten, remote_display, sizeof(remote_display));
  13021. /* There are some limitations to how this works. The primary one is that the
  13022. callee must be dialing the same extension that is being monitored. Simply dialing
  13023. the hint'd device is not sufficient. */
  13024. if (sip_cfg.notifycid) {
  13025. struct ast_channel *callee;
  13026. callee = find_ringing_channel(data->device_state_info, p);
  13027. if (callee) {
  13028. static char *anonymous = "anonymous";
  13029. static char *invalid = "anonymous.invalid";
  13030. char *cid_num;
  13031. char *connected_num;
  13032. int need;
  13033. int cid_num_restricted, connected_num_restricted;
  13034. ast_channel_lock(callee);
  13035. cid_num_restricted = (ast_channel_caller(callee)->id.number.presentation &
  13036. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
  13037. cid_num = S_COR(ast_channel_caller(callee)->id.number.valid,
  13038. S_COR(cid_num_restricted, anonymous,
  13039. ast_channel_caller(callee)->id.number.str), "");
  13040. need = strlen(cid_num) + (cid_num_restricted ? strlen(invalid) :
  13041. strlen(p->fromdomain)) + sizeof("sip:@");
  13042. local_target = ast_alloca(need);
  13043. snprintf(local_target, need, "sip:%s@%s", cid_num,
  13044. cid_num_restricted ? invalid : p->fromdomain);
  13045. ast_xml_escape(S_COR(ast_channel_caller(callee)->id.name.valid,
  13046. S_COR((ast_channel_caller(callee)->id.name.presentation &
  13047. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
  13048. ast_channel_caller(callee)->id.name.str), ""),
  13049. local_display, sizeof(local_display));
  13050. connected_num_restricted = (ast_channel_connected(callee)->id.number.presentation &
  13051. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
  13052. connected_num = S_COR(ast_channel_connected(callee)->id.number.valid,
  13053. S_COR(connected_num_restricted, anonymous,
  13054. ast_channel_connected(callee)->id.number.str), "");
  13055. need = strlen(connected_num) + (connected_num_restricted ? strlen(invalid) :
  13056. strlen(p->fromdomain)) + sizeof("sip:@");
  13057. remote_target = ast_alloca(need);
  13058. snprintf(remote_target, need, "sip:%s@%s", connected_num,
  13059. connected_num_restricted ? invalid : p->fromdomain);
  13060. ast_xml_escape(S_COR(ast_channel_connected(callee)->id.name.valid,
  13061. S_COR((ast_channel_connected(callee)->id.name.presentation &
  13062. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
  13063. ast_channel_connected(callee)->id.name.str), ""),
  13064. remote_display, sizeof(remote_display));
  13065. ast_channel_unlock(callee);
  13066. callee = ast_channel_unref(callee);
  13067. }
  13068. /* We create a fake call-id which the phone will send back in an INVITE
  13069. Replaces header which we can grab and do some magic with. */
  13070. if (sip_cfg.pedanticsipchecking) {
  13071. ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
  13072. exten, p->callid, p->theirtag, p->tag);
  13073. } else {
  13074. ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
  13075. exten, p->callid);
  13076. }
  13077. ast_str_append(tmp, 0,
  13078. "<remote>\n"
  13079. /* See the limitations of this above. Luckily the phone seems to still be
  13080. happy when these values are not correct. */
  13081. "<identity display=\"%s\">%s</identity>\n"
  13082. "<target uri=\"%s\"/>\n"
  13083. "</remote>\n"
  13084. "<local>\n"
  13085. "<identity display=\"%s\">%s</identity>\n"
  13086. "<target uri=\"%s\"/>\n"
  13087. "</local>\n",
  13088. remote_display, remote_target, remote_target, local_display, local_target, local_target);
  13089. } else {
  13090. ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
  13091. }
  13092. } else {
  13093. ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
  13094. }
  13095. ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
  13096. if (data->state == AST_EXTENSION_ONHOLD) {
  13097. ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
  13098. "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
  13099. "</target>\n</local>\n", mto);
  13100. }
  13101. ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
  13102. break;
  13103. case NONE:
  13104. default:
  13105. break;
  13106. }
  13107. }
  13108. static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
  13109. {
  13110. struct sip_request req;
  13111. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  13112. char uri[SIPBUFSIZE];
  13113. char state_str[64];
  13114. char subscription_state_hdr[64];
  13115. if (state < CC_QUEUED || state > CC_READY) {
  13116. ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%u)\n", state);
  13117. return -1;
  13118. }
  13119. reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
  13120. snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
  13121. add_header(&req, "Event", "call-completion");
  13122. add_header(&req, "Content-Type", "application/call-completion");
  13123. snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
  13124. add_header(&req, "Subscription-State", subscription_state_hdr);
  13125. if (state == CC_READY) {
  13126. generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
  13127. snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
  13128. }
  13129. add_content(&req, state_str);
  13130. if (state == CC_READY) {
  13131. add_content(&req, uri);
  13132. }
  13133. return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
  13134. }
  13135. /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
  13136. static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout)
  13137. {
  13138. struct ast_str *tmp = ast_str_alloca(4000);
  13139. char from[256], to[256];
  13140. char *c, *mfrom, *mto;
  13141. struct sip_request req;
  13142. const struct cfsubscription_types *subscriptiontype;
  13143. /* If the subscription has not yet been accepted do not send a NOTIFY */
  13144. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  13145. return 0;
  13146. }
  13147. memset(from, 0, sizeof(from));
  13148. memset(to, 0, sizeof(to));
  13149. subscriptiontype = find_subscription_type(p->subscribed);
  13150. ast_copy_string(from, sip_get_header(&p->initreq, "From"), sizeof(from));
  13151. c = get_in_brackets(from);
  13152. if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
  13153. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  13154. return -1;
  13155. }
  13156. mfrom = remove_uri_parameters(c);
  13157. ast_copy_string(to, sip_get_header(&p->initreq, "To"), sizeof(to));
  13158. c = get_in_brackets(to);
  13159. if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
  13160. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  13161. return -1;
  13162. }
  13163. mto = remove_uri_parameters(c);
  13164. reqprep(&req, p, SIP_NOTIFY, 0, 1);
  13165. switch(data->state) {
  13166. case AST_EXTENSION_DEACTIVATED:
  13167. if (timeout)
  13168. add_header(&req, "Subscription-State", "terminated;reason=timeout");
  13169. else {
  13170. add_header(&req, "Subscription-State", "terminated;reason=probation");
  13171. add_header(&req, "Retry-After", "60");
  13172. }
  13173. break;
  13174. case AST_EXTENSION_REMOVED:
  13175. add_header(&req, "Subscription-State", "terminated;reason=noresource");
  13176. break;
  13177. default:
  13178. if (p->expiry)
  13179. add_header(&req, "Subscription-State", "active");
  13180. else /* Expired */
  13181. add_header(&req, "Subscription-State", "terminated;reason=timeout");
  13182. }
  13183. switch (p->subscribed) {
  13184. case XPIDF_XML:
  13185. case CPIM_PIDF_XML:
  13186. add_header(&req, "Event", subscriptiontype->event);
  13187. state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
  13188. add_header(&req, "Content-Type", subscriptiontype->mediatype);
  13189. p->dialogver++;
  13190. break;
  13191. case PIDF_XML: /* Eyebeam supports this format */
  13192. add_header(&req, "Event", subscriptiontype->event);
  13193. state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
  13194. add_header(&req, "Content-Type", subscriptiontype->mediatype);
  13195. p->dialogver++;
  13196. break;
  13197. case DIALOG_INFO_XML: /* SNOM subscribes in this format */
  13198. add_header(&req, "Event", subscriptiontype->event);
  13199. state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
  13200. add_header(&req, "Content-Type", subscriptiontype->mediatype);
  13201. p->dialogver++;
  13202. break;
  13203. case NONE:
  13204. default:
  13205. break;
  13206. }
  13207. add_content(&req, ast_str_buffer(tmp));
  13208. p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
  13209. /* Send as XMIT_CRITICAL as we may never receive a 200 OK Response which clears p->pendinginvite.
  13210. *
  13211. * extensionstate_update() uses p->pendinginvite for queuing control.
  13212. * Updates stall if pendinginvite <> 0.
  13213. *
  13214. * The most appropriate solution is to remove the subscription when the NOTIFY transaction fails.
  13215. * The client will re-subscribe after restarting or maxexpiry timeout.
  13216. */
  13217. /* RFC6665 4.2.2. Sending State Information to Subscribers
  13218. * If the NOTIFY request fails due to expiration of SIP Timer F (transaction timeout),
  13219. * the notifier SHOULD remove the subscription.
  13220. */
  13221. return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  13222. }
  13223. /*! \brief Notify user of messages waiting in voicemail (RFC3842)
  13224. \note - Notification only works for registered peers with mailbox= definitions
  13225. in sip.conf
  13226. - We use the SIP Event package message-summary
  13227. MIME type defaults to "application/simple-message-summary";
  13228. */
  13229. static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
  13230. {
  13231. struct sip_request req;
  13232. struct ast_str *out = ast_str_alloca(500);
  13233. int ourport = (p->fromdomainport && (p->fromdomainport != STANDARD_SIP_PORT)) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
  13234. const char *domain;
  13235. const char *exten = S_OR(vmexten, default_vmexten);
  13236. initreqprep(&req, p, SIP_NOTIFY, NULL);
  13237. add_header(&req, "Event", "message-summary");
  13238. add_header(&req, "Content-Type", default_notifymime);
  13239. ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
  13240. /* domain initialization occurs here because initreqprep changes ast_sockaddr_stringify string. */
  13241. domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
  13242. if (!sip_standard_port(p->socket.type, ourport)) {
  13243. if (p->socket.type == AST_TRANSPORT_UDP) {
  13244. ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
  13245. } else {
  13246. ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, sip_get_transport(p->socket.type));
  13247. }
  13248. } else {
  13249. if (p->socket.type == AST_TRANSPORT_UDP) {
  13250. ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
  13251. } else {
  13252. ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, sip_get_transport(p->socket.type));
  13253. }
  13254. }
  13255. /* Cisco has a bug in the SIP stack where it can't accept the
  13256. (0/0) notification. This can temporarily be disabled in
  13257. sip.conf with the "buggymwi" option */
  13258. ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
  13259. newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
  13260. if (p->subscribed) {
  13261. if (p->expiry) {
  13262. add_header(&req, "Subscription-State", "active");
  13263. } else { /* Expired */
  13264. add_header(&req, "Subscription-State", "terminated;reason=timeout");
  13265. }
  13266. }
  13267. add_content(&req, ast_str_buffer(out));
  13268. if (!p->initreq.headers) {
  13269. initialize_initreq(p, &req);
  13270. }
  13271. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13272. }
  13273. /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
  13274. static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
  13275. {
  13276. struct sip_request req;
  13277. char tmp[SIPBUFSIZE/2];
  13278. reqprep(&req, p, SIP_NOTIFY, 0, 1);
  13279. snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
  13280. add_header(&req, "Event", tmp);
  13281. add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
  13282. add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
  13283. add_header(&req, "Allow", ALLOWED_METHODS);
  13284. add_supported(p, &req);
  13285. snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
  13286. add_content(&req, tmp);
  13287. if (!p->initreq.headers) {
  13288. initialize_initreq(p, &req);
  13289. }
  13290. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13291. }
  13292. static int manager_sipnotify(struct mansession *s, const struct message *m)
  13293. {
  13294. const char *channame = astman_get_header(m, "Channel");
  13295. struct ast_variable *vars = astman_get_variables_order(m, ORDER_NATURAL);
  13296. struct sip_pvt *p;
  13297. struct ast_variable *header, *var;
  13298. if (ast_strlen_zero(channame)) {
  13299. astman_send_error(s, m, "SIPNotify requires a channel name");
  13300. return 0;
  13301. }
  13302. if (!strncasecmp(channame, "sip/", 4)) {
  13303. channame += 4;
  13304. }
  13305. if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, 0))) {
  13306. astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
  13307. return 0;
  13308. }
  13309. if (create_addr(p, channame, NULL, 0)) {
  13310. /* Maybe they're not registered, etc. */
  13311. dialog_unlink_all(p);
  13312. dialog_unref(p, "unref dialog inside for loop" );
  13313. /* sip_destroy(p); */
  13314. astman_send_error(s, m, "Could not create address");
  13315. return 0;
  13316. }
  13317. /* Notify is outgoing call */
  13318. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  13319. sip_notify_alloc(p);
  13320. p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
  13321. for (var = vars; var; var = var->next) {
  13322. if (!strcasecmp(var->name, "Content")) {
  13323. if (ast_str_strlen(p->notify->content))
  13324. ast_str_append(&p->notify->content, 0, "\r\n");
  13325. ast_str_append(&p->notify->content, 0, "%s", var->value);
  13326. } else if (!strcasecmp(var->name, "Content-Length")) {
  13327. ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
  13328. } else {
  13329. header->next = ast_variable_new(var->name, var->value, "");
  13330. header = header->next;
  13331. }
  13332. }
  13333. sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
  13334. transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
  13335. dialog_unref(p, "bump down the count of p since we're done with it.");
  13336. astman_send_ack(s, m, "Notify Sent");
  13337. ast_variables_destroy(vars);
  13338. return 0;
  13339. }
  13340. /*! \brief Send a provisional response indicating that a call was redirected
  13341. */
  13342. static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
  13343. {
  13344. struct sip_request resp;
  13345. if (ast_channel_state(p->owner) == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  13346. return;
  13347. }
  13348. respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
  13349. add_diversion(&resp, p);
  13350. send_response(p, &resp, XMIT_UNRELIABLE, 0);
  13351. }
  13352. /*! \brief Notify peer that the connected line has changed */
  13353. static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
  13354. {
  13355. struct ast_party_id connected_id = ast_channel_connected_effective_id(p->owner);
  13356. if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
  13357. return;
  13358. }
  13359. if (!connected_id.number.valid
  13360. || ast_strlen_zero(connected_id.number.str)) {
  13361. return;
  13362. }
  13363. append_history(p, "ConnectedLine", "%s party is now %s <%s>",
  13364. ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
  13365. S_COR(connected_id.name.valid, connected_id.name.str, ""),
  13366. S_COR(connected_id.number.valid, connected_id.number.str, ""));
  13367. if (ast_channel_state(p->owner) == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  13368. struct sip_request req;
  13369. if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
  13370. reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
  13371. add_header(&req, "Allow", ALLOWED_METHODS);
  13372. add_supported(p, &req);
  13373. add_rpid(&req, p);
  13374. add_sdp(&req, p, FALSE, TRUE, FALSE);
  13375. initialize_initreq(p, &req);
  13376. p->lastinvite = p->ocseq;
  13377. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  13378. p->invitestate = INV_CALLING;
  13379. send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  13380. } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) {
  13381. reqprep(&req, p, SIP_UPDATE, 0, 1);
  13382. add_rpid(&req, p);
  13383. add_header(&req, "X-Asterisk-rpid-update", "Yes");
  13384. send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  13385. } else {
  13386. /* We cannot send the update yet, so we have to wait until we can */
  13387. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  13388. }
  13389. } else {
  13390. ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  13391. if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
  13392. struct sip_request resp;
  13393. if ((ast_channel_state(p->owner) == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
  13394. ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  13395. respprep(&resp, p, "180 Ringing", &p->initreq);
  13396. add_rpid(&resp, p);
  13397. send_response(p, &resp, XMIT_UNRELIABLE, 0);
  13398. ast_set_flag(&p->flags[0], SIP_RINGING);
  13399. } else if (ast_channel_state(p->owner) == AST_STATE_RINGING) {
  13400. ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  13401. respprep(&resp, p, "183 Session Progress", &p->initreq);
  13402. add_rpid(&resp, p);
  13403. send_response(p, &resp, XMIT_UNRELIABLE, 0);
  13404. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  13405. } else {
  13406. ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", ast_channel_name(p->owner), ast_state2str(ast_channel_state(p->owner)));
  13407. }
  13408. }
  13409. }
  13410. }
  13411. static const struct _map_x_s regstatestrings[] = {
  13412. { REG_STATE_FAILED, "Failed" },
  13413. { REG_STATE_UNREGISTERED, "Unregistered"},
  13414. { REG_STATE_REGSENT, "Request Sent"},
  13415. { REG_STATE_AUTHSENT, "Auth. Sent"},
  13416. { REG_STATE_REGISTERED, "Registered"},
  13417. { REG_STATE_REJECTED, "Rejected"},
  13418. { REG_STATE_TIMEOUT, "Timeout"},
  13419. { REG_STATE_NOAUTH, "No Authentication"},
  13420. { -1, NULL } /* terminator */
  13421. };
  13422. /*! \brief Convert registration state status to string */
  13423. static const char *regstate2str(enum sipregistrystate regstate)
  13424. {
  13425. return map_x_s(regstatestrings, regstate, "Unknown");
  13426. }
  13427. static void sip_publish_registry(const char *username, const char *domain, const char *status)
  13428. {
  13429. ast_system_publish_registry("SIP", username, domain, status, NULL);
  13430. }
  13431. /*! \brief Update registration with SIP Proxy.
  13432. * Called from the scheduler when the previous registration expires,
  13433. * so we don't have to cancel the pending event.
  13434. * We assume the reference so the sip_registry is valid, since it
  13435. * is stored in the scheduled event anyways.
  13436. */
  13437. static int sip_reregister(const void *data)
  13438. {
  13439. /* if we are here, we know that we need to reregister. */
  13440. struct sip_registry *r = (struct sip_registry *) data;
  13441. /* if we couldn't get a reference to the registry object, punt */
  13442. if (!r) {
  13443. return 0;
  13444. }
  13445. if (r->call && r->call->do_history) {
  13446. append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
  13447. }
  13448. /* Since registry's are only added/removed by the the monitor thread, this
  13449. may be overkill to reference/dereference at all here */
  13450. if (sipdebug) {
  13451. ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
  13452. }
  13453. r->expire = -1;
  13454. r->expiry = r->configured_expiry;
  13455. __sip_do_register(r);
  13456. ao2_t_ref(r, -1, "unref the re-register scheduled event");
  13457. return 0;
  13458. }
  13459. /*! \brief Register with SIP proxy
  13460. \return see \ref __sip_xmit
  13461. */
  13462. static int __sip_do_register(struct sip_registry *r)
  13463. {
  13464. int res;
  13465. res = transmit_register(r, SIP_REGISTER, NULL, NULL);
  13466. return res;
  13467. }
  13468. /*! \brief Registration timeout, register again
  13469. * Registered as a timeout handler during transmit_register(),
  13470. * to retransmit the packet if a reply does not come back.
  13471. * This is called by the scheduler so the event is not pending anymore when
  13472. * we are called.
  13473. */
  13474. static int sip_reg_timeout(const void *data)
  13475. {
  13476. /* if we are here, our registration timed out, so we'll just do it over */
  13477. struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
  13478. struct sip_pvt *p;
  13479. /* if we couldn't get a reference to the registry object, punt */
  13480. if (!r) {
  13481. return 0;
  13482. }
  13483. if (r->dnsmgr) {
  13484. /* If the registration has timed out, maybe the IP changed. Force a refresh. */
  13485. ast_dnsmgr_refresh(r->dnsmgr);
  13486. }
  13487. /* If the initial tranmission failed, we may not have an existing dialog,
  13488. * so it is possible that r->call == NULL.
  13489. * Otherwise destroy it, as we have a timeout so we don't want it.
  13490. */
  13491. if (r->call) {
  13492. /* Unlink us, destroy old call. Locking is not relevant here because all this happens
  13493. in the single SIP manager thread. */
  13494. p = r->call;
  13495. sip_pvt_lock(p);
  13496. pvt_set_needdestroy(p, "registration timeout");
  13497. /* Pretend to ACK anything just in case */
  13498. __sip_pretend_ack(p);
  13499. sip_pvt_unlock(p);
  13500. /* decouple the two objects */
  13501. /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
  13502. ao2_t_replace(p->registry, NULL, "p->registry unreffed");
  13503. r->call = dialog_unref(r->call, "unrefing r->call");
  13504. }
  13505. /* If we have a limit, stop registration and give up */
  13506. r->timeout = -1;
  13507. if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
  13508. /* Ok, enough is enough. Don't try any more */
  13509. /* We could add an external notification here...
  13510. steal it from app_voicemail :-) */
  13511. ast_log(LOG_NOTICE, " -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
  13512. r->regstate = REG_STATE_FAILED;
  13513. } else {
  13514. r->regstate = REG_STATE_UNREGISTERED;
  13515. transmit_register(r, SIP_REGISTER, NULL, NULL);
  13516. ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
  13517. }
  13518. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  13519. ao2_t_ref(r, -1, "unreffing registry_unref r");
  13520. return 0;
  13521. }
  13522. static const char *sip_sanitized_host(const char *host)
  13523. {
  13524. struct ast_sockaddr addr = { { 0, 0, }, };
  13525. /* peer/sip_pvt->tohost and sip_registry->hostname should never have a port
  13526. * in them, so we use PARSE_PORT_FORBID here. If this lookup fails, we return
  13527. * the original host which is most likely a host name and not an IP. */
  13528. if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
  13529. return host;
  13530. }
  13531. return ast_sockaddr_stringify_host_remote(&addr);
  13532. }
  13533. /*! \brief Transmit register to SIP proxy or UA
  13534. * auth = NULL on the initial registration (from sip_reregister())
  13535. */
  13536. static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
  13537. {
  13538. struct sip_request req;
  13539. char from[256];
  13540. char to[256];
  13541. char tmp[80];
  13542. char addr[80];
  13543. struct sip_pvt *p;
  13544. struct sip_peer *peer = NULL;
  13545. int res;
  13546. int portno = 0;
  13547. /* exit if we are already in process with this registrar ?*/
  13548. if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
  13549. if (r) {
  13550. ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
  13551. }
  13552. return 0;
  13553. }
  13554. if (r->dnsmgr == NULL) {
  13555. char transport[MAXHOSTNAMELEN];
  13556. peer = sip_find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
  13557. snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static sip_get_transport function */
  13558. r->us.ss.ss_family = get_address_family_filter(r->transport); /* Filter address family */
  13559. /* No point in doing a DNS lookup of the register hostname if we're just going to
  13560. * end up using an outbound proxy. obproxy_get is safe to call with either of r->call
  13561. * or peer NULL. Since we're only concerned with its existence, we're not going to
  13562. * bother getting a ref to the proxy*/
  13563. if (!obproxy_get(r->call, peer)) {
  13564. ao2_t_ref(r, +1, "add reg ref for dnsmgr");
  13565. ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
  13566. if (!r->dnsmgr) {
  13567. /*dnsmgr refresh disabled, no reference added! */
  13568. ao2_t_ref(r, -1, "remove reg ref, dnsmgr disabled");
  13569. }
  13570. }
  13571. if (peer) {
  13572. peer = sip_unref_peer(peer, "removing peer ref for dnsmgr_lookup");
  13573. }
  13574. }
  13575. if (r->call) { /* We have a registration */
  13576. if (!auth) {
  13577. ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
  13578. return 0;
  13579. } else {
  13580. p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
  13581. ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
  13582. }
  13583. } else {
  13584. /* Build callid for registration if we haven't registered before */
  13585. if (!r->callid_valid) {
  13586. build_callid_registry(r, &internip, default_fromdomain);
  13587. build_localtag_registry(r);
  13588. r->callid_valid = TRUE;
  13589. }
  13590. /* Allocate SIP dialog for registration */
  13591. if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL, 0))) {
  13592. ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
  13593. return 0;
  13594. }
  13595. /* reset tag to consistent value from registry */
  13596. ast_string_field_set(p, tag, r->localtag);
  13597. if (p->do_history) {
  13598. append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
  13599. }
  13600. p->socket.type = r->transport;
  13601. /* Use port number specified if no SRV record was found */
  13602. if (!ast_sockaddr_isnull(&r->us)) {
  13603. if (!ast_sockaddr_port(&r->us) && r->portno) {
  13604. ast_sockaddr_set_port(&r->us, r->portno);
  13605. }
  13606. /* It is possible that DNS was unavailable at the time the peer was created.
  13607. * Here, if we've updated the address in the registry via manually calling
  13608. * ast_dnsmgr_lookup_cb() above, then we call the same function that dnsmgr would
  13609. * call if it was updating a peer's address */
  13610. if ((peer = sip_find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
  13611. if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
  13612. on_dns_update_peer(&peer->addr, &r->us, peer);
  13613. }
  13614. peer = sip_unref_peer(peer, "unref after sip_find_peer");
  13615. }
  13616. }
  13617. /* Find address to hostname */
  13618. if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
  13619. /* we have what we hope is a temporary network error,
  13620. * probably DNS. We need to reschedule a registration try */
  13621. dialog_unlink_all(p);
  13622. p = dialog_unref(p, "unref dialog after unlink_all");
  13623. if (r->timeout > -1) {
  13624. AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
  13625. ao2_t_ref(_data, -1, "del for REPLACE of registry ptr"),
  13626. ao2_t_ref(r, -1, "object ptr dec when SCHED_REPLACE add failed"),
  13627. ao2_t_ref(r, +1, "add for REPLACE registry ptr"));
  13628. ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
  13629. } else {
  13630. r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, ao2_t_bump(r, "add for REPLACE registry ptr"));
  13631. ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r->username, r->hostname, global_reg_timeout);
  13632. }
  13633. r->regattempts++;
  13634. return 0;
  13635. }
  13636. /* Copy back Call-ID in case create_addr changed it */
  13637. ast_string_field_set(r, callid, p->callid);
  13638. if (!r->dnsmgr && r->portno) {
  13639. ast_sockaddr_set_port(&p->sa, r->portno);
  13640. ast_sockaddr_set_port(&p->recv, r->portno);
  13641. }
  13642. if (!ast_strlen_zero(p->fromdomain)) {
  13643. portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
  13644. } else if (!ast_strlen_zero(r->regdomain)) {
  13645. portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
  13646. } else {
  13647. portno = ast_sockaddr_port(&p->sa);
  13648. }
  13649. ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
  13650. r->call = dialog_ref(p, "copying dialog into registry r->call"); /* Save pointer to SIP dialog */
  13651. p->registry = ao2_t_bump(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
  13652. if (!ast_strlen_zero(r->secret)) { /* Secret (password) */
  13653. ast_string_field_set(p, peersecret, r->secret);
  13654. }
  13655. if (!ast_strlen_zero(r->md5secret))
  13656. ast_string_field_set(p, peermd5secret, r->md5secret);
  13657. /* User name in this realm
  13658. - if authuser is set, use that, otherwise use username */
  13659. if (!ast_strlen_zero(r->authuser)) {
  13660. ast_string_field_set(p, peername, r->authuser);
  13661. ast_string_field_set(p, authname, r->authuser);
  13662. } else if (!ast_strlen_zero(r->username)) {
  13663. ast_string_field_set(p, peername, r->username);
  13664. ast_string_field_set(p, authname, r->username);
  13665. ast_string_field_set(p, fromuser, r->username);
  13666. }
  13667. if (!ast_strlen_zero(r->username)) {
  13668. ast_string_field_set(p, username, r->username);
  13669. }
  13670. /* Save extension in packet */
  13671. if (!ast_strlen_zero(r->callback)) {
  13672. ast_string_field_set(p, exten, r->callback);
  13673. }
  13674. /* Set transport and port so the correct contact is built */
  13675. set_socket_transport(&p->socket, r->transport);
  13676. if (r->transport == AST_TRANSPORT_TLS || r->transport == AST_TRANSPORT_TCP) {
  13677. p->socket.port =
  13678. htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
  13679. }
  13680. /*
  13681. check which address we should use in our contact header
  13682. based on whether the remote host is on the external or
  13683. internal network so we can register through nat
  13684. */
  13685. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  13686. }
  13687. /* set up a timeout */
  13688. if (auth == NULL) {
  13689. if (r->timeout > -1) {
  13690. ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
  13691. }
  13692. AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
  13693. ao2_t_ref(_data, -1, "reg ptr unrefed from del in SCHED_REPLACE"),
  13694. ao2_t_ref(r, -1, "reg ptr unrefed from add failure in SCHED_REPLACE"),
  13695. ao2_t_ref(r, +1, "reg ptr reffed from add in SCHED_REPLACE"));
  13696. ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
  13697. }
  13698. snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
  13699. if (!ast_strlen_zero(p->theirtag)) {
  13700. snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
  13701. } else {
  13702. snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
  13703. }
  13704. /* Fromdomain is what we are registering to, regardless of actual
  13705. host name from SRV */
  13706. if (portno && portno != STANDARD_SIP_PORT) {
  13707. snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
  13708. } else {
  13709. snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
  13710. }
  13711. ast_string_field_set(p, uri, addr);
  13712. p->branch ^= ast_random();
  13713. init_req(&req, sipmethod, addr);
  13714. /* Add to CSEQ */
  13715. snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
  13716. p->ocseq = r->ocseq;
  13717. build_via(p);
  13718. add_header(&req, "Via", p->via);
  13719. add_max_forwards(p, &req);
  13720. add_header(&req, "From", from);
  13721. add_header(&req, "To", to);
  13722. add_header(&req, "Call-ID", p->callid);
  13723. add_header(&req, "CSeq", tmp);
  13724. add_supported(p, &req);
  13725. if (!ast_strlen_zero(global_useragent))
  13726. add_header(&req, "User-Agent", global_useragent);
  13727. if (auth) { /* Add auth header */
  13728. add_header(&req, authheader, auth);
  13729. } else if (!ast_strlen_zero(r->nonce)) {
  13730. char digest[1024];
  13731. /* We have auth data to reuse, build a digest header.
  13732. * Note, this is not always useful because some parties do not
  13733. * like nonces to be reused (for good reasons!) so they will
  13734. * challenge us anyways.
  13735. */
  13736. if (sipdebug) {
  13737. ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
  13738. }
  13739. ast_string_field_set(p, realm, r->realm);
  13740. ast_string_field_set(p, nonce, r->nonce);
  13741. ast_string_field_set(p, domain, r->authdomain);
  13742. ast_string_field_set(p, opaque, r->opaque);
  13743. ast_string_field_set(p, qop, r->qop);
  13744. p->noncecount = ++r->noncecount;
  13745. memset(digest, 0, sizeof(digest));
  13746. if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
  13747. add_header(&req, "Authorization", digest);
  13748. } else {
  13749. ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
  13750. }
  13751. }
  13752. add_expires(&req, r->expiry);
  13753. build_contact(p, &req, 0);
  13754. add_header(&req, "Contact", p->our_contact);
  13755. initialize_initreq(p, &req);
  13756. if (sip_debug_test_pvt(p)) {
  13757. ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  13758. }
  13759. r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
  13760. r->regattempts++; /* Another attempt */
  13761. ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
  13762. res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  13763. dialog_unref(p, "p is finished here at the end of transmit_register");
  13764. return res;
  13765. }
  13766. /*!
  13767. * \brief Transmit with SIP MESSAGE method
  13768. * \note The p->msg_headers and p->msg_body are already setup.
  13769. */
  13770. static int transmit_message(struct sip_pvt *p, int init, int auth)
  13771. {
  13772. struct sip_request req;
  13773. if (init) {
  13774. initreqprep(&req, p, SIP_MESSAGE, NULL);
  13775. initialize_initreq(p, &req);
  13776. } else {
  13777. reqprep(&req, p, SIP_MESSAGE, 0, 1);
  13778. }
  13779. if (auth) {
  13780. return transmit_request_with_auth(p, SIP_MESSAGE, p->ocseq, XMIT_RELIABLE, 0);
  13781. } else {
  13782. add_text(&req, p);
  13783. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13784. }
  13785. }
  13786. /*! \brief Allocate SIP refer structure */
  13787. static int sip_refer_alloc(struct sip_pvt *p)
  13788. {
  13789. sip_refer_destroy(p);
  13790. p->refer = ast_calloc_with_stringfields(1, struct sip_refer, 512);
  13791. return p->refer ? 1 : 0;
  13792. }
  13793. /*! \brief Destroy SIP refer structure */
  13794. static void sip_refer_destroy(struct sip_pvt *p)
  13795. {
  13796. if (p->refer) {
  13797. ast_string_field_free_memory(p->refer);
  13798. ast_free(p->refer);
  13799. p->refer = NULL;
  13800. }
  13801. }
  13802. /*! \brief Allocate SIP refer structure */
  13803. static int sip_notify_alloc(struct sip_pvt *p)
  13804. {
  13805. p->notify = ast_calloc(1, sizeof(struct sip_notify));
  13806. if (p->notify) {
  13807. p->notify->content = ast_str_create(128);
  13808. }
  13809. return p->notify ? 1 : 0;
  13810. }
  13811. /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
  13812. \note this is currently broken as we have no way of telling the dialplan
  13813. engine whether a transfer succeeds or fails.
  13814. \todo Fix the transfer() dialplan function so that a transfer may fail
  13815. */
  13816. static int transmit_refer(struct sip_pvt *p, const char *dest)
  13817. {
  13818. char from[256];
  13819. const char *of;
  13820. char *c;
  13821. char referto[256];
  13822. int use_tls=FALSE;
  13823. if (sipdebug) {
  13824. ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
  13825. }
  13826. /* Are we transfering an inbound or outbound call ? */
  13827. if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  13828. of = sip_get_header(&p->initreq, "To");
  13829. } else {
  13830. of = sip_get_header(&p->initreq, "From");
  13831. }
  13832. ast_copy_string(from, of, sizeof(from));
  13833. of = get_in_brackets(from);
  13834. ast_string_field_set(p, from, of);
  13835. if (!strncasecmp(of, "sip:", 4)) {
  13836. of += 4;
  13837. } else if (!strncasecmp(of, "sips:", 5)) {
  13838. of += 5;
  13839. use_tls = TRUE;
  13840. } else {
  13841. ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
  13842. }
  13843. /* Get just the username part */
  13844. if (strchr(dest, '@')) {
  13845. c = NULL;
  13846. } else if ((c = strchr(of, '@'))) {
  13847. *c++ = '\0';
  13848. }
  13849. if (c) {
  13850. snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
  13851. } else {
  13852. snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
  13853. }
  13854. /* save in case we get 407 challenge */
  13855. sip_refer_alloc(p);
  13856. ast_string_field_set(p->refer, refer_to, referto);
  13857. ast_string_field_set(p->refer, referred_by, p->our_contact);
  13858. p->refer->status = REFER_SENT; /* Set refer status */
  13859. return transmit_invite(p, SIP_REFER, FALSE, 0, NULL);
  13860. /* We should propably wait for a NOTIFY here until we ack the transfer */
  13861. /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
  13862. /*! \todo In theory, we should hang around and wait for a reply, before
  13863. returning to the dial plan here. Don't know really how that would
  13864. affect the transfer() app or the pbx, but, well, to make this
  13865. useful we should have a STATUS code on transfer().
  13866. */
  13867. }
  13868. /*! \brief Send SIP INFO advice of charge message */
  13869. static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
  13870. {
  13871. struct sip_request req;
  13872. struct ast_str *str = ast_str_alloca(512);
  13873. const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
  13874. enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
  13875. reqprep(&req, p, SIP_INFO, 0, 1);
  13876. if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
  13877. ast_str_append(&str, 0, "type=active;");
  13878. } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
  13879. ast_str_append(&str, 0, "type=terminated;");
  13880. } else {
  13881. /* unsupported message type */
  13882. return -1;
  13883. }
  13884. switch (charging) {
  13885. case AST_AOC_CHARGE_FREE:
  13886. ast_str_append(&str, 0, "free-of-charge;");
  13887. break;
  13888. case AST_AOC_CHARGE_CURRENCY:
  13889. ast_str_append(&str, 0, "charging;");
  13890. ast_str_append(&str, 0, "charging-info=currency;");
  13891. ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
  13892. ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
  13893. if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
  13894. ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
  13895. }
  13896. break;
  13897. case AST_AOC_CHARGE_UNIT:
  13898. ast_str_append(&str, 0, "charging;");
  13899. ast_str_append(&str, 0, "charging-info=pulse;");
  13900. if (unit_entry) {
  13901. ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
  13902. }
  13903. break;
  13904. default:
  13905. ast_str_append(&str, 0, "not-available;");
  13906. };
  13907. add_header(&req, "AOC", ast_str_buffer(str));
  13908. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13909. }
  13910. /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
  13911. static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
  13912. {
  13913. struct sip_request req;
  13914. reqprep(&req, p, SIP_INFO, 0, 1);
  13915. add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
  13916. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13917. }
  13918. /*! \brief Send SIP INFO with video update request */
  13919. static int transmit_info_with_vidupdate(struct sip_pvt *p)
  13920. {
  13921. struct sip_request req;
  13922. reqprep(&req, p, SIP_INFO, 0, 1);
  13923. add_vidupdate(&req);
  13924. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13925. }
  13926. /*! \brief Transmit generic SIP request
  13927. returns XMIT_ERROR if transmit failed with a critical error (don't retry)
  13928. */
  13929. static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
  13930. {
  13931. struct sip_request resp;
  13932. reqprep(&resp, p, sipmethod, seqno, newbranch);
  13933. if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
  13934. add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
  13935. }
  13936. if (sipmethod == SIP_ACK) {
  13937. p->invitestate = INV_CONFIRMED;
  13938. }
  13939. return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
  13940. }
  13941. /*! \brief return the request and response header for a 401 or 407 code */
  13942. void sip_auth_headers(enum sip_auth_type code, char **header, char **respheader)
  13943. {
  13944. if (code == WWW_AUTH) { /* 401 */
  13945. *header = "WWW-Authenticate";
  13946. *respheader = "Authorization";
  13947. } else if (code == PROXY_AUTH) { /* 407 */
  13948. *header = "Proxy-Authenticate";
  13949. *respheader = "Proxy-Authorization";
  13950. } else {
  13951. ast_verbose("-- wrong response code %u\n", code);
  13952. *header = *respheader = "Invalid";
  13953. }
  13954. }
  13955. /*! \brief Transmit SIP request, auth added */
  13956. static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
  13957. {
  13958. struct sip_request resp;
  13959. reqprep(&resp, p, sipmethod, seqno, newbranch);
  13960. if (!ast_strlen_zero(p->realm)) {
  13961. char digest[1024];
  13962. memset(digest, 0, sizeof(digest));
  13963. if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
  13964. char *dummy, *response;
  13965. enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
  13966. sip_auth_headers(code, &dummy, &response);
  13967. add_header(&resp, response, digest);
  13968. } else {
  13969. ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
  13970. }
  13971. }
  13972. switch (sipmethod) {
  13973. case SIP_BYE:
  13974. {
  13975. char buf[20];
  13976. /*
  13977. * We are hanging up. If we know a cause for that, send it in
  13978. * clear text to make debugging easier.
  13979. */
  13980. if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
  13981. snprintf(buf, sizeof(buf), "Q.850;cause=%d", p->hangupcause & 0x7f);
  13982. add_header(&resp, "Reason", buf);
  13983. }
  13984. add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
  13985. snprintf(buf, sizeof(buf), "%d", p->hangupcause);
  13986. add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
  13987. break;
  13988. }
  13989. case SIP_MESSAGE:
  13990. add_text(&resp, p);
  13991. break;
  13992. default:
  13993. break;
  13994. }
  13995. return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
  13996. }
  13997. /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
  13998. static void destroy_association(struct sip_peer *peer)
  13999. {
  14000. int realtimeregs = ast_check_realtime("sipregs");
  14001. char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
  14002. if (!sip_cfg.ignore_regexpire) {
  14003. if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
  14004. ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "0", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
  14005. } else {
  14006. ast_db_del("SIP/Registry", peer->name);
  14007. ast_db_del("SIP/RegistryPath", peer->name);
  14008. ast_db_del("SIP/PeerMethods", peer->name);
  14009. }
  14010. }
  14011. }
  14012. static void set_socket_transport(struct sip_socket *socket, int transport)
  14013. {
  14014. /* if the transport type changes, clear all socket data */
  14015. if (socket->type != transport) {
  14016. socket->fd = -1;
  14017. socket->type = transport;
  14018. if (socket->tcptls_session) {
  14019. ao2_ref(socket->tcptls_session, -1);
  14020. socket->tcptls_session = NULL;
  14021. } else if (socket->ws_session) {
  14022. ast_websocket_unref(socket->ws_session);
  14023. socket->ws_session = NULL;
  14024. }
  14025. }
  14026. }
  14027. /*! \brief Expire registration of SIP peer */
  14028. static int expire_register(const void *data)
  14029. {
  14030. struct sip_peer *peer = (struct sip_peer *)data;
  14031. if (!peer) { /* Hmmm. We have no peer. Weird. */
  14032. return 0;
  14033. }
  14034. peer->expire = -1;
  14035. peer->portinuri = 0;
  14036. destroy_association(peer); /* remove registration data from storage */
  14037. set_socket_transport(&peer->socket, peer->default_outbound_transport);
  14038. if (peer->socket.tcptls_session) {
  14039. ao2_ref(peer->socket.tcptls_session, -1);
  14040. peer->socket.tcptls_session = NULL;
  14041. } else if (peer->socket.ws_session) {
  14042. ast_websocket_unref(peer->socket.ws_session);
  14043. peer->socket.ws_session = NULL;
  14044. }
  14045. if (peer->endpoint) {
  14046. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  14047. ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_OFFLINE);
  14048. blob = ast_json_pack("{s: s, s: s}",
  14049. "peer_status", "Unregistered",
  14050. "cause", "Expired");
  14051. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  14052. }
  14053. register_peer_exten(peer, FALSE); /* Remove regexten */
  14054. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  14055. /* Do we need to release this peer from memory?
  14056. Only for realtime peers and autocreated peers
  14057. */
  14058. if (peer->is_realtime) {
  14059. ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
  14060. }
  14061. if (peer->selfdestruct ||
  14062. ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
  14063. ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
  14064. }
  14065. if (!ast_sockaddr_isnull(&peer->addr)) {
  14066. /* We still need to unlink the peer from the peers_by_ip table,
  14067. * otherwise we end up with multiple copies hanging around each
  14068. * time a registration expires and the peer re-registers. */
  14069. ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
  14070. }
  14071. /* Only clear the addr after we check for destruction. The addr must remain
  14072. * in order to unlink from the peers_by_ip container correctly */
  14073. memset(&peer->addr, 0, sizeof(peer->addr));
  14074. sip_unref_peer(peer, "removing peer ref for expire_register");
  14075. return 0;
  14076. }
  14077. /*! \brief Poke peer (send qualify to check if peer is alive and well) */
  14078. static int sip_poke_peer_s(const void *data)
  14079. {
  14080. struct sip_peer *peer = (struct sip_peer *)data;
  14081. struct sip_peer *foundpeer;
  14082. peer->pokeexpire = -1;
  14083. foundpeer = ao2_find(peers, peer, OBJ_POINTER);
  14084. if (!foundpeer) {
  14085. sip_unref_peer(peer, "removing poke peer ref");
  14086. return 0;
  14087. } else if (foundpeer->name != peer->name) {
  14088. sip_unref_peer(foundpeer, "removing above peer ref");
  14089. sip_unref_peer(peer, "removing poke peer ref");
  14090. return 0;
  14091. }
  14092. sip_unref_peer(foundpeer, "removing above peer ref");
  14093. sip_poke_peer(peer, 0);
  14094. sip_unref_peer(peer, "removing poke peer ref");
  14095. return 0;
  14096. }
  14097. static int sip_poke_peer_now(const void *data)
  14098. {
  14099. struct sip_peer *peer = (struct sip_peer *) data;
  14100. peer->pokeexpire = -1;
  14101. sip_poke_peer(peer, 0);
  14102. sip_unref_peer(peer, "removing poke peer ref");
  14103. return 0;
  14104. }
  14105. /*! \brief Get registration details from Asterisk DB */
  14106. static void reg_source_db(struct sip_peer *peer)
  14107. {
  14108. char data[256];
  14109. char path[SIPBUFSIZE * 2];
  14110. struct ast_sockaddr sa;
  14111. int expire;
  14112. char full_addr[128];
  14113. AST_DECLARE_APP_ARGS(args,
  14114. AST_APP_ARG(addr);
  14115. AST_APP_ARG(port);
  14116. AST_APP_ARG(expiry_str);
  14117. AST_APP_ARG(username);
  14118. AST_APP_ARG(contact);
  14119. );
  14120. /* If read-only RT backend, then refresh from local DB cache */
  14121. if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
  14122. return;
  14123. }
  14124. if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
  14125. return;
  14126. }
  14127. AST_NONSTANDARD_RAW_ARGS(args, data, ':');
  14128. snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
  14129. if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
  14130. return;
  14131. }
  14132. if (args.expiry_str) {
  14133. expire = atoi(args.expiry_str);
  14134. } else {
  14135. return;
  14136. }
  14137. if (args.username) {
  14138. ast_string_field_set(peer, username, args.username);
  14139. }
  14140. if (args.contact) {
  14141. ast_string_field_set(peer, fullcontact, args.contact);
  14142. }
  14143. ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
  14144. peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
  14145. ast_sockaddr_copy(&peer->addr, &sa);
  14146. if (peer->maxms) {
  14147. /* Don't poke peer immediately, just schedule it within qualifyfreq */
  14148. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
  14149. ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
  14150. sip_poke_peer_s, peer,
  14151. sip_unref_peer(_data, "removing poke peer ref"),
  14152. sip_unref_peer(peer, "removing poke peer ref"),
  14153. sip_ref_peer(peer, "adding poke peer ref"));
  14154. }
  14155. AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
  14156. sip_unref_peer(_data, "remove registration ref"),
  14157. sip_unref_peer(peer, "remove registration ref"),
  14158. sip_ref_peer(peer, "add registration ref"));
  14159. register_peer_exten(peer, TRUE);
  14160. if (!ast_db_get("SIP/RegistryPath", peer->name, path, sizeof(path))) {
  14161. build_path(NULL, peer, NULL, path);
  14162. }
  14163. }
  14164. /*! \brief Save contact header for 200 OK on INVITE */
  14165. static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
  14166. {
  14167. char contact[SIPBUFSIZE];
  14168. char *c;
  14169. /* Look for brackets */
  14170. ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
  14171. c = get_in_brackets(contact);
  14172. /* Save full contact to call pvt for later bye or re-invite */
  14173. ast_string_field_set(pvt, fullcontact, c);
  14174. /* Save URI for later ACKs, BYE or RE-invites */
  14175. ast_string_field_set(pvt, okcontacturi, c);
  14176. /* We should return false for URI:s we can't handle,
  14177. like tel:, mailto:,ldap: etc */
  14178. return TRUE;
  14179. }
  14180. /*! \brief parse uri in a way that allows semicolon stripping if legacy mode is enabled
  14181. *
  14182. * \note This calls parse_uri which has the unexpected property that passing more
  14183. * arguments results in more splitting. Most common is to leave out the pass
  14184. * argument, causing user to contain user:pass if available.
  14185. */
  14186. static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
  14187. {
  14188. int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
  14189. if (sip_cfg.legacy_useroption_parsing) { /* if legacy mode is active, strip semis from the user field */
  14190. char *p;
  14191. if ((p = strchr(uri, (int)';'))) {
  14192. *p = '\0';
  14193. }
  14194. }
  14195. return ret;
  14196. }
  14197. static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
  14198. {
  14199. char *hostport, *transport;
  14200. char contact_buf[256];
  14201. char *contact;
  14202. /* Work on a copy */
  14203. ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
  14204. contact = contact_buf;
  14205. /*
  14206. * We have only the part in <brackets> here so we just need to parse a SIP URI.
  14207. *
  14208. * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
  14209. * We still need to be able to send to the remote agent through the proxy.
  14210. */
  14211. if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
  14212. &transport)) {
  14213. ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
  14214. }
  14215. /* XXX This could block for a long time XXX */
  14216. /* We should only do this if it's a name, not an IP */
  14217. /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
  14218. to find transport, port address and hostname. If there's a port number, we have to
  14219. assume that the hostport part is a host name and only look for an A/AAAA record in DNS.
  14220. */
  14221. /* If we took in an invalid URI, hostport may not have been initialized */
  14222. /* ast_sockaddr_resolve requires an initialized hostport string. */
  14223. if (ast_strlen_zero(hostport)) {
  14224. ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
  14225. return -1;
  14226. }
  14227. if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
  14228. ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
  14229. "resolve in DNS) : '%s'\n", hostport);
  14230. return -1;
  14231. }
  14232. /* set port */
  14233. if (!ast_sockaddr_port(addr)) {
  14234. ast_sockaddr_set_port(addr,
  14235. (get_transport_str2enum(transport) ==
  14236. AST_TRANSPORT_TLS ||
  14237. !strncasecmp(fullcontact, "sips", 4)) ?
  14238. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  14239. }
  14240. return 0;
  14241. }
  14242. /*! \brief Change the other partys IP address based on given contact */
  14243. static int set_address_from_contact(struct sip_pvt *pvt)
  14244. {
  14245. if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
  14246. /* NAT: Don't trust the contact field. Just use what they came to us
  14247. with. */
  14248. /*! \todo We need to save the TRANSPORT here too */
  14249. pvt->sa = pvt->recv;
  14250. return 0;
  14251. }
  14252. return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == AST_TRANSPORT_TLS ? 1 : 0);
  14253. }
  14254. /*! \brief Parse contact header and save registration (peer registration) */
  14255. static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
  14256. {
  14257. char contact[SIPBUFSIZE];
  14258. char data[SIPBUFSIZE];
  14259. const char *expires = sip_get_header(req, "Expires");
  14260. int expire = atoi(expires);
  14261. char *curi = NULL, *hostport = NULL, *transport = NULL;
  14262. int transport_type;
  14263. const char *useragent;
  14264. struct ast_sockaddr oldsin, testsa;
  14265. char *firstcuri = NULL;
  14266. int start = 0;
  14267. int wildcard_found = 0;
  14268. int single_binding_found = 0;
  14269. ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
  14270. if (ast_strlen_zero(expires)) { /* No expires header, try look in Contact: */
  14271. char *s = strcasestr(contact, ";expires=");
  14272. if (s) {
  14273. expires = strsep(&s, ";"); /* trim ; and beyond */
  14274. if (sscanf(expires + 9, "%30d", &expire) != 1) {
  14275. expire = default_expiry;
  14276. }
  14277. } else {
  14278. /* Nothing has been specified */
  14279. expire = default_expiry;
  14280. }
  14281. }
  14282. if (expire > max_expiry) {
  14283. expire = max_expiry;
  14284. }
  14285. if (expire < min_expiry && expire != 0) {
  14286. expire = min_expiry;
  14287. }
  14288. pvt->expiry = expire;
  14289. copy_socket_data(&pvt->socket, &req->socket);
  14290. do {
  14291. /* Look for brackets */
  14292. curi = contact;
  14293. if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
  14294. strsep(&curi, ";"); /* This is Header options, not URI options */
  14295. curi = get_in_brackets(contact);
  14296. if (!firstcuri) {
  14297. firstcuri = ast_strdupa(curi);
  14298. }
  14299. if (!strcasecmp(curi, "*")) {
  14300. wildcard_found = 1;
  14301. } else {
  14302. single_binding_found = 1;
  14303. }
  14304. if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
  14305. /* Contact header parameter "*" detected, so punt if: Expires header is missing,
  14306. * Expires value is not zero, or another Contact header is present. */
  14307. return PARSE_REGISTER_FAILED;
  14308. }
  14309. ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
  14310. } while (!ast_strlen_zero(contact));
  14311. curi = firstcuri;
  14312. /* if they did not specify Contact: or Expires:, they are querying
  14313. what we currently have stored as their contact address, so return
  14314. it
  14315. */
  14316. if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
  14317. /* If we have an active registration, tell them when the registration is going to expire */
  14318. if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
  14319. pvt->expiry = ast_sched_when(sched, peer->expire);
  14320. }
  14321. return PARSE_REGISTER_QUERY;
  14322. } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
  14323. /* This means remove all registrations and return OK */
  14324. AST_SCHED_DEL_UNREF(sched, peer->expire,
  14325. sip_unref_peer(peer, "remove register expire ref"));
  14326. ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
  14327. expire_register(sip_ref_peer(peer,"add ref for explicit expire_register"));
  14328. return PARSE_REGISTER_UPDATE;
  14329. }
  14330. /* Store whatever we got as a contact from the client */
  14331. ast_string_field_set(peer, fullcontact, curi);
  14332. /* For the 200 OK, we should use the received contact */
  14333. ast_string_field_build(pvt, our_contact, "<%s>", curi);
  14334. /* Make sure it's a SIP URL */
  14335. if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
  14336. ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
  14337. }
  14338. /* handle the transport type specified in Contact header. */
  14339. if (!(transport_type = get_transport_str2enum(transport))) {
  14340. transport_type = pvt->socket.type;
  14341. }
  14342. /* if the peer's socket type is different than the Registration
  14343. * transport type, change it. If it got this far, it is a
  14344. * supported type, but check just in case */
  14345. if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
  14346. set_socket_transport(&peer->socket, transport_type);
  14347. }
  14348. oldsin = peer->addr;
  14349. /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
  14350. if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
  14351. ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
  14352. }
  14353. if ((transport_type != AST_TRANSPORT_WS) && (transport_type != AST_TRANSPORT_WSS) &&
  14354. (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT))) {
  14355. /* use the data provided in the Contact header for call routing */
  14356. ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
  14357. /* XXX This could block for a long time XXX */
  14358. /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
  14359. if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
  14360. ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
  14361. ast_string_field_set(peer, fullcontact, "");
  14362. ast_string_field_set(pvt, our_contact, "");
  14363. return PARSE_REGISTER_FAILED;
  14364. }
  14365. /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
  14366. The hostport part is actually a host. */
  14367. peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
  14368. if (!ast_sockaddr_port(&testsa)) {
  14369. ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
  14370. }
  14371. ast_sockaddr_copy(&peer->addr, &testsa);
  14372. } else {
  14373. /* Don't trust the contact field. Just use what they came to us
  14374. with */
  14375. ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
  14376. peer->addr = pvt->recv;
  14377. }
  14378. /* Check that they're allowed to register at this IP */
  14379. if (ast_apply_acl(sip_cfg.contact_acl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW ||
  14380. ast_apply_acl(peer->contactacl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW) {
  14381. ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
  14382. ast_sockaddr_stringify_addr(&peer->addr));
  14383. ast_string_field_set(peer, fullcontact, "");
  14384. ast_string_field_set(pvt, our_contact, "");
  14385. return PARSE_REGISTER_DENIED;
  14386. }
  14387. /* if the Contact header information copied into peer->addr matches the
  14388. * received address, and the transport types are the same, then copy socket
  14389. * data into the peer struct */
  14390. if ((peer->socket.type == pvt->socket.type) &&
  14391. !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
  14392. copy_socket_data(&peer->socket, &pvt->socket);
  14393. }
  14394. /* Now that our address has been updated put ourselves back into the container for lookups */
  14395. if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  14396. ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
  14397. }
  14398. /* Save SIP options profile */
  14399. peer->sipoptions = pvt->sipoptions;
  14400. if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
  14401. ast_string_field_set(peer, username, curi);
  14402. }
  14403. AST_SCHED_DEL_UNREF(sched, peer->expire,
  14404. sip_unref_peer(peer, "remove register expire ref"));
  14405. if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  14406. peer->expire = -1;
  14407. } else {
  14408. peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
  14409. sip_ref_peer(peer, "add registration ref"));
  14410. if (peer->expire == -1) {
  14411. sip_unref_peer(peer, "remote registration ref");
  14412. }
  14413. }
  14414. if (!build_path(pvt, peer, req, NULL)) {
  14415. /* Tell the dialog to use the Path header in the response */
  14416. ast_set2_flag(&pvt->flags[0], 1, SIP_USEPATH);
  14417. }
  14418. snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
  14419. expire, peer->username, peer->fullcontact);
  14420. /* We might not immediately be able to reconnect via TCP, but try caching it anyhow */
  14421. if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate) {
  14422. if (!sip_route_empty(&peer->path)) {
  14423. struct ast_str *r = sip_route_list(&peer->path, 0, 0);
  14424. if (r) {
  14425. ast_db_put("SIP/RegistryPath", peer->name, ast_str_buffer(r));
  14426. ast_free(r);
  14427. }
  14428. }
  14429. ast_db_put("SIP/Registry", peer->name, data);
  14430. }
  14431. if (peer->endpoint) {
  14432. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  14433. ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_ONLINE);
  14434. blob = ast_json_pack("{s: s, s: s}",
  14435. "peer_status", "Registered",
  14436. "address", ast_sockaddr_stringify(&peer->addr));
  14437. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  14438. }
  14439. /* Is this a new IP address for us? */
  14440. if (ast_sockaddr_cmp(&peer->addr, &oldsin)) {
  14441. ast_verb(3, "Registered SIP '%s' at %s\n", peer->name,
  14442. ast_sockaddr_stringify(&peer->addr));
  14443. }
  14444. sip_pvt_unlock(pvt);
  14445. sip_poke_peer(peer, 0);
  14446. sip_pvt_lock(pvt);
  14447. register_peer_exten(peer, 1);
  14448. /* Save User agent */
  14449. useragent = sip_get_header(req, "User-Agent");
  14450. if (strcasecmp(useragent, peer->useragent)) {
  14451. ast_string_field_set(peer, useragent, useragent);
  14452. ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
  14453. }
  14454. return PARSE_REGISTER_UPDATE;
  14455. }
  14456. /*! \brief Build route list from Record-Route header
  14457. *
  14458. * \param p
  14459. * \param req
  14460. * \param backwards
  14461. * \param resp the SIP response code or 0 for a request
  14462. *
  14463. */
  14464. static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
  14465. {
  14466. int start = 0;
  14467. const char *header;
  14468. /* Once a persistent route is set, don't fool with it */
  14469. if (!sip_route_empty(&p->route) && p->route_persistent) {
  14470. ast_debug(1, "build_route: Retaining previous route: <%s>\n", sip_route_first_uri(&p->route));
  14471. return;
  14472. }
  14473. sip_route_clear(&p->route);
  14474. /* We only want to create the route set the first time this is called except
  14475. it is called from a provisional response.*/
  14476. if ((resp < 100) || (resp > 199)) {
  14477. p->route_persistent = 1;
  14478. }
  14479. /* Build a tailq, then assign it to p->route when done.
  14480. * If backwards, we add entries from the head so they end up
  14481. * in reverse order. However, we do need to maintain a correct
  14482. * tail pointer because the contact is always at the end.
  14483. */
  14484. /* 1st we pass through all the hops in any Record-Route headers */
  14485. for (;;) {
  14486. header = __get_header(req, "Record-Route", &start);
  14487. if (*header == '\0') {
  14488. break;
  14489. }
  14490. sip_route_process_header(&p->route, header, backwards);
  14491. }
  14492. /* Only append the contact if we are dealing with a strict router or have no route */
  14493. if (sip_route_empty(&p->route) || sip_route_is_strict(&p->route)) {
  14494. /* 2nd append the Contact: if there is one */
  14495. /* Can be multiple Contact headers, comma separated values - we just take the first */
  14496. int len;
  14497. header = sip_get_header(req, "Contact");
  14498. if (strchr(header, '<')) {
  14499. get_in_brackets_const(header, &header, &len);
  14500. } else {
  14501. len = strlen(header);
  14502. }
  14503. if (header && len) {
  14504. sip_route_add(&p->route, header, len, 0);
  14505. }
  14506. }
  14507. /* For debugging dump what we ended up with */
  14508. if (sip_debug_test_pvt(p)) {
  14509. sip_route_dump(&p->route);
  14510. }
  14511. }
  14512. /*! \brief Build route list from Path header
  14513. * RFC 3327 requires that the Path header contains SIP URIs with lr paramter.
  14514. * Thus, we do not care about strict routing SIP routers
  14515. */
  14516. static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, const char *pathbuf)
  14517. {
  14518. sip_route_clear(&peer->path);
  14519. if (!ast_test_flag(&peer->flags[0], SIP_USEPATH)) {
  14520. ast_debug(2, "build_path: do not use Path headers\n");
  14521. return -1;
  14522. }
  14523. ast_debug(2, "build_path: try to build pre-loaded route-set by parsing Path headers\n");
  14524. if (req) {
  14525. int start = 0;
  14526. const char *header;
  14527. for (;;) {
  14528. header = __get_header(req, "Path", &start);
  14529. if (*header == '\0') {
  14530. break;
  14531. }
  14532. sip_route_process_header(&peer->path, header, 0);
  14533. }
  14534. } else if (pathbuf) {
  14535. sip_route_process_header(&peer->path, pathbuf, 0);
  14536. }
  14537. /* Caches result for any dialog->route copied from peer->path */
  14538. sip_route_is_strict(&peer->path);
  14539. /* For debugging dump what we ended up with */
  14540. if (p && sip_debug_test_pvt(p)) {
  14541. sip_route_dump(&peer->path);
  14542. }
  14543. return 0;
  14544. }
  14545. /*! \brief builds the sip_pvt's nonce field which is used for the authentication
  14546. * challenge. When forceupdate is not set, the nonce is only updated if
  14547. * the current one is stale. In this case, a stalenonce is one which
  14548. * has already received a response, if a nonce has not received a response
  14549. * it is not always necessary or beneficial to create a new one. */
  14550. static void build_nonce(struct sip_pvt *p, int forceupdate)
  14551. {
  14552. if (p->stalenonce || forceupdate || ast_strlen_zero(p->nonce)) {
  14553. ast_string_field_build(p, nonce, "%08lx", (unsigned long)ast_random()); /* Create nonce for challenge */
  14554. p->stalenonce = 0;
  14555. }
  14556. }
  14557. /*! \brief Takes the digest response and parses it */
  14558. void sip_digest_parser(char *c, struct digestkeys *keys)
  14559. {
  14560. struct digestkeys *i = i;
  14561. while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
  14562. for (i = keys; i->key != NULL; i++) {
  14563. const char *separator = ","; /* default */
  14564. if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
  14565. continue;
  14566. }
  14567. /* Found. Skip keyword, take text in quotes or up to the separator. */
  14568. c += strlen(i->key);
  14569. if (*c == '"') { /* in quotes. Skip first and look for last */
  14570. c++;
  14571. separator = "\"";
  14572. }
  14573. i->s = c;
  14574. strsep(&c, separator);
  14575. break;
  14576. }
  14577. if (i->key == NULL) { /* not found, jump after space or comma */
  14578. strsep(&c, " ,");
  14579. }
  14580. }
  14581. }
  14582. /*! \brief Check user authorization from peer definition
  14583. Some actions, like REGISTER and INVITEs from peers require
  14584. authentication (if peer have secret set)
  14585. \return 0 on success, non-zero on error
  14586. */
  14587. static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
  14588. const char *secret, const char *md5secret, int sipmethod,
  14589. const char *uri, enum xmittype reliable)
  14590. {
  14591. const char *response;
  14592. char *reqheader, *respheader;
  14593. const char *authtoken;
  14594. char a1_hash[256];
  14595. char resp_hash[256]="";
  14596. char *c;
  14597. int is_bogus_peer = 0;
  14598. int wrongnonce = FALSE;
  14599. int good_response;
  14600. const char *usednonce = p->nonce;
  14601. struct ast_str *buf;
  14602. int res;
  14603. /* table of recognised keywords, and their value in the digest */
  14604. struct digestkeys keys[] = {
  14605. [K_RESP] = { "response=", "" },
  14606. [K_URI] = { "uri=", "" },
  14607. [K_USER] = { "username=", "" },
  14608. [K_NONCE] = { "nonce=", "" },
  14609. [K_LAST] = { NULL, NULL}
  14610. };
  14611. /* Always OK if no secret */
  14612. if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)) {
  14613. return AUTH_SUCCESSFUL;
  14614. }
  14615. /* Always auth with WWW-auth since we're NOT a proxy */
  14616. /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
  14617. response = "401 Unauthorized";
  14618. /*
  14619. * Note the apparent swap of arguments below, compared to other
  14620. * usages of sip_auth_headers().
  14621. */
  14622. sip_auth_headers(WWW_AUTH, &respheader, &reqheader);
  14623. authtoken = sip_get_header(req, reqheader);
  14624. if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
  14625. /* This is a retransmitted invite/register/etc, don't reconstruct authentication
  14626. information */
  14627. if (!reliable) {
  14628. /* Resend message if this was NOT a reliable delivery. Otherwise the
  14629. retransmission should get it */
  14630. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
  14631. /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
  14632. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14633. }
  14634. return AUTH_CHALLENGE_SENT;
  14635. } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
  14636. /* We have no auth, so issue challenge and request authentication */
  14637. build_nonce(p, 1); /* Create nonce for challenge */
  14638. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
  14639. /* Schedule auto destroy in 32 seconds */
  14640. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14641. return AUTH_CHALLENGE_SENT;
  14642. }
  14643. /* --- We have auth, so check it */
  14644. /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
  14645. an example in the spec of just what it is you're doing a hash on. */
  14646. if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
  14647. return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
  14648. }
  14649. /* Make a copy of the response and parse it */
  14650. res = ast_str_set(&buf, 0, "%s", authtoken);
  14651. if (res == AST_DYNSTR_BUILD_FAILED) {
  14652. return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
  14653. }
  14654. c = ast_str_buffer(buf);
  14655. sip_digest_parser(c, keys);
  14656. /* We cannot rely on the bogus_peer having a bad md5 value. Someone could
  14657. * use it to construct valid auth. */
  14658. if (md5secret && strcmp(md5secret, BOGUS_PEER_MD5SECRET) == 0) {
  14659. is_bogus_peer = 1;
  14660. }
  14661. /* Verify that digest username matches the username we auth as */
  14662. if (strcmp(username, keys[K_USER].s) && !is_bogus_peer) {
  14663. ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
  14664. username, keys[K_USER].s);
  14665. /* Oops, we're trying something here */
  14666. return AUTH_USERNAME_MISMATCH;
  14667. }
  14668. /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
  14669. * If this check fails, send 401 with new nonce */
  14670. if (strcasecmp(p->nonce, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
  14671. wrongnonce = TRUE;
  14672. usednonce = keys[K_NONCE].s;
  14673. } else {
  14674. p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
  14675. }
  14676. if (!ast_strlen_zero(md5secret)) {
  14677. ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
  14678. } else {
  14679. char a1[256];
  14680. snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
  14681. ast_md5_hash(a1_hash, a1);
  14682. }
  14683. /* compute the expected response to compare with what we received */
  14684. {
  14685. char a2[256];
  14686. char a2_hash[256];
  14687. char resp[256];
  14688. snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
  14689. S_OR(keys[K_URI].s, uri));
  14690. ast_md5_hash(a2_hash, a2);
  14691. snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
  14692. ast_md5_hash(resp_hash, resp);
  14693. }
  14694. good_response = keys[K_RESP].s &&
  14695. !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash)) &&
  14696. !is_bogus_peer; /* lastly, check that the peer isn't the fake peer */
  14697. if (wrongnonce) {
  14698. if (good_response) {
  14699. if (sipdebug)
  14700. ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", sip_get_header(req, "From"));
  14701. /* We got working auth token, based on stale nonce . */
  14702. build_nonce(p, 0);
  14703. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, TRUE);
  14704. } else {
  14705. /* Everything was wrong, so give the device one more try with a new challenge */
  14706. if (!req->ignore) {
  14707. if (sipdebug) {
  14708. ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", sip_get_header(req, "To"));
  14709. }
  14710. build_nonce(p, 1);
  14711. } else {
  14712. if (sipdebug) {
  14713. ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", sip_get_header(req, "To"));
  14714. }
  14715. }
  14716. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
  14717. }
  14718. /* Schedule auto destroy in 32 seconds */
  14719. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14720. return AUTH_CHALLENGE_SENT;
  14721. }
  14722. if (good_response) {
  14723. append_history(p, "AuthOK", "Auth challenge successful for %s", username);
  14724. return AUTH_SUCCESSFUL;
  14725. }
  14726. /* Ok, we have a bad username/secret pair */
  14727. /* Tell the UAS not to re-send this authentication data, because
  14728. it will continue to fail
  14729. */
  14730. return AUTH_SECRET_FAILED;
  14731. }
  14732. /*! \brief Change onhold state of a peer using a pvt structure */
  14733. static void sip_peer_hold(struct sip_pvt *p, int hold)
  14734. {
  14735. if (!p->relatedpeer) {
  14736. return;
  14737. }
  14738. /* If they put someone on hold, increment the value... otherwise decrement it */
  14739. ast_atomic_fetchadd_int(&p->relatedpeer->onhold, (hold ? +1 : -1));
  14740. /* Request device state update */
  14741. ast_devstate_changed(AST_DEVICE_UNKNOWN, (ast_test_flag(ast_channel_flags(p->owner), AST_FLAG_DISABLE_DEVSTATE_CACHE) ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE),
  14742. "SIP/%s", p->relatedpeer->name);
  14743. return;
  14744. }
  14745. /*! \brief Receive MWI events that we have subscribed to */
  14746. static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
  14747. {
  14748. char *peer_name = userdata;
  14749. struct sip_peer *peer = sip_find_peer(peer_name, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
  14750. if (stasis_subscription_final_message(sub, msg)) {
  14751. if (peer) {
  14752. /* configuration reloaded */
  14753. return;
  14754. }
  14755. ast_free(peer_name);
  14756. return;
  14757. }
  14758. if (peer && ast_mwi_state_type() == stasis_message_type(msg)) {
  14759. sip_send_mwi_to_peer(peer, 0);
  14760. }
  14761. ao2_cleanup(peer);
  14762. }
  14763. static void network_change_stasis_subscribe(void)
  14764. {
  14765. if (!network_change_sub) {
  14766. network_change_sub = stasis_subscribe(ast_system_topic(),
  14767. network_change_stasis_cb, NULL);
  14768. }
  14769. }
  14770. static void network_change_stasis_unsubscribe(void)
  14771. {
  14772. network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
  14773. }
  14774. static void acl_change_stasis_subscribe(void)
  14775. {
  14776. if (!acl_change_sub) {
  14777. acl_change_sub = stasis_subscribe(ast_security_topic(),
  14778. acl_change_stasis_cb, NULL);
  14779. }
  14780. }
  14781. static void acl_change_event_stasis_unsubscribe(void)
  14782. {
  14783. acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
  14784. }
  14785. static int network_change_sched_cb(const void *data)
  14786. {
  14787. network_change_sched_id = -1;
  14788. sip_send_all_registers();
  14789. sip_send_all_mwi_subscriptions();
  14790. return 0;
  14791. }
  14792. static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
  14793. {
  14794. /* This callback is only concerned with network change messages from the system topic. */
  14795. if (stasis_message_type(message) != ast_network_change_type()) {
  14796. return;
  14797. }
  14798. ast_verb(1, "SIP, got a network change message, renewing all SIP registrations.\n");
  14799. if (network_change_sched_id == -1) {
  14800. network_change_sched_id = ast_sched_add(sched, 1000, network_change_sched_cb, NULL);
  14801. }
  14802. }
  14803. static void cb_extensionstate_destroy(int id, void *data)
  14804. {
  14805. struct sip_pvt *p = data;
  14806. dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
  14807. }
  14808. /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
  14809. \note If you add an "hint" priority to the extension in the dial plan,
  14810. you will get notifications on device state changes */
  14811. static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force)
  14812. {
  14813. sip_pvt_lock(p);
  14814. switch (data->state) {
  14815. case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
  14816. case AST_EXTENSION_REMOVED: /* Extension is gone */
  14817. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
  14818. ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, data->state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
  14819. p->subscribed = NONE;
  14820. append_history(p, "Subscribestatus", "%s", data->state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
  14821. break;
  14822. default: /* Tell user */
  14823. if (force) {
  14824. /* we must skip the next two checks for a queued state change or resubscribe */
  14825. } else if ((p->laststate == data->state && (~data->state & AST_EXTENSION_RINGING)) &&
  14826. (p->last_presence_state == data->presence_state &&
  14827. !strcmp(p->last_presence_subtype, data->presence_subtype) &&
  14828. !strcmp(p->last_presence_message, data->presence_message))) {
  14829. /* don't notify unchanged state or unchanged early-state causing parties again */
  14830. sip_pvt_unlock(p);
  14831. return 0;
  14832. } else if (data->state & AST_EXTENSION_RINGING) {
  14833. /* check if another channel than last time is ringing now to be notified */
  14834. struct ast_channel *ringing = find_ringing_channel(data->device_state_info, p);
  14835. if (ringing) {
  14836. if (!ast_tvcmp(ast_channel_creationtime(ringing), p->last_ringing_channel_time)) {
  14837. /* we assume here that no two channels have the exact same creation time */
  14838. ao2_ref(ringing, -1);
  14839. sip_pvt_unlock(p);
  14840. return 0;
  14841. } else {
  14842. p->last_ringing_channel_time = ast_channel_creationtime(ringing);
  14843. ao2_ref(ringing, -1);
  14844. }
  14845. }
  14846. /* If no ringing channel was found, it doesn't necessarily indicate anything bad.
  14847. * Likely, a device state change occurred for a custom device state, which does not
  14848. * correspond to any channel. In such a case, just go ahead and pass the notification
  14849. * along.
  14850. */
  14851. }
  14852. /* ref before unref because the new could be the same as the old one. Don't risk destruction! */
  14853. if (data->device_state_info) {
  14854. ao2_ref(data->device_state_info, 1);
  14855. }
  14856. ao2_cleanup(p->last_device_state_info);
  14857. p->last_device_state_info = data->device_state_info;
  14858. p->laststate = data->state;
  14859. p->last_presence_state = data->presence_state;
  14860. ast_string_field_set(p, last_presence_subtype, S_OR(data->presence_subtype, ""));
  14861. ast_string_field_set(p, last_presence_message, S_OR(data->presence_message, ""));
  14862. break;
  14863. }
  14864. if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
  14865. if (!p->pendinginvite) {
  14866. transmit_state_notify(p, data, 1, FALSE);
  14867. if (p->last_device_state_info) {
  14868. /* We don't need the saved ref anymore, don't keep channels ref'd. */
  14869. ao2_ref(p->last_device_state_info, -1);
  14870. p->last_device_state_info = NULL;
  14871. }
  14872. } else {
  14873. /* We already have a NOTIFY sent that is not answered. Queue the state up.
  14874. if many state changes happen meanwhile, we will only send a notification of the last one */
  14875. ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
  14876. }
  14877. }
  14878. if (!force) {
  14879. ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(data->state), p->username,
  14880. ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
  14881. }
  14882. sip_pvt_unlock(p);
  14883. return 0;
  14884. }
  14885. /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
  14886. \note If you add an "hint" priority to the extension in the dial plan,
  14887. you will get notifications on device state changes */
  14888. static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data)
  14889. {
  14890. struct sip_pvt *p = data;
  14891. struct state_notify_data notify_data = {
  14892. .state = info->exten_state,
  14893. .device_state_info = info->device_state_info,
  14894. .presence_state = info->presence_state,
  14895. .presence_subtype = info->presence_subtype,
  14896. .presence_message = info->presence_message,
  14897. };
  14898. if ((info->reason == AST_HINT_UPDATE_PRESENCE) && !(allow_notify_user_presence(p))) {
  14899. /* ignore a presence triggered update if we know the useragent doesn't care */
  14900. return 0;
  14901. }
  14902. return extensionstate_update(context, exten, &notify_data, p, FALSE);
  14903. }
  14904. /*! \brief Send a fake 401 Unauthorized response when the administrator
  14905. wants to hide the names of local devices from fishers
  14906. */
  14907. static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable)
  14908. {
  14909. /* We have to emulate EXACTLY what we'd get with a good peer
  14910. * and a bad password, or else we leak information. */
  14911. const char *response = "401 Unauthorized";
  14912. const char *reqheader = "Authorization";
  14913. const char *respheader = "WWW-Authenticate";
  14914. const char *authtoken;
  14915. struct ast_str *buf;
  14916. char *c;
  14917. /* table of recognised keywords, and their value in the digest */
  14918. enum keys { K_NONCE, K_LAST };
  14919. struct x {
  14920. const char *key;
  14921. const char *s;
  14922. } *i, keys[] = {
  14923. [K_NONCE] = { "nonce=", "" },
  14924. [K_LAST] = { NULL, NULL}
  14925. };
  14926. authtoken = sip_get_header(req, reqheader);
  14927. if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
  14928. /* This is a retransmitted invite/register/etc, don't reconstruct authentication
  14929. * information */
  14930. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
  14931. /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
  14932. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14933. return;
  14934. } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
  14935. /* We have no auth, so issue challenge and request authentication */
  14936. build_nonce(p, 1);
  14937. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
  14938. /* Schedule auto destroy in 32 seconds */
  14939. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14940. return;
  14941. }
  14942. if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
  14943. __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
  14944. return;
  14945. }
  14946. /* Make a copy of the response and parse it */
  14947. if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
  14948. __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
  14949. return;
  14950. }
  14951. c = ast_str_buffer(buf);
  14952. while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
  14953. for (i = keys; i->key != NULL; i++) {
  14954. const char *separator = ","; /* default */
  14955. if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
  14956. continue;
  14957. }
  14958. /* Found. Skip keyword, take text in quotes or up to the separator. */
  14959. c += strlen(i->key);
  14960. if (*c == '"') { /* in quotes. Skip first and look for last */
  14961. c++;
  14962. separator = "\"";
  14963. }
  14964. i->s = c;
  14965. strsep(&c, separator);
  14966. break;
  14967. }
  14968. if (i->key == NULL) { /* not found, jump after space or comma */
  14969. strsep(&c, " ,");
  14970. }
  14971. }
  14972. /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
  14973. if (strcasecmp(p->nonce, keys[K_NONCE].s)) {
  14974. if (!req->ignore) {
  14975. build_nonce(p, 1);
  14976. }
  14977. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
  14978. /* Schedule auto destroy in 32 seconds */
  14979. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14980. } else {
  14981. __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
  14982. }
  14983. }
  14984. /*!
  14985. * Terminate the uri at the first ';' or space.
  14986. * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
  14987. * but don't do it for the time being. Remember the uri format is:
  14988. * (User-parameters was added after RFC 3261)
  14989. *\verbatim
  14990. *
  14991. * sip:user:password;user-parameters@host:port;uri-parameters?headers
  14992. * sips:user:password;user-parameters@host:port;uri-parameters?headers
  14993. *
  14994. *\endverbatim
  14995. * \todo As this function does not support user-parameters, it's considered broken
  14996. * and needs fixing.
  14997. */
  14998. static char *terminate_uri(char *uri)
  14999. {
  15000. char *t = uri;
  15001. while (*t && *t > ' ' && *t != ';') {
  15002. t++;
  15003. }
  15004. *t = '\0';
  15005. return uri;
  15006. }
  15007. /*! \brief Terminate a host:port at the ':'
  15008. * \param hostport The address of the hostport string
  15009. *
  15010. * \note In the case of a bracket-enclosed IPv6 address, the hostport variable
  15011. * will contain the non-bracketed host as a result of calling this function.
  15012. */
  15013. static void extract_host_from_hostport(char **hostport)
  15014. {
  15015. char *dont_care;
  15016. ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
  15017. }
  15018. /*!
  15019. * \internal
  15020. * \brief Helper function to update a peer's lastmsgssent value
  15021. */
  15022. static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
  15023. {
  15024. if (!locked) {
  15025. ao2_lock(peer);
  15026. }
  15027. peer->lastmsgssent = value;
  15028. if (!locked) {
  15029. ao2_unlock(peer);
  15030. }
  15031. }
  15032. /*!
  15033. * \brief Verify registration of user
  15034. *
  15035. * \details
  15036. * - Registration is done in several steps, first a REGISTER without auth
  15037. * to get a challenge (nonce) then a second one with auth
  15038. * - Registration requests are only matched with peers that are marked as "dynamic"
  15039. */
  15040. static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
  15041. struct sip_request *req, const char *uri)
  15042. {
  15043. enum check_auth_result res = AUTH_NOT_FOUND;
  15044. struct sip_peer *peer;
  15045. char tmp[256];
  15046. char *c, *name, *unused_password, *domain;
  15047. char *uri2 = ast_strdupa(uri);
  15048. int send_mwi = 0;
  15049. terminate_uri(uri2);
  15050. ast_copy_string(tmp, sip_get_header(req, "To"), sizeof(tmp));
  15051. c = get_in_brackets(tmp);
  15052. c = remove_uri_parameters(c);
  15053. if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
  15054. ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
  15055. return -1;
  15056. }
  15057. SIP_PEDANTIC_DECODE(name);
  15058. SIP_PEDANTIC_DECODE(domain);
  15059. extract_host_from_hostport(&domain);
  15060. if (ast_strlen_zero(domain)) {
  15061. /* <sip:name@[EMPTY]>, never good */
  15062. transmit_response(p, "404 Not found", &p->initreq);
  15063. return AUTH_UNKNOWN_DOMAIN;
  15064. }
  15065. if (ast_strlen_zero(name)) {
  15066. /* <sip:[EMPTY][@]hostport>, unsure whether valid for
  15067. * registration. RFC 3261, 10.2 states:
  15068. * "The To header field and the Request-URI field typically
  15069. * differ, as the former contains a user name."
  15070. * But, Asterisk has always treated the domain-only uri as a
  15071. * username: we allow admins to create accounts described by
  15072. * domain name. */
  15073. name = domain;
  15074. }
  15075. /* This here differs from 1.4 and 1.6: the domain matching ACLs were
  15076. * skipped if it was a domain-only URI (used as username). Here we treat
  15077. * <sip:hostport> as <sip:host@hostport> and won't forget to test the
  15078. * domain ACLs against host. */
  15079. if (!AST_LIST_EMPTY(&domain_list)) {
  15080. if (!check_sip_domain(domain, NULL, 0)) {
  15081. if (sip_cfg.alwaysauthreject) {
  15082. transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
  15083. } else {
  15084. transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
  15085. }
  15086. return AUTH_UNKNOWN_DOMAIN;
  15087. }
  15088. }
  15089. ast_string_field_set(p, exten, name);
  15090. build_contact(p, req, 1);
  15091. if (req->ignore) {
  15092. /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
  15093. const char *expires = sip_get_header(req, "Expires");
  15094. int expire = atoi(expires);
  15095. if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
  15096. if ((expires = strcasestr(sip_get_header(req, "Contact"), ";expires="))) {
  15097. expire = atoi(expires + 9);
  15098. }
  15099. }
  15100. if (!ast_strlen_zero(expires) && expire == 0) {
  15101. transmit_response_with_date(p, "200 OK", req);
  15102. return 0;
  15103. }
  15104. }
  15105. peer = sip_find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
  15106. /* If we don't want username disclosure, use the bogus_peer when a user
  15107. * is not found. */
  15108. if (!peer && sip_cfg.alwaysauthreject && sip_cfg.autocreatepeer == AUTOPEERS_DISABLED) {
  15109. peer = bogus_peer;
  15110. sip_ref_peer(peer, "register_verify: ref the bogus_peer");
  15111. }
  15112. if (!(peer && ast_apply_acl(peer->acl, addr, "SIP Peer ACL: "))) {
  15113. /* Peer fails ACL check */
  15114. if (peer) {
  15115. sip_unref_peer(peer, "register_verify: sip_unref_peer: from sip_find_peer operation");
  15116. peer = NULL;
  15117. res = AUTH_ACL_FAILED;
  15118. } else {
  15119. res = AUTH_NOT_FOUND;
  15120. }
  15121. }
  15122. if (peer) {
  15123. ao2_lock(peer);
  15124. if (!peer->host_dynamic) {
  15125. ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
  15126. res = AUTH_PEER_NOT_DYNAMIC;
  15127. } else {
  15128. set_peer_nat(p, peer);
  15129. ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
  15130. if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE))) {
  15131. if (sip_cancel_destroy(p))
  15132. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  15133. if (check_request_transport(peer, req)) {
  15134. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  15135. transmit_response_with_date(p, "403 Forbidden", req);
  15136. res = AUTH_BAD_TRANSPORT;
  15137. } else {
  15138. /* We have a successful registration attempt with proper authentication,
  15139. now, update the peer */
  15140. switch (parse_register_contact(p, peer, req)) {
  15141. case PARSE_REGISTER_DENIED:
  15142. ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
  15143. transmit_response_with_date(p, "603 Denied", req);
  15144. res = 0;
  15145. break;
  15146. case PARSE_REGISTER_FAILED:
  15147. ast_log(LOG_WARNING, "Failed to parse contact info\n");
  15148. transmit_response_with_date(p, "400 Bad Request", req);
  15149. res = 0;
  15150. break;
  15151. case PARSE_REGISTER_QUERY:
  15152. ast_string_field_set(p, fullcontact, peer->fullcontact);
  15153. transmit_response_with_date(p, "200 OK", req);
  15154. res = 0;
  15155. send_mwi = 1;
  15156. break;
  15157. case PARSE_REGISTER_UPDATE:
  15158. ast_string_field_set(p, fullcontact, peer->fullcontact);
  15159. /* If expiry is 0, peer has been unregistered already */
  15160. if (p->expiry != 0) {
  15161. update_peer(peer, p->expiry);
  15162. }
  15163. /* Say OK and ask subsystem to retransmit msg counter */
  15164. transmit_response_with_date(p, "200 OK", req);
  15165. send_mwi = 1;
  15166. res = 0;
  15167. break;
  15168. }
  15169. }
  15170. }
  15171. }
  15172. ao2_unlock(peer);
  15173. }
  15174. if (!peer && sip_cfg.autocreatepeer != AUTOPEERS_DISABLED) {
  15175. /* Create peer if we have autocreate mode enabled */
  15176. peer = temp_peer(name);
  15177. if (peer) {
  15178. ao2_t_link(peers, peer, "link peer into peer table");
  15179. if (!ast_sockaddr_isnull(&peer->addr)) {
  15180. ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
  15181. }
  15182. ao2_lock(peer);
  15183. if (sip_cancel_destroy(p))
  15184. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  15185. switch (parse_register_contact(p, peer, req)) {
  15186. case PARSE_REGISTER_DENIED:
  15187. ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
  15188. transmit_response_with_date(p, "403 Forbidden", req);
  15189. res = 0;
  15190. break;
  15191. case PARSE_REGISTER_FAILED:
  15192. ast_log(LOG_WARNING, "Failed to parse contact info\n");
  15193. transmit_response_with_date(p, "400 Bad Request", req);
  15194. res = 0;
  15195. break;
  15196. case PARSE_REGISTER_QUERY:
  15197. ast_string_field_set(p, fullcontact, peer->fullcontact);
  15198. transmit_response_with_date(p, "200 OK", req);
  15199. send_mwi = 1;
  15200. res = 0;
  15201. break;
  15202. case PARSE_REGISTER_UPDATE:
  15203. ast_string_field_set(p, fullcontact, peer->fullcontact);
  15204. /* Say OK and ask subsystem to retransmit msg counter */
  15205. transmit_response_with_date(p, "200 OK", req);
  15206. if (peer->endpoint) {
  15207. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  15208. ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_ONLINE);
  15209. blob = ast_json_pack("{s: s, s: s}",
  15210. "peer_status", "Registered",
  15211. "address", ast_sockaddr_stringify(addr));
  15212. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  15213. }
  15214. send_mwi = 1;
  15215. res = 0;
  15216. break;
  15217. }
  15218. ao2_unlock(peer);
  15219. }
  15220. }
  15221. if (!res) {
  15222. if (send_mwi) {
  15223. sip_pvt_unlock(p);
  15224. sip_send_mwi_to_peer(peer, 0);
  15225. sip_pvt_lock(p);
  15226. } else {
  15227. update_peer_lastmsgssent(peer, -1, 0);
  15228. }
  15229. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  15230. }
  15231. if (res < 0) {
  15232. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  15233. switch (res) {
  15234. case AUTH_SECRET_FAILED:
  15235. /* Wrong password in authentication. Go away, don't try again until you fixed it */
  15236. transmit_response(p, "403 Forbidden", &p->initreq);
  15237. if (global_authfailureevents) {
  15238. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  15239. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  15240. blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
  15241. "peer_status", "Rejected",
  15242. "cause", "AUTH_SECRET_FAILED",
  15243. "address", peer_addr,
  15244. "port", peer_port);
  15245. }
  15246. break;
  15247. case AUTH_USERNAME_MISMATCH:
  15248. /* Username and digest username does not match.
  15249. Asterisk uses the From: username for authentication. We need the
  15250. devices to use the same authentication user name until we support
  15251. proper authentication by digest auth name */
  15252. case AUTH_NOT_FOUND:
  15253. case AUTH_PEER_NOT_DYNAMIC:
  15254. case AUTH_ACL_FAILED:
  15255. if (sip_cfg.alwaysauthreject) {
  15256. transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
  15257. if (global_authfailureevents) {
  15258. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  15259. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  15260. blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
  15261. "peer_status", "Rejected",
  15262. "cause", res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
  15263. "address", peer_addr,
  15264. "port", peer_port);
  15265. }
  15266. } else {
  15267. /* URI not found */
  15268. if (res == AUTH_PEER_NOT_DYNAMIC) {
  15269. transmit_response(p, "403 Forbidden", &p->initreq);
  15270. if (global_authfailureevents) {
  15271. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  15272. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  15273. blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
  15274. "peer_status", "Rejected",
  15275. "cause", "AUTH_PEER_NOT_DYNAMIC",
  15276. "address", peer_addr,
  15277. "port", peer_port);
  15278. }
  15279. } else {
  15280. transmit_response(p, "404 Not found", &p->initreq);
  15281. if (global_authfailureevents) {
  15282. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  15283. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  15284. blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
  15285. "peer_status", "Rejected",
  15286. "cause", (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
  15287. "address", peer_addr,
  15288. "port", peer_port);
  15289. }
  15290. }
  15291. }
  15292. break;
  15293. case AUTH_BAD_TRANSPORT:
  15294. default:
  15295. break;
  15296. }
  15297. if (peer && peer->endpoint) {
  15298. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  15299. }
  15300. }
  15301. if (peer) {
  15302. sip_unref_peer(peer, "register_verify: sip_unref_peer: tossing stack peer pointer at end of func");
  15303. }
  15304. return res;
  15305. }
  15306. /*! \brief Translate referring cause */
  15307. static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
  15308. if (!strcmp(reason, "unknown")) {
  15309. ast_string_field_set(p, redircause, "UNKNOWN");
  15310. } else if (!strcmp(reason, "user-busy")) {
  15311. ast_string_field_set(p, redircause, "BUSY");
  15312. } else if (!strcmp(reason, "no-answer")) {
  15313. ast_string_field_set(p, redircause, "NOANSWER");
  15314. } else if (!strcmp(reason, "unavailable")) {
  15315. ast_string_field_set(p, redircause, "UNREACHABLE");
  15316. } else if (!strcmp(reason, "unconditional")) {
  15317. ast_string_field_set(p, redircause, "UNCONDITIONAL");
  15318. } else if (!strcmp(reason, "time-of-day")) {
  15319. ast_string_field_set(p, redircause, "UNKNOWN");
  15320. } else if (!strcmp(reason, "do-not-disturb")) {
  15321. ast_string_field_set(p, redircause, "UNKNOWN");
  15322. } else if (!strcmp(reason, "deflection")) {
  15323. ast_string_field_set(p, redircause, "UNKNOWN");
  15324. } else if (!strcmp(reason, "follow-me")) {
  15325. ast_string_field_set(p, redircause, "UNKNOWN");
  15326. } else if (!strcmp(reason, "out-of-service")) {
  15327. ast_string_field_set(p, redircause, "UNREACHABLE");
  15328. } else if (!strcmp(reason, "away")) {
  15329. ast_string_field_set(p, redircause, "UNREACHABLE");
  15330. } else {
  15331. ast_string_field_set(p, redircause, "UNKNOWN");
  15332. }
  15333. }
  15334. /*! \brief Parse the parts of the P-Asserted-Identity header
  15335. * on an incoming packet. Returns 1 if a valid header is found
  15336. * and it is different from the current caller id.
  15337. */
  15338. static int get_pai(struct sip_pvt *p, struct sip_request *req)
  15339. {
  15340. char pai[256];
  15341. char privacy[64];
  15342. char *cid_num = NULL;
  15343. char *cid_name = NULL;
  15344. char emptyname[1] = "";
  15345. int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  15346. char *uri = NULL;
  15347. int is_anonymous = 0, do_update = 1, no_name = 0;
  15348. ast_copy_string(pai, sip_get_header(req, "P-Asserted-Identity"), sizeof(pai));
  15349. if (ast_strlen_zero(pai)) {
  15350. return 0;
  15351. }
  15352. /* use the reqresp_parser function get_name_and_number*/
  15353. if (get_name_and_number(pai, &cid_name, &cid_num)) {
  15354. return 0;
  15355. }
  15356. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
  15357. ast_shrink_phone_number(cid_num);
  15358. }
  15359. uri = get_in_brackets(pai);
  15360. if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
  15361. callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  15362. /*XXX Assume no change in cid_num. Perhaps it should be
  15363. * blanked?
  15364. */
  15365. ast_free(cid_num);
  15366. is_anonymous = 1;
  15367. cid_num = (char *)p->cid_num;
  15368. }
  15369. ast_copy_string(privacy, sip_get_header(req, "Privacy"), sizeof(privacy));
  15370. if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
  15371. callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  15372. }
  15373. if (!cid_name) {
  15374. no_name = 1;
  15375. cid_name = (char *)emptyname;
  15376. }
  15377. /* Only return true if the supplied caller id is different */
  15378. if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
  15379. do_update = 0;
  15380. } else {
  15381. ast_string_field_set(p, cid_num, cid_num);
  15382. ast_string_field_set(p, cid_name, cid_name);
  15383. p->callingpres = callingpres;
  15384. if (p->owner) {
  15385. ast_set_callerid(p->owner, cid_num, cid_name, NULL);
  15386. ast_channel_caller(p->owner)->id.name.presentation = callingpres;
  15387. ast_channel_caller(p->owner)->id.number.presentation = callingpres;
  15388. }
  15389. }
  15390. /* get_name_and_number allocates memory for cid_num and cid_name so we have to free it */
  15391. if (!is_anonymous) {
  15392. ast_free(cid_num);
  15393. }
  15394. if (!no_name) {
  15395. ast_free(cid_name);
  15396. }
  15397. return do_update;
  15398. }
  15399. /*! \brief Get name, number and presentation from remote party id header,
  15400. * returns true if a valid header was found and it was different from the
  15401. * current caller id.
  15402. */
  15403. static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
  15404. {
  15405. char tmp[256];
  15406. struct sip_request *req;
  15407. char *cid_num = "";
  15408. char *cid_name = "";
  15409. int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  15410. char *privacy = "";
  15411. char *screen = "";
  15412. char *start, *end;
  15413. if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
  15414. return 0;
  15415. req = oreq;
  15416. if (!req)
  15417. req = &p->initreq;
  15418. ast_copy_string(tmp, sip_get_header(req, "Remote-Party-ID"), sizeof(tmp));
  15419. if (ast_strlen_zero(tmp)) {
  15420. return get_pai(p, req);
  15421. }
  15422. /*
  15423. * RPID is not:
  15424. * rpid = (name-addr / addr-spec) *(SEMI rpi-token)
  15425. * But it is:
  15426. * rpid = [display-name] LAQUOT addr-spec RAQUOT *(SEMI rpi-token)
  15427. * Ergo, calling parse_name_andor_addr() on it wouldn't be
  15428. * correct because that would allow addr-spec style too.
  15429. */
  15430. start = tmp;
  15431. /* Quoted (note that we're not dealing with escapes properly) */
  15432. if (*start == '"') {
  15433. *start++ = '\0';
  15434. end = strchr(start, '"');
  15435. if (!end)
  15436. return 0;
  15437. *end++ = '\0';
  15438. cid_name = start;
  15439. start = ast_skip_blanks(end);
  15440. /* Unquoted */
  15441. } else {
  15442. cid_name = start;
  15443. start = end = strchr(start, '<');
  15444. if (!start) {
  15445. return 0;
  15446. }
  15447. /* trim blanks if there are any. the mandatory NUL is done below */
  15448. while (--end >= cid_name && *end < 33) {
  15449. *end = '\0';
  15450. }
  15451. }
  15452. if (*start != '<')
  15453. return 0;
  15454. *start++ = '\0';
  15455. end = strchr(start, '@');
  15456. if (!end)
  15457. return 0;
  15458. *end++ = '\0';
  15459. if (strncasecmp(start, "sip:", 4))
  15460. return 0;
  15461. cid_num = start + 4;
  15462. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
  15463. ast_shrink_phone_number(cid_num);
  15464. start = end;
  15465. end = strchr(start, '>');
  15466. if (!end)
  15467. return 0;
  15468. *end++ = '\0';
  15469. if (*end) {
  15470. start = end;
  15471. if (*start != ';')
  15472. return 0;
  15473. *start++ = '\0';
  15474. while (!ast_strlen_zero(start)) {
  15475. end = strchr(start, ';');
  15476. if (end)
  15477. *end++ = '\0';
  15478. if (!strncasecmp(start, "privacy=", 8))
  15479. privacy = start + 8;
  15480. else if (!strncasecmp(start, "screen=", 7))
  15481. screen = start + 7;
  15482. start = end;
  15483. }
  15484. if (!strcasecmp(privacy, "full")) {
  15485. if (!strcasecmp(screen, "yes"))
  15486. callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
  15487. else if (!strcasecmp(screen, "no"))
  15488. callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  15489. } else {
  15490. if (!strcasecmp(screen, "yes"))
  15491. callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
  15492. else if (!strcasecmp(screen, "no"))
  15493. callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  15494. }
  15495. }
  15496. /* Only return true if the supplied caller id is different */
  15497. if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
  15498. return 0;
  15499. ast_string_field_set(p, cid_num, cid_num);
  15500. ast_string_field_set(p, cid_name, cid_name);
  15501. p->callingpres = callingpres;
  15502. if (p->owner) {
  15503. ast_set_callerid(p->owner, cid_num, cid_name, NULL);
  15504. ast_channel_caller(p->owner)->id.name.presentation = callingpres;
  15505. ast_channel_caller(p->owner)->id.number.presentation = callingpres;
  15506. }
  15507. return 1;
  15508. }
  15509. /*! \brief Get referring dnis
  15510. *
  15511. * \param p dialog information
  15512. * \param oreq The request to retrieve RDNIS from
  15513. * \param[out] name The name of the party redirecting the call.
  15514. * \param[out] number The number of the party redirecting the call.
  15515. * \param[out] reason_code The numerical code corresponding to the reason for the redirection.
  15516. * \param[out] reason_str A string describing the reason for redirection. Will never be zero-length
  15517. *
  15518. * \retval -1 Could not retrieve RDNIS information
  15519. * \retval 0 RDNIS successfully retrieved
  15520. */
  15521. static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason_code, char **reason_str)
  15522. {
  15523. char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
  15524. char *params, *reason_param = NULL;
  15525. struct sip_request *req;
  15526. req = oreq ? oreq : &p->initreq;
  15527. ast_copy_string(tmp, sip_get_header(req, "Diversion"), sizeof(tmp));
  15528. if (ast_strlen_zero(tmp))
  15529. return -1;
  15530. if ((params = strchr(tmp, '>'))) {
  15531. params = strchr(params, ';');
  15532. }
  15533. exten = get_in_brackets(tmp);
  15534. if (!strncasecmp(exten, "sip:", 4)) {
  15535. exten += 4;
  15536. } else if (!strncasecmp(exten, "sips:", 5)) {
  15537. exten += 5;
  15538. } else {
  15539. ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
  15540. return -1;
  15541. }
  15542. /* Get diversion-reason param if present */
  15543. if (params) {
  15544. *params = '\0'; /* Cut off parameters */
  15545. params++;
  15546. while (*params == ';' || *params == ' ')
  15547. params++;
  15548. /* Check if we have a reason parameter */
  15549. if ((reason_param = strcasestr(params, "reason="))) {
  15550. char *end;
  15551. reason_param+=7;
  15552. if ((end = strchr(reason_param, ';'))) {
  15553. *end = '\0';
  15554. }
  15555. /* Remove enclosing double-quotes */
  15556. if (*reason_param == '"')
  15557. reason_param = ast_strip_quoted(reason_param, "\"", "\"");
  15558. if (!ast_strlen_zero(reason_param)) {
  15559. sip_set_redirstr(p, reason_param);
  15560. if (p->owner) {
  15561. pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
  15562. pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
  15563. }
  15564. }
  15565. }
  15566. }
  15567. rdomain = exten;
  15568. rexten = strsep(&rdomain, "@"); /* trim anything after @ */
  15569. if (p->owner)
  15570. pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
  15571. if (sip_debug_test_pvt(p)) {
  15572. ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
  15573. }
  15574. /*ast_string_field_set(p, rdnis, rexten);*/
  15575. if (*tmp == '\"') {
  15576. char *end_quote;
  15577. rname = tmp + 1;
  15578. end_quote = strchr(rname, '\"');
  15579. if (end_quote) {
  15580. *end_quote = '\0';
  15581. }
  15582. }
  15583. if (number) {
  15584. *number = ast_strdup(rexten);
  15585. }
  15586. if (name && rname) {
  15587. *name = ast_strdup(rname);
  15588. }
  15589. if (!ast_strlen_zero(reason_param)) {
  15590. if (reason_code) {
  15591. *reason_code = sip_reason_str_to_code(reason_param);
  15592. }
  15593. if (reason_str) {
  15594. *reason_str = ast_strdup(reason_param);
  15595. }
  15596. }
  15597. return 0;
  15598. }
  15599. /*!
  15600. * \brief Find out who the call is for.
  15601. *
  15602. * \details
  15603. * We use the request uri as a destination.
  15604. * This code assumes authentication has been done, so that the
  15605. * device (peer/user) context is already set.
  15606. *
  15607. * \return 0 on success (found a matching extension), non-zero on failure
  15608. *
  15609. * \note If the incoming uri is a SIPS: uri, we are required to carry this across
  15610. * the dialplan, so that the outbound call also is a sips: call or encrypted
  15611. * IAX2 call. If that's not available, the call should FAIL.
  15612. */
  15613. static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
  15614. {
  15615. char tmp[256] = "", *uri, *unused_password, *domain;
  15616. RAII_VAR(char *, tmpf, NULL, ast_free);
  15617. char *from = NULL;
  15618. struct sip_request *req;
  15619. char *decoded_uri;
  15620. RAII_VAR(struct ast_features_pickup_config *, pickup_cfg, ast_get_chan_features_pickup_config(p->owner), ao2_cleanup);
  15621. const char *pickupexten;
  15622. if (!pickup_cfg) {
  15623. ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
  15624. pickupexten = "";
  15625. } else {
  15626. /* Don't need to duplicate since channel is locked for the duration of this function */
  15627. pickupexten = pickup_cfg->pickupexten;
  15628. }
  15629. req = oreq;
  15630. if (!req) {
  15631. req = &p->initreq;
  15632. }
  15633. /* Find the request URI */
  15634. if (req->rlpart2) {
  15635. ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlpart2), sizeof(tmp));
  15636. }
  15637. uri = ast_strdupa(get_in_brackets(tmp));
  15638. if (parse_uri_legacy_check(uri, "sip:,sips:,tel:", &uri, &unused_password, &domain, NULL)) {
  15639. ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
  15640. return SIP_GET_DEST_INVALID_URI;
  15641. }
  15642. SIP_PEDANTIC_DECODE(domain);
  15643. SIP_PEDANTIC_DECODE(uri);
  15644. extract_host_from_hostport(&domain);
  15645. if (strncasecmp(get_in_brackets(tmp), "tel:", 4)) {
  15646. ast_string_field_set(p, domain, domain);
  15647. } else {
  15648. ast_string_field_set(p, tel_phone_context, domain);
  15649. }
  15650. if (ast_strlen_zero(uri)) {
  15651. /*
  15652. * Either there really was no extension found or the request
  15653. * URI had encoded nulls that made the string "empty". Use "s"
  15654. * as the extension.
  15655. */
  15656. uri = "s";
  15657. }
  15658. /* Now find the From: caller ID and name */
  15659. /* XXX Why is this done in get_destination? Isn't it already done?
  15660. Needs to be checked
  15661. */
  15662. tmpf = ast_strdup(sip_get_header(req, "From"));
  15663. if (!ast_strlen_zero(tmpf)) {
  15664. from = get_in_brackets(tmpf);
  15665. if (parse_uri_legacy_check(from, "sip:,sips:,tel:", &from, NULL, &domain, NULL)) {
  15666. ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
  15667. return SIP_GET_DEST_INVALID_URI;
  15668. }
  15669. SIP_PEDANTIC_DECODE(from);
  15670. SIP_PEDANTIC_DECODE(domain);
  15671. extract_host_from_hostport(&domain);
  15672. ast_string_field_set(p, fromdomain, domain);
  15673. }
  15674. if (!AST_LIST_EMPTY(&domain_list)) {
  15675. char domain_context[AST_MAX_EXTENSION];
  15676. domain_context[0] = '\0';
  15677. if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
  15678. if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
  15679. ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
  15680. return SIP_GET_DEST_REFUSED;
  15681. }
  15682. }
  15683. /* If we don't have a peer (i.e. we're a guest call),
  15684. * overwrite the original context */
  15685. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
  15686. ast_string_field_set(p, context, domain_context);
  15687. }
  15688. }
  15689. /* If the request coming in is a subscription and subscribecontext has been specified use it */
  15690. if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
  15691. ast_string_field_set(p, context, p->subscribecontext);
  15692. }
  15693. if (sip_debug_test_pvt(p)) {
  15694. ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
  15695. }
  15696. /* Since extensions.conf can have unescaped characters, try matching a
  15697. * decoded uri in addition to the non-decoded uri. */
  15698. decoded_uri = ast_strdupa(uri);
  15699. ast_uri_decode(decoded_uri, ast_uri_sip_user);
  15700. /* If this is a subscription we actually just need to see if a hint exists for the extension */
  15701. if (req->method == SIP_SUBSCRIBE) {
  15702. char hint[AST_MAX_EXTENSION];
  15703. int which = 0;
  15704. if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
  15705. (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
  15706. if (!oreq) {
  15707. ast_string_field_set(p, exten, which ? decoded_uri : uri);
  15708. }
  15709. return SIP_GET_DEST_EXTEN_FOUND;
  15710. } else {
  15711. return SIP_GET_DEST_EXTEN_NOT_FOUND;
  15712. }
  15713. } else {
  15714. struct ast_cc_agent *agent;
  15715. /* Check the dialplan for the username part of the request URI,
  15716. the domain will be stored in the SIPDOMAIN variable
  15717. Return 0 if we have a matching extension */
  15718. if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
  15719. if (!oreq) {
  15720. ast_string_field_set(p, exten, uri);
  15721. }
  15722. return SIP_GET_DEST_EXTEN_FOUND;
  15723. }
  15724. if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
  15725. || !strcmp(decoded_uri, pickupexten)) {
  15726. if (!oreq) {
  15727. ast_string_field_set(p, exten, decoded_uri);
  15728. }
  15729. return SIP_GET_DEST_EXTEN_FOUND;
  15730. }
  15731. if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
  15732. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  15733. /* This is a CC recall. We can set p's extension to the exten from
  15734. * the original INVITE
  15735. */
  15736. ast_string_field_set(p, exten, agent_pvt->original_exten);
  15737. /* And we need to let the CC core know that the caller is attempting
  15738. * his recall
  15739. */
  15740. ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
  15741. agent->device_name);
  15742. if (cc_recall_core_id) {
  15743. *cc_recall_core_id = agent->core_id;
  15744. }
  15745. ao2_ref(agent, -1);
  15746. return SIP_GET_DEST_EXTEN_FOUND;
  15747. }
  15748. }
  15749. if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
  15750. && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
  15751. || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
  15752. || !strncmp(decoded_uri, pickupexten, strlen(decoded_uri)))) {
  15753. /* Overlap dialing is enabled and we need more digits to match an extension. */
  15754. return SIP_GET_DEST_EXTEN_MATCHMORE;
  15755. }
  15756. return SIP_GET_DEST_EXTEN_NOT_FOUND;
  15757. }
  15758. /*! \brief Find a companion dialog based on Replaces information
  15759. *
  15760. * This information may come from a Refer-To header in a REFER or from
  15761. * a Replaces header in an INVITE.
  15762. *
  15763. * This function will find the appropriate sip_pvt and increment the refcount
  15764. * of both the sip_pvt and its owner channel. These two references are returned
  15765. * in the out parameters
  15766. *
  15767. * \param callid Callid to search for
  15768. * \param totag to-tag parameter from Replaces
  15769. * \param fromtag from-tag parameter from Replaces
  15770. * \param[out] out_pvt The found sip_pvt.
  15771. * \param[out] out_chan The found sip_pvt's owner channel.
  15772. * \retval 0 Success
  15773. * \retval non-zero Failure
  15774. */
  15775. static int get_sip_pvt_from_replaces(const char *callid, const char *totag,
  15776. const char *fromtag, struct sip_pvt **out_pvt, struct ast_channel **out_chan)
  15777. {
  15778. struct sip_pvt *sip_pvt_ptr;
  15779. struct sip_pvt tmp_dialog = {
  15780. .callid = callid,
  15781. };
  15782. if (totag) {
  15783. ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
  15784. }
  15785. /* Search dialogs and find the match */
  15786. sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
  15787. if (sip_pvt_ptr) {
  15788. /* Go ahead and lock it (and its owner) before returning */
  15789. SCOPED_LOCK(lock, sip_pvt_ptr, sip_pvt_lock, sip_pvt_unlock);
  15790. if (sip_cfg.pedanticsipchecking) {
  15791. unsigned char frommismatch = 0, tomismatch = 0;
  15792. if (ast_strlen_zero(fromtag)) {
  15793. ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
  15794. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
  15795. return -1;
  15796. }
  15797. if (ast_strlen_zero(totag)) {
  15798. ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
  15799. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
  15800. return -1;
  15801. }
  15802. /* RFC 3891
  15803. * > 3. User Agent Server Behavior: Receiving a Replaces Header
  15804. * > The Replaces header contains information used to match an existing
  15805. * > SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE
  15806. * > with a Replaces header, the User Agent (UA) attempts to match this
  15807. * > information with a confirmed or early dialog. The User Agent Server
  15808. * > (UAS) matches the to-tag and from-tag parameters as if they were tags
  15809. * > present in an incoming request. In other words, the to-tag parameter
  15810. * > is compared to the local tag, and the from-tag parameter is compared
  15811. * > to the remote tag.
  15812. *
  15813. * Thus, the totag is always compared to the local tag, regardless if
  15814. * this our call is an incoming or outgoing call.
  15815. */
  15816. frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
  15817. tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
  15818. /* Don't check from if the dialog is not established, due to multi forking the from
  15819. * can change when the call is not answered yet.
  15820. */
  15821. if ((frommismatch && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) || tomismatch) {
  15822. if (frommismatch) {
  15823. ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
  15824. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
  15825. fromtag, sip_pvt_ptr->theirtag);
  15826. }
  15827. if (tomismatch) {
  15828. ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
  15829. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
  15830. totag, sip_pvt_ptr->tag);
  15831. }
  15832. return -1;
  15833. }
  15834. }
  15835. if (totag)
  15836. ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
  15837. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
  15838. sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
  15839. *out_pvt = sip_pvt_ptr;
  15840. if (out_chan) {
  15841. *out_chan = sip_pvt_ptr->owner ? ast_channel_ref(sip_pvt_ptr->owner) : NULL;
  15842. }
  15843. }
  15844. return 0;
  15845. }
  15846. /*! \brief Call transfer support (the REFER method)
  15847. * Extracts Refer headers into pvt dialog structure
  15848. *
  15849. * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
  15850. * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
  15851. * flag.
  15852. */
  15853. static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
  15854. {
  15855. const char *p_referred_by = NULL;
  15856. char *h_refer_to = NULL;
  15857. char *h_referred_by = NULL;
  15858. char *refer_to;
  15859. const char *p_refer_to;
  15860. char *referred_by_uri = NULL;
  15861. char *ptr;
  15862. struct sip_request *req = NULL;
  15863. const char *transfer_context = NULL;
  15864. struct sip_refer *refer;
  15865. req = outgoing_req;
  15866. refer = transferer->refer;
  15867. if (!req) {
  15868. req = &transferer->initreq;
  15869. }
  15870. p_refer_to = sip_get_header(req, "Refer-To");
  15871. if (ast_strlen_zero(p_refer_to)) {
  15872. ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
  15873. return -2; /* Syntax error */
  15874. }
  15875. h_refer_to = ast_strdupa(p_refer_to);
  15876. refer_to = get_in_brackets(h_refer_to);
  15877. if (!strncasecmp(refer_to, "sip:", 4)) {
  15878. refer_to += 4; /* Skip sip: */
  15879. } else if (!strncasecmp(refer_to, "sips:", 5)) {
  15880. refer_to += 5;
  15881. } else {
  15882. ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
  15883. return -3;
  15884. }
  15885. /* Get referred by header if it exists */
  15886. p_referred_by = sip_get_header(req, "Referred-By");
  15887. /* Give useful transfer information to the dialplan */
  15888. if (transferer->owner) {
  15889. RAII_VAR(struct ast_channel *, peer, NULL, ast_channel_cleanup);
  15890. RAII_VAR(struct ast_channel *, owner_relock, NULL, ast_channel_cleanup);
  15891. RAII_VAR(struct ast_channel *, owner_ref, NULL, ast_channel_cleanup);
  15892. /* Grab a reference to transferer->owner to prevent it from going away */
  15893. owner_ref = ast_channel_ref(transferer->owner);
  15894. /* Established locking order here is bridge, channel, pvt
  15895. * and the bridge will be locked during ast_channel_bridge_peer */
  15896. ast_channel_unlock(owner_ref);
  15897. sip_pvt_unlock(transferer);
  15898. peer = ast_channel_bridge_peer(owner_ref);
  15899. if (peer) {
  15900. pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT",
  15901. S_OR(transferer->context, NULL));
  15902. pbx_builtin_setvar_helper(peer, "__SIPREFERREDBYHDR",
  15903. S_OR(p_referred_by, NULL));
  15904. ast_channel_unlock(peer);
  15905. }
  15906. owner_relock = sip_pvt_lock_full(transferer);
  15907. if (!owner_relock) {
  15908. ast_debug(3, "Unable to reacquire owner channel lock, channel is gone\n");
  15909. return -5;
  15910. }
  15911. }
  15912. if (!ast_strlen_zero(p_referred_by)) {
  15913. h_referred_by = ast_strdupa(p_referred_by);
  15914. referred_by_uri = get_in_brackets(h_referred_by);
  15915. if (!strncasecmp(referred_by_uri, "sip:", 4)) {
  15916. referred_by_uri += 4; /* Skip sip: */
  15917. } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
  15918. referred_by_uri += 5; /* Skip sips: */
  15919. } else {
  15920. ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
  15921. referred_by_uri = NULL;
  15922. }
  15923. }
  15924. /* Check for arguments in the refer_to header */
  15925. if ((ptr = strcasestr(refer_to, "replaces="))) {
  15926. char *to = NULL, *from = NULL, *callid;
  15927. /* This is an attended transfer */
  15928. refer->attendedtransfer = 1;
  15929. callid = ast_strdupa(ptr + 9);
  15930. ast_uri_decode(callid, ast_uri_sip_user);
  15931. if ((ptr = strchr(callid, ';'))) { /* Find options */
  15932. *ptr++ = '\0';
  15933. }
  15934. ast_string_field_set(refer, replaces_callid, callid);
  15935. if (ptr) {
  15936. /* Find the different tags before we destroy the string */
  15937. to = strcasestr(ptr, "to-tag=");
  15938. from = strcasestr(ptr, "from-tag=");
  15939. }
  15940. /* Grab the to header */
  15941. if (to) {
  15942. ptr = to + 7;
  15943. if ((to = strchr(ptr, '&'))) {
  15944. *to = '\0';
  15945. }
  15946. if ((to = strchr(ptr, ';'))) {
  15947. *to = '\0';
  15948. }
  15949. ast_string_field_set(refer, replaces_callid_totag, ptr);
  15950. }
  15951. if (from) {
  15952. ptr = from + 9;
  15953. if ((from = strchr(ptr, '&'))) {
  15954. *from = '\0';
  15955. }
  15956. if ((from = strchr(ptr, ';'))) {
  15957. *from = '\0';
  15958. }
  15959. ast_string_field_set(refer, replaces_callid_fromtag, ptr);
  15960. }
  15961. if (!strcmp(refer->replaces_callid, transferer->callid) &&
  15962. (!sip_cfg.pedanticsipchecking ||
  15963. (!strcmp(refer->replaces_callid_fromtag, transferer->theirtag) &&
  15964. !strcmp(refer->replaces_callid_totag, transferer->tag)))) {
  15965. ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
  15966. return -4;
  15967. }
  15968. if (!sip_cfg.pedanticsipchecking) {
  15969. ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", refer->replaces_callid);
  15970. } else {
  15971. ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", refer->replaces_callid, refer->replaces_callid_fromtag ? refer->replaces_callid_fromtag : "<none>", refer->replaces_callid_totag ? refer->replaces_callid_totag : "<none>");
  15972. }
  15973. }
  15974. if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
  15975. char *urioption = NULL, *domain;
  15976. int bracket = 0;
  15977. *ptr++ = '\0';
  15978. if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
  15979. *urioption++ = '\0';
  15980. }
  15981. domain = ptr;
  15982. /* Remove :port */
  15983. for (; *ptr != '\0'; ++ptr) {
  15984. if (*ptr == ':' && bracket == 0) {
  15985. *ptr = '\0';
  15986. break;
  15987. } else if (*ptr == '[') {
  15988. ++bracket;
  15989. } else if (*ptr == ']') {
  15990. --bracket;
  15991. }
  15992. }
  15993. SIP_PEDANTIC_DECODE(domain);
  15994. SIP_PEDANTIC_DECODE(urioption);
  15995. /* Save the domain for the dial plan */
  15996. ast_string_field_set(refer, refer_to_domain, domain);
  15997. if (urioption) {
  15998. ast_string_field_set(refer, refer_to_urioption, urioption);
  15999. }
  16000. }
  16001. if ((ptr = strchr(refer_to, ';'))) /* Remove options */
  16002. *ptr = '\0';
  16003. SIP_PEDANTIC_DECODE(refer_to);
  16004. ast_string_field_set(refer, refer_to, refer_to);
  16005. if (referred_by_uri) {
  16006. if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
  16007. *ptr = '\0';
  16008. SIP_PEDANTIC_DECODE(referred_by_uri);
  16009. ast_string_field_build(refer, referred_by, "<sip:%s>", referred_by_uri);
  16010. } else {
  16011. ast_string_field_set(refer, referred_by, "");
  16012. }
  16013. /* Determine transfer context */
  16014. if (transferer->owner) {
  16015. /* By default, use the context in the channel sending the REFER */
  16016. transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
  16017. if (ast_strlen_zero(transfer_context)) {
  16018. transfer_context = ast_channel_macrocontext(transferer->owner);
  16019. }
  16020. }
  16021. if (ast_strlen_zero(transfer_context)) {
  16022. transfer_context = S_OR(transferer->context, sip_cfg.default_context);
  16023. }
  16024. ast_string_field_set(refer, refer_to_context, transfer_context);
  16025. /* Either an existing extension or the parking extension */
  16026. if (refer->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL)) {
  16027. if (sip_debug_test_pvt(transferer)) {
  16028. ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, S_OR(referred_by_uri, "Unknown"));
  16029. }
  16030. /* We are ready to transfer to the extension */
  16031. return 0;
  16032. }
  16033. if (sip_debug_test_pvt(transferer))
  16034. ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
  16035. /* Failure, we can't find this extension */
  16036. return -1;
  16037. }
  16038. /*! \brief Call transfer support (old way, deprecated by the IETF)
  16039. * \note does not account for SIPS: uri requirements, nor check transport
  16040. */
  16041. static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
  16042. {
  16043. char tmp[256] = "", *c, *a;
  16044. struct sip_request *req = oreq ? oreq : &p->initreq;
  16045. struct sip_refer *refer = NULL;
  16046. const char *transfer_context = NULL;
  16047. if (!sip_refer_alloc(p)) {
  16048. return -1;
  16049. }
  16050. refer = p->refer;
  16051. ast_copy_string(tmp, sip_get_header(req, "Also"), sizeof(tmp));
  16052. c = get_in_brackets(tmp);
  16053. if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
  16054. ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
  16055. return -1;
  16056. }
  16057. SIP_PEDANTIC_DECODE(c);
  16058. SIP_PEDANTIC_DECODE(a);
  16059. if (!ast_strlen_zero(a)) {
  16060. ast_string_field_set(refer, refer_to_domain, a);
  16061. }
  16062. if (sip_debug_test_pvt(p))
  16063. ast_verbose("Looking for %s in %s\n", c, p->context);
  16064. /* Determine transfer context */
  16065. if (p->owner) {
  16066. /* By default, use the context in the channel sending the REFER */
  16067. transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
  16068. if (ast_strlen_zero(transfer_context)) {
  16069. transfer_context = ast_channel_macrocontext(p->owner);
  16070. }
  16071. }
  16072. if (ast_strlen_zero(transfer_context)) {
  16073. transfer_context = S_OR(p->context, sip_cfg.default_context);
  16074. }
  16075. if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
  16076. /* This is a blind transfer */
  16077. ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
  16078. ast_string_field_set(refer, refer_to, c);
  16079. ast_string_field_set(refer, referred_by, "");
  16080. ast_string_field_set(refer, refer_contact, "");
  16081. /* Set new context */
  16082. ast_string_field_set(p, context, transfer_context);
  16083. return 0;
  16084. } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
  16085. return 1;
  16086. }
  16087. return -1;
  16088. }
  16089. /*! \brief Set the peers nat flags if they are using auto_* settings */
  16090. static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer)
  16091. {
  16092. if (!p || !peer) {
  16093. return;
  16094. }
  16095. if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
  16096. if (p->natdetected) {
  16097. ast_set_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
  16098. } else {
  16099. ast_clear_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
  16100. }
  16101. }
  16102. if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
  16103. if (p->natdetected) {
  16104. ast_set_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
  16105. } else {
  16106. ast_clear_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
  16107. }
  16108. }
  16109. }
  16110. /*! \brief Check and see if the requesting UA is likely to be behind a NAT.
  16111. *
  16112. * If the requesting NAT is behind NAT, set the * natdetected flag so that
  16113. * later, peers with nat=auto_* can use the value. Also, set the flags so
  16114. * that Asterisk responds identically whether or not a peer exists so as
  16115. * not to leak peer name information.
  16116. */
  16117. static void check_for_nat(const struct ast_sockaddr *addr, struct sip_pvt *p)
  16118. {
  16119. if (!addr || !p) {
  16120. return;
  16121. }
  16122. if (ast_sockaddr_cmp_addr(addr, &p->recv)) {
  16123. char *tmp_str = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  16124. ast_debug(3, "NAT detected for %s / %s\n", tmp_str, ast_sockaddr_stringify_addr(&p->recv));
  16125. p->natdetected = 1;
  16126. if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
  16127. ast_set_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
  16128. }
  16129. if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
  16130. ast_set_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
  16131. }
  16132. } else {
  16133. p->natdetected = 0;
  16134. if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
  16135. ast_clear_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
  16136. }
  16137. if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
  16138. ast_clear_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
  16139. }
  16140. }
  16141. }
  16142. /*! \brief check Via: header for hostname, port and rport request/answer */
  16143. static void check_via(struct sip_pvt *p, const struct sip_request *req)
  16144. {
  16145. char via[512];
  16146. char *c, *maddr;
  16147. struct ast_sockaddr tmp = { { 0, } };
  16148. uint16_t port;
  16149. ast_copy_string(via, sip_get_header(req, "Via"), sizeof(via));
  16150. /* If this is via WebSocket we don't use the Via header contents at all */
  16151. if (!strncasecmp(via, "SIP/2.0/WS", 10)) {
  16152. return;
  16153. }
  16154. /* Work on the leftmost value of the topmost Via header */
  16155. c = strchr(via, ',');
  16156. if (c)
  16157. *c = '\0';
  16158. /* Check for rport */
  16159. c = strstr(via, ";rport");
  16160. if (c && (c[6] != '=')) { /* rport query, not answer */
  16161. ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
  16162. ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
  16163. }
  16164. /* Check for maddr */
  16165. maddr = strstr(via, "maddr=");
  16166. if (maddr) {
  16167. maddr += 6;
  16168. c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
  16169. "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
  16170. *c = '\0';
  16171. }
  16172. c = strchr(via, ';');
  16173. if (c)
  16174. *c = '\0';
  16175. c = strchr(via, ' ');
  16176. if (c) {
  16177. *c = '\0';
  16178. c = ast_skip_blanks(c+1);
  16179. if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
  16180. ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
  16181. return;
  16182. }
  16183. if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
  16184. p->sa = p->recv;
  16185. }
  16186. if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
  16187. ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
  16188. port = STANDARD_SIP_PORT;
  16189. } else if (!(port = ast_sockaddr_port(&tmp))) {
  16190. port = STANDARD_SIP_PORT;
  16191. ast_sockaddr_set_port(&tmp, port);
  16192. }
  16193. ast_sockaddr_set_port(&p->sa, port);
  16194. check_for_nat(&tmp, p);
  16195. if (sip_debug_test_pvt(p)) {
  16196. ast_verbose("Sending to %s (%s)\n",
  16197. ast_sockaddr_stringify(sip_real_dst(p)),
  16198. sip_nat_mode(p));
  16199. }
  16200. }
  16201. }
  16202. /*! \brief Validate device authentication */
  16203. static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
  16204. struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
  16205. struct sip_peer **authpeer,
  16206. enum xmittype reliable, char *calleridname, char *uri2)
  16207. {
  16208. enum check_auth_result res;
  16209. int debug = sip_debug_test_addr(addr);
  16210. struct sip_peer *peer;
  16211. if (sipmethod == SIP_SUBSCRIBE) {
  16212. /* For subscribes, match on device name only; for other methods,
  16213. * match on IP address-port of the incoming request.
  16214. */
  16215. peer = sip_find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
  16216. } else {
  16217. /* First find devices based on username (avoid all type=peer's) */
  16218. peer = sip_find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
  16219. /* Then find devices based on IP */
  16220. if (!peer) {
  16221. char *uri_tmp, *callback = NULL, *dummy;
  16222. uri_tmp = ast_strdupa(uri2);
  16223. parse_uri(uri_tmp, "sip:,sips:,tel:", &callback, &dummy, &dummy, &dummy);
  16224. if (!ast_strlen_zero(callback) && (peer = sip_find_peer_by_ip_and_exten(&p->recv, callback, p->socket.type))) {
  16225. ; /* found, fall through */
  16226. } else {
  16227. peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
  16228. }
  16229. }
  16230. }
  16231. if (!peer) {
  16232. if (debug) {
  16233. ast_verbose("No matching peer for '%s' from '%s'\n",
  16234. of, ast_sockaddr_stringify(&p->recv));
  16235. }
  16236. /* If you don't mind, we can return 404s for devices that do
  16237. * not exist: username disclosure. If we allow guests, there
  16238. * is no way around that. */
  16239. if (sip_cfg.allowguest || !sip_cfg.alwaysauthreject) {
  16240. return AUTH_DONT_KNOW;
  16241. }
  16242. /* If you do mind, we use a peer that will never authenticate.
  16243. * This ensures that we follow the same code path as regular
  16244. * auth: less chance for username disclosure. */
  16245. peer = bogus_peer;
  16246. sip_ref_peer(peer, "sip_ref_peer: check_peer_ok: must ref bogus_peer so unreffing it does not fail");
  16247. }
  16248. /* build_peer, called through sip_find_peer, is not able to check the
  16249. * sip_pvt->natdetected flag in order to determine if the peer is behind
  16250. * NAT or not when SIP_PAGE3_NAT_AUTO_RPORT or SIP_PAGE3_NAT_AUTO_COMEDIA
  16251. * are set on the peer. So we check for that here and set the peer's
  16252. * address accordingly.
  16253. */
  16254. set_peer_nat(p, peer);
  16255. if (p->natdetected && ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
  16256. ast_sockaddr_copy(&peer->addr, &p->recv);
  16257. }
  16258. if (!ast_apply_acl(peer->acl, addr, "SIP Peer ACL: ")) {
  16259. ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
  16260. sip_unref_peer(peer, "sip_unref_peer: check_peer_ok: from sip_find_peer call, early return of AUTH_ACL_FAILED");
  16261. return AUTH_ACL_FAILED;
  16262. }
  16263. if (debug && peer != bogus_peer) {
  16264. ast_verbose("Found peer '%s' for '%s' from %s\n",
  16265. peer->name, of, ast_sockaddr_stringify(&p->recv));
  16266. }
  16267. /* Set Frame packetization */
  16268. if (p->rtp) {
  16269. ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(p->rtp), ast_format_cap_get_framing(peer->caps));
  16270. p->autoframing = peer->autoframing;
  16271. }
  16272. /* Take the peer */
  16273. ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
  16274. ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  16275. ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  16276. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
  16277. p->t38_maxdatagram = peer->t38_maxdatagram;
  16278. set_t38_capabilities(p);
  16279. }
  16280. ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &p->dtls_cfg);
  16281. /* Copy SIP extensions profile to peer */
  16282. /* XXX is this correct before a successful auth ? */
  16283. if (p->sipoptions)
  16284. peer->sipoptions = p->sipoptions;
  16285. do_setnat(p);
  16286. ast_string_field_set(p, peersecret, peer->secret);
  16287. ast_string_field_set(p, peermd5secret, peer->md5secret);
  16288. ast_string_field_set(p, subscribecontext, peer->subscribecontext);
  16289. ast_string_field_set(p, mohinterpret, peer->mohinterpret);
  16290. ast_string_field_set(p, mohsuggest, peer->mohsuggest);
  16291. if (!ast_strlen_zero(peer->parkinglot)) {
  16292. ast_string_field_set(p, parkinglot, peer->parkinglot);
  16293. }
  16294. ast_string_field_set(p, engine, peer->engine);
  16295. p->disallowed_methods = peer->disallowed_methods;
  16296. set_pvt_allowed_methods(p, req);
  16297. ast_cc_copy_config_params(p->cc_params, peer->cc_params);
  16298. if (peer->callingpres) /* Peer calling pres setting will override RPID */
  16299. p->callingpres = peer->callingpres;
  16300. if (peer->maxms && peer->lastms)
  16301. p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
  16302. else
  16303. p->timer_t1 = peer->timer_t1;
  16304. /* Set timer B to control transaction timeouts */
  16305. if (peer->timer_b)
  16306. p->timer_b = peer->timer_b;
  16307. else
  16308. p->timer_b = 64 * p->timer_t1;
  16309. p->allowtransfer = peer->allowtransfer;
  16310. if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
  16311. /* Pretend there is no required authentication */
  16312. ast_string_field_set(p, peersecret, NULL);
  16313. ast_string_field_set(p, peermd5secret, NULL);
  16314. }
  16315. if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable))) {
  16316. /* If we have a call limit, set flag */
  16317. if (peer->call_limit)
  16318. ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
  16319. ast_string_field_set(p, peername, peer->name);
  16320. ast_string_field_set(p, authname, peer->name);
  16321. ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &p->dtls_cfg);
  16322. if (sipmethod == SIP_INVITE) {
  16323. /* destroy old channel vars and copy in new ones. */
  16324. ast_variables_destroy(p->chanvars);
  16325. p->chanvars = copy_vars(peer->chanvars);
  16326. }
  16327. if (authpeer) {
  16328. ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
  16329. (*authpeer) = peer; /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
  16330. }
  16331. if (!ast_strlen_zero(peer->username)) {
  16332. ast_string_field_set(p, username, peer->username);
  16333. /* Use the default username for authentication on outbound calls */
  16334. /* XXX this takes the name from the caller... can we override ? */
  16335. ast_string_field_set(p, authname, peer->username);
  16336. }
  16337. if (!get_rpid(p, req)) {
  16338. if (!ast_strlen_zero(peer->cid_num)) {
  16339. char *tmp = ast_strdupa(peer->cid_num);
  16340. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
  16341. ast_shrink_phone_number(tmp);
  16342. ast_string_field_set(p, cid_num, tmp);
  16343. }
  16344. if (!ast_strlen_zero(peer->cid_name))
  16345. ast_string_field_set(p, cid_name, peer->cid_name);
  16346. if (peer->callingpres)
  16347. p->callingpres = peer->callingpres;
  16348. }
  16349. if (!ast_strlen_zero(peer->cid_tag)) {
  16350. ast_string_field_set(p, cid_tag, peer->cid_tag);
  16351. }
  16352. ast_string_field_set(p, fullcontact, peer->fullcontact);
  16353. if (!ast_strlen_zero(peer->context)) {
  16354. ast_string_field_set(p, context, peer->context);
  16355. }
  16356. if (!ast_strlen_zero(peer->messagecontext)) {
  16357. ast_string_field_set(p, messagecontext, peer->messagecontext);
  16358. }
  16359. if (!ast_strlen_zero(peer->mwi_from)) {
  16360. ast_string_field_set(p, mwi_from, peer->mwi_from);
  16361. }
  16362. ast_string_field_set(p, peersecret, peer->secret);
  16363. ast_string_field_set(p, peermd5secret, peer->md5secret);
  16364. ast_string_field_set(p, language, peer->language);
  16365. ast_string_field_set(p, accountcode, peer->accountcode);
  16366. p->amaflags = peer->amaflags;
  16367. p->callgroup = peer->callgroup;
  16368. p->pickupgroup = peer->pickupgroup;
  16369. ast_unref_namedgroups(p->named_callgroups);
  16370. p->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);
  16371. ast_unref_namedgroups(p->named_pickupgroups);
  16372. p->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
  16373. ast_format_cap_remove_by_type(p->caps, AST_MEDIA_TYPE_UNKNOWN);
  16374. ast_format_cap_append_from_cap(p->caps, peer->caps, AST_MEDIA_TYPE_UNKNOWN);
  16375. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  16376. ast_format_cap_append_from_cap(p->jointcaps, peer->caps, AST_MEDIA_TYPE_UNKNOWN);
  16377. ast_copy_string(p->zone, peer->zone, sizeof(p->zone));
  16378. if (peer->maxforwards > 0) {
  16379. p->maxforwards = peer->maxforwards;
  16380. }
  16381. if (ast_format_cap_count(p->peercaps)) {
  16382. struct ast_format_cap *joint;
  16383. joint = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  16384. if (joint) {
  16385. ast_format_cap_get_compatible(p->jointcaps, p->peercaps, joint);
  16386. ao2_ref(p->jointcaps, -1);
  16387. p->jointcaps = joint;
  16388. }
  16389. }
  16390. p->maxcallbitrate = peer->maxcallbitrate;
  16391. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
  16392. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
  16393. p->noncodeccapability |= AST_RTP_DTMF;
  16394. else
  16395. p->noncodeccapability &= ~AST_RTP_DTMF;
  16396. p->jointnoncodeccapability = p->noncodeccapability;
  16397. p->rtptimeout = peer->rtptimeout;
  16398. p->rtpholdtimeout = peer->rtpholdtimeout;
  16399. p->rtpkeepalive = peer->rtpkeepalive;
  16400. if (!dialog_initialize_rtp(p)) {
  16401. if (p->rtp) {
  16402. ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(p->rtp), ast_format_cap_get_framing(peer->caps));
  16403. p->autoframing = peer->autoframing;
  16404. }
  16405. } else {
  16406. res = AUTH_RTP_FAILED;
  16407. }
  16408. }
  16409. sip_unref_peer(peer, "check_peer_ok: sip_unref_peer: tossing temp ptr to peer from sip_find_peer");
  16410. return res;
  16411. }
  16412. /*! \brief Check if matching user or peer is defined
  16413. Match user on From: user name and peer on IP/port
  16414. This is used on first invite (not re-invites) and subscribe requests
  16415. \return 0 on success, non-zero on failure
  16416. */
  16417. static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
  16418. int sipmethod, const char *uri, enum xmittype reliable,
  16419. struct ast_sockaddr *addr, struct sip_peer **authpeer)
  16420. {
  16421. char *of, *name, *unused_password, *domain;
  16422. RAII_VAR(char *, ofbuf, NULL, ast_free); /* beware, everyone starts pointing to this */
  16423. RAII_VAR(char *, namebuf, NULL, ast_free);
  16424. enum check_auth_result res = AUTH_DONT_KNOW;
  16425. char calleridname[256];
  16426. char *uri2 = ast_strdupa(uri);
  16427. terminate_uri(uri2); /* trim extra stuff */
  16428. ofbuf = ast_strdup(sip_get_header(req, "From"));
  16429. /* XXX here tries to map the username for invite things */
  16430. /* strip the display-name portion off the beginning of the FROM header. */
  16431. if (!(of = (char *) get_calleridname(ofbuf, calleridname, sizeof(calleridname)))) {
  16432. ast_log(LOG_ERROR, "FROM header can not be parsed\n");
  16433. return res;
  16434. }
  16435. if (calleridname[0]) {
  16436. ast_string_field_set(p, cid_name, calleridname);
  16437. }
  16438. if (ast_strlen_zero(p->exten)) {
  16439. char *t = uri2;
  16440. if (!strncasecmp(t, "sip:", 4)) {
  16441. t += 4;
  16442. } else if (!strncasecmp(t, "sips:", 5)) {
  16443. t += 5;
  16444. } else if (!strncasecmp(t, "tel:", 4)) { /* TEL URI INVITE */
  16445. t += 4;
  16446. }
  16447. ast_string_field_set(p, exten, t);
  16448. t = strchr(p->exten, '@');
  16449. if (t)
  16450. *t = '\0';
  16451. if (ast_strlen_zero(p->our_contact)) {
  16452. build_contact(p, req, 1);
  16453. }
  16454. }
  16455. of = get_in_brackets(of);
  16456. /* save the URI part of the From header */
  16457. ast_string_field_set(p, from, of);
  16458. if (parse_uri_legacy_check(of, "sip:,sips:,tel:", &name, &unused_password, &domain, NULL)) {
  16459. ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
  16460. }
  16461. SIP_PEDANTIC_DECODE(name);
  16462. SIP_PEDANTIC_DECODE(domain);
  16463. extract_host_from_hostport(&domain);
  16464. if (ast_strlen_zero(domain)) {
  16465. /* <sip:name@[EMPTY]>, never good */
  16466. ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
  16467. return res;
  16468. }
  16469. if (ast_strlen_zero(name)) {
  16470. /* <sip:[EMPTY][@]hostport>. Asterisk 1.4 and 1.6 have always
  16471. * treated that as a username, so we continue the tradition:
  16472. * uri is now <sip:host@hostport>. */
  16473. name = domain;
  16474. } else {
  16475. /* Non-empty name, try to get caller id from it */
  16476. char *tmp = ast_strdupa(name);
  16477. /* We need to be able to handle from-headers looking like
  16478. <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
  16479. */
  16480. tmp = strsep(&tmp, ";");
  16481. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
  16482. ast_shrink_phone_number(tmp);
  16483. }
  16484. ast_string_field_set(p, cid_num, tmp);
  16485. }
  16486. if (global_match_auth_username) {
  16487. /*
  16488. * XXX This is experimental code to grab the search key from the
  16489. * Auth header's username instead of the 'From' name, if available.
  16490. * Do not enable this block unless you understand the side effects (if any!)
  16491. * Note, the search for "username" should be done in a more robust way.
  16492. * Note2, at the moment we check both fields, though maybe we should
  16493. * pick one or another depending on the request ? XXX
  16494. */
  16495. const char *hdr = sip_get_header(req, "Authorization");
  16496. if (ast_strlen_zero(hdr)) {
  16497. hdr = sip_get_header(req, "Proxy-Authorization");
  16498. }
  16499. if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
  16500. namebuf = name = ast_strdup(hdr + strlen("username=\""));
  16501. name = strsep(&name, "\"");
  16502. }
  16503. }
  16504. res = check_peer_ok(p, name, req, sipmethod, addr,
  16505. authpeer, reliable, calleridname, uri2);
  16506. if (res != AUTH_DONT_KNOW) {
  16507. return res;
  16508. }
  16509. /* Finally, apply the guest policy */
  16510. if (sip_cfg.allowguest) {
  16511. /* Ignore check_return warning from Coverity for get_rpid below. */
  16512. get_rpid(p, req);
  16513. p->rtptimeout = global_rtptimeout;
  16514. p->rtpholdtimeout = global_rtpholdtimeout;
  16515. p->rtpkeepalive = global_rtpkeepalive;
  16516. if (!dialog_initialize_rtp(p)) {
  16517. res = AUTH_SUCCESSFUL;
  16518. } else {
  16519. res = AUTH_RTP_FAILED;
  16520. }
  16521. } else {
  16522. res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
  16523. }
  16524. if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
  16525. ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
  16526. }
  16527. return res;
  16528. }
  16529. /*! \brief Find user
  16530. If we get a match, this will add a reference pointer to the user object, that needs to be unreferenced
  16531. */
  16532. static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
  16533. {
  16534. return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
  16535. }
  16536. static int set_message_vars_from_req(struct ast_msg *msg, struct sip_request *req)
  16537. {
  16538. size_t x;
  16539. char name_buf[1024];
  16540. char val_buf[1024];
  16541. const char *name;
  16542. char *c;
  16543. int res = 0;
  16544. for (x = 0; x < req->headers; x++) {
  16545. const char *header = REQ_OFFSET_TO_STR(req, header[x]);
  16546. if ((c = strchr(header, ':'))) {
  16547. ast_copy_string(name_buf, header, MIN((c - header + 1), sizeof(name_buf)));
  16548. ast_copy_string(val_buf, ast_skip_blanks(c + 1), sizeof(val_buf));
  16549. ast_trim_blanks(name_buf);
  16550. /* Convert header name to full name alias. */
  16551. name = find_full_alias(name_buf, name_buf);
  16552. res = ast_msg_set_var(msg, name, val_buf);
  16553. if (res) {
  16554. break;
  16555. }
  16556. }
  16557. }
  16558. return res;
  16559. }
  16560. /*! \brief Receive SIP MESSAGE method messages
  16561. \note We only handle messages within current calls currently
  16562. Reference: RFC 3428 */
  16563. static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
  16564. {
  16565. char *buf;
  16566. size_t len;
  16567. struct ast_frame f;
  16568. const char *content_type = sip_get_header(req, "Content-Type");
  16569. struct ast_msg *msg;
  16570. int res;
  16571. char *from;
  16572. char *to;
  16573. char from_name[50];
  16574. char stripped[SIPBUFSIZE];
  16575. enum sip_get_dest_result dest_result;
  16576. if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
  16577. transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
  16578. if (!p->owner) {
  16579. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16580. }
  16581. return;
  16582. }
  16583. if (!(buf = get_content(req))) {
  16584. ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
  16585. transmit_response(p, "500 Internal Server Error", req);
  16586. if (!p->owner) {
  16587. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16588. }
  16589. return;
  16590. }
  16591. /* Strip trailing line feeds from message body. (get_content may add
  16592. * a trailing linefeed and we don't need any at the end) */
  16593. len = strlen(buf);
  16594. while (len > 0) {
  16595. if (buf[--len] != '\n') {
  16596. ++len;
  16597. break;
  16598. }
  16599. }
  16600. buf[len] = '\0';
  16601. if (p->owner) {
  16602. if (sip_debug_test_pvt(p)) {
  16603. ast_verbose("SIP Text message received: '%s'\n", buf);
  16604. }
  16605. memset(&f, 0, sizeof(f));
  16606. f.frametype = AST_FRAME_TEXT;
  16607. f.subclass.integer = 0;
  16608. f.offset = 0;
  16609. f.data.ptr = buf;
  16610. f.datalen = strlen(buf) + 1;
  16611. ast_queue_frame(p->owner, &f);
  16612. transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
  16613. return;
  16614. }
  16615. /*
  16616. * At this point MESSAGE is outside of a call.
  16617. *
  16618. * NOTE: p->owner is NULL so no additional check is needed after
  16619. * this point.
  16620. */
  16621. if (!sip_cfg.accept_outofcall_message) {
  16622. /* Message outside of a call, we do not support that */
  16623. ast_debug(1, "MESSAGE outside of a call administratively disabled.\n");
  16624. transmit_response(p, "405 Method Not Allowed", req);
  16625. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16626. return;
  16627. }
  16628. copy_request(&p->initreq, req);
  16629. if (sip_cfg.auth_message_requests) {
  16630. int res;
  16631. set_pvt_allowed_methods(p, req);
  16632. res = check_user(p, req, SIP_MESSAGE, e, XMIT_UNRELIABLE, addr);
  16633. if (res == AUTH_CHALLENGE_SENT) {
  16634. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16635. return;
  16636. }
  16637. if (res < 0) { /* Something failed in authentication */
  16638. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
  16639. transmit_response(p, "403 Forbidden", req);
  16640. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16641. return;
  16642. }
  16643. /* Auth was successful. Proceed. */
  16644. } else {
  16645. struct sip_peer *peer;
  16646. /*
  16647. * MESSAGE outside of a call, not authenticating it.
  16648. * Check to see if we match a peer anyway so that we can direct
  16649. * it to the right context.
  16650. */
  16651. peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, 0, p->socket.type);
  16652. if (peer) {
  16653. /* Only if no auth is required. */
  16654. if (ast_strlen_zero(peer->secret) && ast_strlen_zero(peer->md5secret)) {
  16655. ast_string_field_set(p, context, peer->context);
  16656. }
  16657. if (!ast_strlen_zero(peer->messagecontext)) {
  16658. ast_string_field_set(p, messagecontext, peer->messagecontext);
  16659. }
  16660. ast_string_field_set(p, peername, peer->name);
  16661. peer = sip_unref_peer(peer, "from sip_find_peer() in receive_message");
  16662. }
  16663. }
  16664. /* Override the context with the message context _BEFORE_
  16665. * getting the destination. This way we can guarantee the correct
  16666. * extension is used in the message context when it is present. */
  16667. if (!ast_strlen_zero(p->messagecontext)) {
  16668. ast_string_field_set(p, context, p->messagecontext);
  16669. } else if (!ast_strlen_zero(sip_cfg.messagecontext)) {
  16670. ast_string_field_set(p, context, sip_cfg.messagecontext);
  16671. }
  16672. dest_result = get_destination(p, NULL, NULL);
  16673. switch (dest_result) {
  16674. case SIP_GET_DEST_REFUSED:
  16675. /* Okay to send 403 since this is after auth processing */
  16676. transmit_response(p, "403 Forbidden", req);
  16677. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16678. return;
  16679. case SIP_GET_DEST_INVALID_URI:
  16680. transmit_response(p, "416 Unsupported URI Scheme", req);
  16681. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16682. return;
  16683. default:
  16684. /* We may have something other than dialplan who wants
  16685. * the message, so defer further error handling for now */
  16686. break;
  16687. }
  16688. if (!(msg = ast_msg_alloc())) {
  16689. transmit_response(p, "500 Internal Server Error", req);
  16690. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16691. return;
  16692. }
  16693. to = ast_strdupa(REQ_OFFSET_TO_STR(req, rlpart2));
  16694. from = ast_strdupa(sip_get_header(req, "From"));
  16695. res = ast_msg_set_to(msg, "%s", to);
  16696. /* Build "display" <uri> for from string. */
  16697. from = (char *) get_calleridname(from, from_name, sizeof(from_name));
  16698. from = get_in_brackets(from);
  16699. if (from_name[0]) {
  16700. char from_buf[128];
  16701. ast_escape_quoted(from_name, from_buf, sizeof(from_buf));
  16702. res |= ast_msg_set_from(msg, "\"%s\" <%s>", from_buf, from);
  16703. } else {
  16704. res |= ast_msg_set_from(msg, "<%s>", from);
  16705. }
  16706. res |= ast_msg_set_body(msg, "%s", buf);
  16707. res |= ast_msg_set_context(msg, "%s", p->context);
  16708. res |= ast_msg_set_var(msg, "SIP_RECVADDR", ast_sockaddr_stringify(&p->recv));
  16709. res |= ast_msg_set_tech(msg, "%s", "SIP");
  16710. if (!ast_strlen_zero(p->peername)) {
  16711. res |= ast_msg_set_endpoint(msg, "%s", p->peername);
  16712. res |= ast_msg_set_var(msg, "SIP_PEERNAME", p->peername);
  16713. }
  16714. ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
  16715. res |= ast_msg_set_var(msg, "SIP_FULLCONTACT", get_in_brackets(stripped));
  16716. res |= ast_msg_set_exten(msg, "%s", p->exten);
  16717. res |= set_message_vars_from_req(msg, req);
  16718. if (res) {
  16719. ast_msg_destroy(msg);
  16720. transmit_response(p, "500 Internal Server Error", req);
  16721. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16722. return;
  16723. }
  16724. if (ast_msg_has_destination(msg)) {
  16725. ast_msg_queue(msg);
  16726. transmit_response(p, "202 Accepted", req);
  16727. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16728. return;
  16729. }
  16730. /* Find a specific error cause to send */
  16731. switch (dest_result) {
  16732. case SIP_GET_DEST_EXTEN_NOT_FOUND:
  16733. case SIP_GET_DEST_EXTEN_MATCHMORE:
  16734. transmit_response(p, "404 Not Found", req);
  16735. break;
  16736. case SIP_GET_DEST_EXTEN_FOUND:
  16737. default:
  16738. /* We should have sent the message already! */
  16739. ast_assert(0);
  16740. transmit_response(p, "500 Internal Server Error", req);
  16741. break;
  16742. }
  16743. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16744. ast_msg_destroy(msg);
  16745. }
  16746. /*! \brief CLI Command to show calls within limits set by call_limit */
  16747. static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16748. {
  16749. #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
  16750. #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
  16751. char ilimits[40];
  16752. char iused[40];
  16753. int showall = FALSE;
  16754. struct ao2_iterator i;
  16755. struct sip_peer *peer;
  16756. switch (cmd) {
  16757. case CLI_INIT:
  16758. e->command = "sip show inuse";
  16759. e->usage =
  16760. "Usage: sip show inuse [all]\n"
  16761. " List all SIP devices usage counters and limits.\n"
  16762. " Add option \"all\" to show all devices, not only those with a limit.\n";
  16763. return NULL;
  16764. case CLI_GENERATE:
  16765. return NULL;
  16766. }
  16767. if (a->argc < 3)
  16768. return CLI_SHOWUSAGE;
  16769. if (a->argc == 4 && !strcmp(a->argv[3], "all"))
  16770. showall = TRUE;
  16771. ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
  16772. i = ao2_iterator_init(peers, 0);
  16773. while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
  16774. ao2_lock(peer);
  16775. if (peer->call_limit)
  16776. snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
  16777. else
  16778. ast_copy_string(ilimits, "N/A", sizeof(ilimits));
  16779. snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inuse, peer->ringing, peer->onhold);
  16780. if (showall || peer->call_limit)
  16781. ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
  16782. ao2_unlock(peer);
  16783. sip_unref_peer(peer, "toss iterator pointer");
  16784. }
  16785. ao2_iterator_destroy(&i);
  16786. return CLI_SUCCESS;
  16787. #undef FORMAT
  16788. #undef FORMAT2
  16789. }
  16790. /*! \brief Convert transfer mode to text string */
  16791. static char *transfermode2str(enum transfermodes mode)
  16792. {
  16793. if (mode == TRANSFER_OPENFORALL)
  16794. return "open";
  16795. else if (mode == TRANSFER_CLOSED)
  16796. return "closed";
  16797. return "strict";
  16798. }
  16799. /*! \brief Report Peer status in character string
  16800. * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
  16801. */
  16802. /* Session-Timer Modes */
  16803. static const struct _map_x_s stmodes[] = {
  16804. { SESSION_TIMER_MODE_ACCEPT, "Accept"},
  16805. { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
  16806. { SESSION_TIMER_MODE_REFUSE, "Refuse"},
  16807. { -1, NULL},
  16808. };
  16809. static const char *stmode2str(enum st_mode m)
  16810. {
  16811. return map_x_s(stmodes, m, "Unknown");
  16812. }
  16813. static enum st_mode str2stmode(const char *s)
  16814. {
  16815. return map_s_x(stmodes, s, -1);
  16816. }
  16817. /* Session-Timer Refreshers */
  16818. static const struct _map_x_s strefresher_params[] = {
  16819. { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
  16820. { SESSION_TIMER_REFRESHER_PARAM_UAC, "uac" },
  16821. { SESSION_TIMER_REFRESHER_PARAM_UAS, "uas" },
  16822. { -1, NULL },
  16823. };
  16824. static const struct _map_x_s strefreshers[] = {
  16825. { SESSION_TIMER_REFRESHER_AUTO, "auto" },
  16826. { SESSION_TIMER_REFRESHER_US, "us" },
  16827. { SESSION_TIMER_REFRESHER_THEM, "them" },
  16828. { -1, NULL },
  16829. };
  16830. static const char *strefresherparam2str(enum st_refresher_param r)
  16831. {
  16832. return map_x_s(strefresher_params, r, "Unknown");
  16833. }
  16834. static enum st_refresher_param str2strefresherparam(const char *s)
  16835. {
  16836. return map_s_x(strefresher_params, s, -1);
  16837. }
  16838. /* Autocreatepeer modes */
  16839. static struct _map_x_s autopeermodes[] = {
  16840. { AUTOPEERS_DISABLED, "Off"},
  16841. { AUTOPEERS_VOLATILE, "Volatile"},
  16842. { AUTOPEERS_PERSIST, "Persisted"},
  16843. { -1, NULL},
  16844. };
  16845. static const char *strefresher2str(enum st_refresher r)
  16846. {
  16847. return map_x_s(strefreshers, r, "Unknown");
  16848. }
  16849. static const char *autocreatepeer2str(enum autocreatepeer_mode r)
  16850. {
  16851. return map_x_s(autopeermodes, r, "Unknown");
  16852. }
  16853. static int peer_status(struct sip_peer *peer, char *status, int statuslen)
  16854. {
  16855. int res = 0;
  16856. if (peer->maxms) {
  16857. if (peer->lastms < 0) {
  16858. ast_copy_string(status, "UNREACHABLE", statuslen);
  16859. } else if (peer->lastms > peer->maxms) {
  16860. snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
  16861. res = 1;
  16862. } else if (peer->lastms) {
  16863. snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
  16864. res = 1;
  16865. } else {
  16866. ast_copy_string(status, "UNKNOWN", statuslen);
  16867. }
  16868. } else {
  16869. ast_copy_string(status, "Unmonitored", statuslen);
  16870. /* Checking if port is 0 */
  16871. res = -1;
  16872. }
  16873. return res;
  16874. }
  16875. /*! \brief Show active TCP connections */
  16876. static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16877. {
  16878. struct sip_threadinfo *th;
  16879. struct ao2_iterator i;
  16880. #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
  16881. #define FORMAT "%-47.47s %-9.9s %-6.6s\n"
  16882. switch (cmd) {
  16883. case CLI_INIT:
  16884. e->command = "sip show tcp";
  16885. e->usage =
  16886. "Usage: sip show tcp\n"
  16887. " Lists all active TCP/TLS sessions.\n";
  16888. return NULL;
  16889. case CLI_GENERATE:
  16890. return NULL;
  16891. }
  16892. if (a->argc != 3)
  16893. return CLI_SHOWUSAGE;
  16894. ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
  16895. i = ao2_iterator_init(threadt, 0);
  16896. while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
  16897. ast_cli(a->fd, FORMAT,
  16898. ast_sockaddr_stringify(&th->tcptls_session->remote_address),
  16899. sip_get_transport(th->type),
  16900. (th->tcptls_session->client ? "Client" : "Server"));
  16901. ao2_t_ref(th, -1, "decrement ref from iterator");
  16902. }
  16903. ao2_iterator_destroy(&i);
  16904. return CLI_SUCCESS;
  16905. #undef FORMAT
  16906. #undef FORMAT2
  16907. }
  16908. /*! \brief CLI Command 'SIP Show Users' */
  16909. static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16910. {
  16911. regex_t regexbuf;
  16912. int havepattern = FALSE;
  16913. struct ao2_iterator user_iter;
  16914. struct sip_peer *user;
  16915. #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
  16916. switch (cmd) {
  16917. case CLI_INIT:
  16918. e->command = "sip show users";
  16919. e->usage =
  16920. "Usage: sip show users [like <pattern>]\n"
  16921. " Lists all known SIP users.\n"
  16922. " Optional regular expression pattern is used to filter the user list.\n";
  16923. return NULL;
  16924. case CLI_GENERATE:
  16925. return NULL;
  16926. }
  16927. switch (a->argc) {
  16928. case 5:
  16929. if (!strcasecmp(a->argv[3], "like")) {
  16930. if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
  16931. return CLI_SHOWUSAGE;
  16932. havepattern = TRUE;
  16933. } else
  16934. return CLI_SHOWUSAGE;
  16935. case 3:
  16936. break;
  16937. default:
  16938. return CLI_SHOWUSAGE;
  16939. }
  16940. ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "Forcerport");
  16941. user_iter = ao2_iterator_init(peers, 0);
  16942. while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
  16943. ao2_lock(user);
  16944. if (!(user->type & SIP_TYPE_USER)) {
  16945. ao2_unlock(user);
  16946. sip_unref_peer(user, "sip show users");
  16947. continue;
  16948. }
  16949. if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
  16950. ao2_unlock(user);
  16951. sip_unref_peer(user, "sip show users");
  16952. continue;
  16953. }
  16954. ast_cli(a->fd, FORMAT, user->name,
  16955. user->secret,
  16956. user->accountcode,
  16957. user->context,
  16958. AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0),
  16959. AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
  16960. ao2_unlock(user);
  16961. sip_unref_peer(user, "sip show users");
  16962. }
  16963. ao2_iterator_destroy(&user_iter);
  16964. if (havepattern)
  16965. regfree(&regexbuf);
  16966. return CLI_SUCCESS;
  16967. #undef FORMAT
  16968. }
  16969. /*! \brief Show SIP registrations in the manager API */
  16970. static int manager_show_registry(struct mansession *s, const struct message *m)
  16971. {
  16972. const char *id = astman_get_header(m, "ActionID");
  16973. char idtext[256] = "";
  16974. int total = 0;
  16975. struct ao2_iterator iter;
  16976. struct sip_registry *iterator;
  16977. if (!ast_strlen_zero(id))
  16978. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  16979. astman_send_listack(s, m, "Registrations will follow", "start");
  16980. iter = ao2_iterator_init(registry_list, 0);
  16981. while ((iterator = ao2_t_iterator_next(&iter, "manager_show_registry iter"))) {
  16982. ao2_lock(iterator);
  16983. astman_append(s,
  16984. "Event: RegistryEntry\r\n"
  16985. "%s"
  16986. "Host: %s\r\n"
  16987. "Port: %d\r\n"
  16988. "Username: %s\r\n"
  16989. "Domain: %s\r\n"
  16990. "DomainPort: %d\r\n"
  16991. "Refresh: %d\r\n"
  16992. "State: %s\r\n"
  16993. "RegistrationTime: %ld\r\n"
  16994. "\r\n",
  16995. idtext,
  16996. iterator->hostname,
  16997. iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
  16998. iterator->username,
  16999. S_OR(iterator->regdomain,iterator->hostname),
  17000. iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
  17001. iterator->refresh,
  17002. regstate2str(iterator->regstate),
  17003. (long) iterator->regtime.tv_sec);
  17004. ao2_unlock(iterator);
  17005. ao2_t_ref(iterator, -1, "manager_show_registry iter");
  17006. total++;
  17007. }
  17008. ao2_iterator_destroy(&iter);
  17009. astman_send_list_complete_start(s, m, "RegistrationsComplete", total);
  17010. astman_send_list_complete_end(s);
  17011. return 0;
  17012. }
  17013. /*! \brief Show SIP peers in the manager API */
  17014. /* Inspired from chan_iax2 */
  17015. static int manager_sip_show_peers(struct mansession *s, const struct message *m)
  17016. {
  17017. const char *id = astman_get_header(m, "ActionID");
  17018. const char *a[] = {"sip", "show", "peers"};
  17019. char idtext[256] = "";
  17020. int total = 0;
  17021. if (!ast_strlen_zero(id))
  17022. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  17023. astman_send_listack(s, m, "Peer status list will follow", "start");
  17024. /* List the peers in separate manager events */
  17025. _sip_show_peers(-1, &total, s, m, 3, a);
  17026. /* Send final confirmation */
  17027. astman_send_list_complete_start(s, m, "PeerlistComplete", total);
  17028. astman_send_list_complete_end(s);
  17029. return 0;
  17030. }
  17031. /*! \brief CLI Show Peers command */
  17032. static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17033. {
  17034. switch (cmd) {
  17035. case CLI_INIT:
  17036. e->command = "sip show peers";
  17037. e->usage =
  17038. "Usage: sip show peers [like <pattern>]\n"
  17039. " Lists all known SIP peers.\n"
  17040. " Optional regular expression pattern is used to filter the peer list.\n";
  17041. return NULL;
  17042. case CLI_GENERATE:
  17043. return NULL;
  17044. }
  17045. return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
  17046. }
  17047. int peercomparefunc(const void *a, const void *b);
  17048. int peercomparefunc(const void *a, const void *b)
  17049. {
  17050. struct sip_peer **ap = (struct sip_peer **)a;
  17051. struct sip_peer **bp = (struct sip_peer **)b;
  17052. return strcmp((*ap)->name, (*bp)->name);
  17053. }
  17054. /* the last argument is left-aligned, so we don't need a size anyways */
  17055. #define PEERS_FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-10.10s %-3.3s %-8s %-11s %-32.32s %s\n"
  17056. /*! \brief Used in the sip_show_peers functions to pass parameters */
  17057. struct show_peers_context {
  17058. regex_t regexbuf;
  17059. int havepattern;
  17060. char idtext[256];
  17061. int realtimepeers;
  17062. int peers_mon_online;
  17063. int peers_mon_offline;
  17064. int peers_unmon_offline;
  17065. int peers_unmon_online;
  17066. };
  17067. /*! \brief Execute sip show peers command */
  17068. static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
  17069. {
  17070. struct show_peers_context cont = {
  17071. .havepattern = FALSE,
  17072. .idtext = "",
  17073. .peers_mon_online = 0,
  17074. .peers_mon_offline = 0,
  17075. .peers_unmon_online = 0,
  17076. .peers_unmon_offline = 0,
  17077. };
  17078. struct sip_peer *peer;
  17079. struct ao2_iterator* it_peers;
  17080. int total_peers = 0;
  17081. const char *id;
  17082. struct sip_peer **peerarray;
  17083. int k;
  17084. cont.realtimepeers = ast_check_realtime("sippeers");
  17085. if (s) { /* Manager - get ActionID */
  17086. id = astman_get_header(m, "ActionID");
  17087. if (!ast_strlen_zero(id)) {
  17088. snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
  17089. }
  17090. }
  17091. switch (argc) {
  17092. case 5:
  17093. if (!strcasecmp(argv[3], "like")) {
  17094. if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB)) {
  17095. return CLI_SHOWUSAGE;
  17096. }
  17097. cont.havepattern = TRUE;
  17098. } else {
  17099. return CLI_SHOWUSAGE;
  17100. }
  17101. case 3:
  17102. break;
  17103. default:
  17104. return CLI_SHOWUSAGE;
  17105. }
  17106. if (!s) {
  17107. /* Normal list */
  17108. ast_cli(fd, PEERS_FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "Comedia", "ACL", "Port", "Status", "Description", (cont.realtimepeers ? "Realtime" : ""));
  17109. }
  17110. ao2_lock(peers);
  17111. if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
  17112. ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
  17113. ao2_unlock(peers);
  17114. return CLI_FAILURE;
  17115. }
  17116. if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
  17117. ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
  17118. ao2_iterator_destroy(it_peers);
  17119. ao2_unlock(peers);
  17120. return CLI_FAILURE;
  17121. }
  17122. ao2_unlock(peers);
  17123. while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
  17124. ao2_lock(peer);
  17125. if (!(peer->type & SIP_TYPE_PEER)) {
  17126. ao2_unlock(peer);
  17127. sip_unref_peer(peer, "unref peer because it's actually a user");
  17128. continue;
  17129. }
  17130. if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
  17131. ao2_unlock(peer);
  17132. sip_unref_peer(peer, "toss iterator peer ptr before continue");
  17133. continue;
  17134. }
  17135. peerarray[total_peers++] = peer;
  17136. ao2_unlock(peer);
  17137. }
  17138. ao2_iterator_destroy(it_peers);
  17139. qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
  17140. for(k = 0; k < total_peers; k++) {
  17141. peerarray[k] = _sip_show_peers_one(fd, s, &cont, peerarray[k]);
  17142. }
  17143. if (!s) {
  17144. ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
  17145. total_peers, cont.peers_mon_online, cont.peers_mon_offline, cont.peers_unmon_online, cont.peers_unmon_offline);
  17146. }
  17147. if (cont.havepattern) {
  17148. regfree(&cont.regexbuf);
  17149. }
  17150. if (total) {
  17151. *total = total_peers;
  17152. }
  17153. ast_free(peerarray);
  17154. return CLI_SUCCESS;
  17155. }
  17156. /*! \brief Emit informations for one peer during sip show peers command */
  17157. static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer)
  17158. {
  17159. /* _sip_show_peers_one() is separated from _sip_show_peers() to properly free the ast_strdupa
  17160. * (this is executed in a loop in _sip_show_peers() )
  17161. */
  17162. char name[256];
  17163. char status[20] = "";
  17164. char pstatus;
  17165. /*
  17166. * tmp_port and tmp_host store copies of ast_sockaddr_stringify strings since the
  17167. * string pointers for that function aren't valid between subsequent calls to
  17168. * ast_sockaddr_stringify functions
  17169. */
  17170. char *tmp_port;
  17171. char *tmp_host;
  17172. tmp_port = ast_sockaddr_isnull(&peer->addr) ?
  17173. "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
  17174. tmp_host = ast_sockaddr_isnull(&peer->addr) ?
  17175. "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
  17176. ao2_lock(peer);
  17177. if (cont->havepattern && regexec(&cont->regexbuf, peer->name, 0, NULL, 0)) {
  17178. ao2_unlock(peer);
  17179. return sip_unref_peer(peer, "toss iterator peer ptr no match");
  17180. }
  17181. if (!ast_strlen_zero(peer->username) && !s) {
  17182. snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
  17183. } else {
  17184. ast_copy_string(name, peer->name, sizeof(name));
  17185. }
  17186. pstatus = peer_status(peer, status, sizeof(status));
  17187. if (pstatus == 1) {
  17188. cont->peers_mon_online++;
  17189. } else if (pstatus == 0) {
  17190. cont->peers_mon_offline++;
  17191. } else {
  17192. if (ast_sockaddr_isnull(&peer->addr) ||
  17193. !ast_sockaddr_port(&peer->addr)) {
  17194. cont->peers_unmon_offline++;
  17195. } else {
  17196. cont->peers_unmon_online++;
  17197. }
  17198. }
  17199. if (!s) { /* Normal CLI list */
  17200. ast_cli(fd, PEERS_FORMAT2, name,
  17201. tmp_host,
  17202. peer->host_dynamic ? " D " : " ", /* Dynamic or not? */
  17203. force_rport_string(peer->flags),
  17204. comedia_string(peer->flags),
  17205. (!ast_acl_list_is_empty(peer->acl)) ? " A " : " ", /* permit/deny */
  17206. tmp_port, status,
  17207. peer->description ? peer->description : "",
  17208. cont->realtimepeers ? (peer->is_realtime ? "Cached RT" : "") : "");
  17209. } else { /* Manager format */
  17210. /* The names here need to be the same as other channels */
  17211. astman_append(s,
  17212. "Event: PeerEntry\r\n%s"
  17213. "Channeltype: SIP\r\n"
  17214. "ObjectName: %s\r\n"
  17215. "ChanObjectType: peer\r\n" /* "peer" or "user" */
  17216. "IPaddress: %s\r\n"
  17217. "IPport: %s\r\n"
  17218. "Dynamic: %s\r\n"
  17219. "AutoForcerport: %s\r\n"
  17220. "Forcerport: %s\r\n"
  17221. "AutoComedia: %s\r\n"
  17222. "Comedia: %s\r\n"
  17223. "VideoSupport: %s\r\n"
  17224. "TextSupport: %s\r\n"
  17225. "ACL: %s\r\n"
  17226. "Status: %s\r\n"
  17227. "RealtimeDevice: %s\r\n"
  17228. "Description: %s\r\n\r\n",
  17229. cont->idtext,
  17230. peer->name,
  17231. ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
  17232. ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
  17233. peer->host_dynamic ? "yes" : "no", /* Dynamic or not? */
  17234. ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ? "yes" : "no",
  17235. ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
  17236. ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ? "yes" : "no",
  17237. ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "yes" : "no",
  17238. ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
  17239. ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no", /* TEXTSUPPORT=yes? */
  17240. ast_acl_list_is_empty(peer->acl) ? "no" : "yes", /* permit/deny/acl */
  17241. status,
  17242. cont->realtimepeers ? (peer->is_realtime ? "yes" : "no") : "no",
  17243. peer->description);
  17244. }
  17245. ao2_unlock(peer);
  17246. return sip_unref_peer(peer, "toss iterator peer ptr");
  17247. }
  17248. #undef PEERS_FORMAT2
  17249. static int peer_dump_func(void *userobj, void *arg, int flags)
  17250. {
  17251. struct sip_peer *peer = userobj;
  17252. int refc = ao2_t_ref(userobj, 0, "");
  17253. struct ast_cli_args *a = (struct ast_cli_args *) arg;
  17254. ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
  17255. peer->name, 0, refc);
  17256. return 0;
  17257. }
  17258. static int dialog_dump_func(void *userobj, void *arg, int flags)
  17259. {
  17260. struct sip_pvt *pvt = userobj;
  17261. int refc = ao2_t_ref(userobj, 0, "");
  17262. struct ast_cli_args *a = (struct ast_cli_args *) arg;
  17263. ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
  17264. pvt->callid, 0, refc);
  17265. return 0;
  17266. }
  17267. /*! \brief List all allocated SIP Objects (realtime or static) */
  17268. static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17269. {
  17270. struct sip_registry *reg;
  17271. struct ao2_iterator iter;
  17272. switch (cmd) {
  17273. case CLI_INIT:
  17274. e->command = "sip show objects";
  17275. e->usage =
  17276. "Usage: sip show objects\n"
  17277. " Lists status of known SIP objects\n";
  17278. return NULL;
  17279. case CLI_GENERATE:
  17280. return NULL;
  17281. }
  17282. if (a->argc != 3)
  17283. return CLI_SHOWUSAGE;
  17284. ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
  17285. ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
  17286. ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
  17287. ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
  17288. iter = ao2_iterator_init(registry_list, 0);
  17289. ast_cli(a->fd, "-= Registry objects: %d =-\n\n", ao2_container_count(registry_list));
  17290. while ((reg = ao2_t_iterator_next(&iter, "sip_show_objects iter"))) {
  17291. ao2_lock(reg);
  17292. ast_cli(a->fd, "name: %s\n", reg->configvalue);
  17293. ao2_unlock(reg);
  17294. ao2_t_ref(reg, -1, "sip_show_objects iter");
  17295. }
  17296. ao2_iterator_destroy(&iter);
  17297. ast_cli(a->fd, "-= Dialog objects:\n\n");
  17298. ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
  17299. return CLI_SUCCESS;
  17300. }
  17301. /*! \brief Print call group and pickup group */
  17302. static void print_group(int fd, ast_group_t group, int crlf)
  17303. {
  17304. char buf[256];
  17305. ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
  17306. }
  17307. /*! \brief Print named call groups and pickup groups */
  17308. static void print_named_groups(int fd, struct ast_namedgroups *group, int crlf)
  17309. {
  17310. struct ast_str *buf = ast_str_create(1024);
  17311. if (buf) {
  17312. ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_namedgroups(&buf, group) );
  17313. ast_free(buf);
  17314. }
  17315. }
  17316. /*! \brief mapping between dtmf flags and strings */
  17317. static const struct _map_x_s dtmfstr[] = {
  17318. { SIP_DTMF_RFC2833, "rfc2833" },
  17319. { SIP_DTMF_INFO, "info" },
  17320. { SIP_DTMF_SHORTINFO, "shortinfo" },
  17321. { SIP_DTMF_INBAND, "inband" },
  17322. { SIP_DTMF_AUTO, "auto" },
  17323. { -1, NULL }, /* terminator */
  17324. };
  17325. /*! \brief Convert DTMF mode to printable string */
  17326. static const char *dtmfmode2str(int mode)
  17327. {
  17328. return map_x_s(dtmfstr, mode, "<error>");
  17329. }
  17330. /*! \brief maps a string to dtmfmode, returns -1 on error */
  17331. static int str2dtmfmode(const char *str)
  17332. {
  17333. return map_s_x(dtmfstr, str, -1);
  17334. }
  17335. static const struct _map_x_s insecurestr[] = {
  17336. { SIP_INSECURE_PORT, "port" },
  17337. { SIP_INSECURE_INVITE, "invite" },
  17338. { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
  17339. { 0, "no" },
  17340. { -1, NULL }, /* terminator */
  17341. };
  17342. /*! \brief Convert Insecure setting to printable string */
  17343. static const char *insecure2str(int mode)
  17344. {
  17345. return map_x_s(insecurestr, mode, "<error>");
  17346. }
  17347. static const struct _map_x_s allowoverlapstr[] = {
  17348. { SIP_PAGE2_ALLOWOVERLAP_YES, "Yes" },
  17349. { SIP_PAGE2_ALLOWOVERLAP_DTMF, "DTMF" },
  17350. { SIP_PAGE2_ALLOWOVERLAP_NO, "No" },
  17351. { -1, NULL }, /* terminator */
  17352. };
  17353. /*! \brief Convert AllowOverlap setting to printable string */
  17354. static const char *allowoverlap2str(int mode)
  17355. {
  17356. return map_x_s(allowoverlapstr, mode, "<error>");
  17357. }
  17358. static const struct _map_x_s trust_id_outboundstr[] = {
  17359. { SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY, "Legacy" },
  17360. { SIP_PAGE2_TRUST_ID_OUTBOUND_NO, "No" },
  17361. { SIP_PAGE2_TRUST_ID_OUTBOUND_YES, "Yes" },
  17362. { -1, NULL }, /* terminator */
  17363. };
  17364. static const char *trust_id_outbound2str(int mode)
  17365. {
  17366. return map_x_s(trust_id_outboundstr, mode, "<error>");
  17367. }
  17368. /*! \brief Destroy disused contexts between reloads
  17369. Only used in reload_config so the code for regcontext doesn't get ugly
  17370. */
  17371. static void cleanup_stale_contexts(char *new, char *old)
  17372. {
  17373. char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
  17374. while ((oldcontext = strsep(&old, "&"))) {
  17375. stalecontext = NULL;
  17376. ast_copy_string(newlist, new, sizeof(newlist));
  17377. stringp = newlist;
  17378. while ((newcontext = strsep(&stringp, "&"))) {
  17379. if (!strcmp(newcontext, oldcontext)) {
  17380. /* This is not the context you're looking for */
  17381. stalecontext = NULL;
  17382. break;
  17383. } else if (strcmp(newcontext, oldcontext)) {
  17384. stalecontext = oldcontext;
  17385. }
  17386. }
  17387. if (stalecontext)
  17388. ast_context_destroy(ast_context_find(stalecontext), "SIP");
  17389. }
  17390. }
  17391. /*!
  17392. * \brief Check RTP Timeout on dialogs
  17393. *
  17394. * \details This is used with ao2_callback to check rtptimeout
  17395. * rtponholdtimeout and send rtpkeepalive packets.
  17396. *
  17397. * \return CMP_MATCH for items to be unlinked from dialogs_rtpcheck.
  17398. */
  17399. static int dialog_checkrtp_cb(void *dialogobj, void *arg, int flags)
  17400. {
  17401. struct sip_pvt *dialog = dialogobj;
  17402. time_t *t = arg;
  17403. int match_status;
  17404. if (sip_pvt_trylock(dialog)) {
  17405. return 0;
  17406. }
  17407. if (dialog->rtp || dialog->vrtp) {
  17408. match_status = check_rtp_timeout(dialog, *t);
  17409. } else {
  17410. /* Dialog has no active RTP or VRTP. unlink it from dialogs_rtpcheck. */
  17411. match_status = CMP_MATCH;
  17412. }
  17413. sip_pvt_unlock(dialog);
  17414. return match_status;
  17415. }
  17416. /*!
  17417. * \brief Match dialogs that need to be destroyed
  17418. *
  17419. * \details This is used with ao2_callback to unlink/delete all dialogs that
  17420. * are marked needdestroy.
  17421. *
  17422. * \todo Re-work this to improve efficiency. Currently, this function is called
  17423. * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
  17424. * potentially even more often when the scheduler has entries to run.
  17425. */
  17426. static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
  17427. {
  17428. struct sip_pvt *dialog = dialogobj;
  17429. if (sip_pvt_trylock(dialog)) {
  17430. /* Don't block the monitor thread. This function is called often enough
  17431. * that we can wait for the next time around. */
  17432. return 0;
  17433. }
  17434. /* If we have sessions that needs to be destroyed, do it now */
  17435. /* Check if we have outstanding requests not responsed to or an active call
  17436. - if that's the case, wait with destruction */
  17437. if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
  17438. /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
  17439. if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
  17440. ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
  17441. sip_pvt_unlock(dialog);
  17442. return 0;
  17443. }
  17444. if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
  17445. ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
  17446. sip_pvt_unlock(dialog);
  17447. return 0;
  17448. }
  17449. sip_pvt_unlock(dialog);
  17450. /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
  17451. /* the CMP_MATCH will unlink this dialog from the dialog hash table */
  17452. dialog_unlink_all(dialog);
  17453. return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
  17454. }
  17455. sip_pvt_unlock(dialog);
  17456. return 0;
  17457. }
  17458. /*! \brief Remove temporary realtime objects from memory (CLI) */
  17459. /*! \todo XXXX Propably needs an overhaul after removal of the devices */
  17460. static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17461. {
  17462. struct sip_peer *peer, *pi;
  17463. int prunepeer = FALSE;
  17464. int multi = FALSE;
  17465. const char *name = NULL;
  17466. regex_t regexbuf;
  17467. int havepattern = 0;
  17468. struct ao2_iterator i;
  17469. static const char * const choices[] = { "all", "like", NULL };
  17470. char *cmplt;
  17471. if (cmd == CLI_INIT) {
  17472. e->command = "sip prune realtime [peer|all]";
  17473. e->usage =
  17474. "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
  17475. " Prunes object(s) from the cache.\n"
  17476. " Optional regular expression pattern is used to filter the objects.\n";
  17477. return NULL;
  17478. } else if (cmd == CLI_GENERATE) {
  17479. if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
  17480. cmplt = ast_cli_complete(a->word, choices, a->n);
  17481. if (!cmplt)
  17482. cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
  17483. return cmplt;
  17484. }
  17485. if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
  17486. return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
  17487. return NULL;
  17488. }
  17489. switch (a->argc) {
  17490. case 4:
  17491. name = a->argv[3];
  17492. /* we accept a name in position 3, but keywords are not good. */
  17493. if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
  17494. return CLI_SHOWUSAGE;
  17495. prunepeer = TRUE;
  17496. if (!strcasecmp(name, "all")) {
  17497. multi = TRUE;
  17498. name = NULL;
  17499. }
  17500. /* else a single name, already set */
  17501. break;
  17502. case 5:
  17503. /* sip prune realtime {peer|like} name */
  17504. name = a->argv[4];
  17505. if (!strcasecmp(a->argv[3], "peer"))
  17506. prunepeer = TRUE;
  17507. else if (!strcasecmp(a->argv[3], "like")) {
  17508. prunepeer = TRUE;
  17509. multi = TRUE;
  17510. } else
  17511. return CLI_SHOWUSAGE;
  17512. if (!strcasecmp(name, "like"))
  17513. return CLI_SHOWUSAGE;
  17514. if (!multi && !strcasecmp(name, "all")) {
  17515. multi = TRUE;
  17516. name = NULL;
  17517. }
  17518. break;
  17519. case 6:
  17520. name = a->argv[5];
  17521. multi = TRUE;
  17522. /* sip prune realtime {peer} like name */
  17523. if (strcasecmp(a->argv[4], "like"))
  17524. return CLI_SHOWUSAGE;
  17525. if (!strcasecmp(a->argv[3], "peer")) {
  17526. prunepeer = TRUE;
  17527. } else
  17528. return CLI_SHOWUSAGE;
  17529. break;
  17530. default:
  17531. return CLI_SHOWUSAGE;
  17532. }
  17533. if (multi && name) {
  17534. if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
  17535. return CLI_SHOWUSAGE;
  17536. }
  17537. havepattern = 1;
  17538. }
  17539. if (multi) {
  17540. if (prunepeer) {
  17541. int pruned = 0;
  17542. i = ao2_iterator_init(peers, 0);
  17543. while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  17544. ao2_lock(pi);
  17545. if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
  17546. ao2_unlock(pi);
  17547. sip_unref_peer(pi, "toss iterator peer ptr before continue");
  17548. continue;
  17549. };
  17550. if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  17551. pi->the_mark = 1;
  17552. pruned++;
  17553. }
  17554. ao2_unlock(pi);
  17555. sip_unref_peer(pi, "toss iterator peer ptr");
  17556. }
  17557. ao2_iterator_destroy(&i);
  17558. if (pruned) {
  17559. unlink_marked_peers_from_tables();
  17560. ast_cli(a->fd, "%d peers pruned.\n", pruned);
  17561. } else
  17562. ast_cli(a->fd, "No peers found to prune.\n");
  17563. }
  17564. } else {
  17565. if (prunepeer) {
  17566. struct sip_peer tmp;
  17567. ast_copy_string(tmp.name, name, sizeof(tmp.name));
  17568. if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
  17569. if (!ast_sockaddr_isnull(&peer->addr)) {
  17570. ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
  17571. }
  17572. if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  17573. ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
  17574. /* put it back! */
  17575. ao2_t_link(peers, peer, "link peer into peer table");
  17576. if (!ast_sockaddr_isnull(&peer->addr)) {
  17577. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  17578. }
  17579. } else
  17580. ast_cli(a->fd, "Peer '%s' pruned.\n", name);
  17581. sip_unref_peer(peer, "sip_prune_realtime: sip_unref_peer: tossing temp peer ptr");
  17582. } else
  17583. ast_cli(a->fd, "Peer '%s' not found.\n", name);
  17584. }
  17585. }
  17586. if (havepattern) {
  17587. regfree(&regexbuf);
  17588. }
  17589. return CLI_SUCCESS;
  17590. }
  17591. /*! \brief Print domain mode to cli */
  17592. static const char *domain_mode_to_text(const enum domain_mode mode)
  17593. {
  17594. switch (mode) {
  17595. case SIP_DOMAIN_AUTO:
  17596. return "[Automatic]";
  17597. case SIP_DOMAIN_CONFIG:
  17598. return "[Configured]";
  17599. }
  17600. return "";
  17601. }
  17602. /*! \brief CLI command to list local domains */
  17603. static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17604. {
  17605. struct domain *d;
  17606. #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
  17607. switch (cmd) {
  17608. case CLI_INIT:
  17609. e->command = "sip show domains";
  17610. e->usage =
  17611. "Usage: sip show domains\n"
  17612. " Lists all configured SIP local domains.\n"
  17613. " Asterisk only responds to SIP messages to local domains.\n";
  17614. return NULL;
  17615. case CLI_GENERATE:
  17616. return NULL;
  17617. }
  17618. if (AST_LIST_EMPTY(&domain_list)) {
  17619. ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
  17620. return CLI_SUCCESS;
  17621. } else {
  17622. ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
  17623. AST_LIST_LOCK(&domain_list);
  17624. AST_LIST_TRAVERSE(&domain_list, d, list)
  17625. ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
  17626. domain_mode_to_text(d->mode));
  17627. AST_LIST_UNLOCK(&domain_list);
  17628. ast_cli(a->fd, "\n");
  17629. return CLI_SUCCESS;
  17630. }
  17631. }
  17632. #undef FORMAT
  17633. /*! \brief Show SIP peers in the manager API */
  17634. static int manager_sip_show_peer(struct mansession *s, const struct message *m)
  17635. {
  17636. const char *a[4];
  17637. const char *peer;
  17638. peer = astman_get_header(m, "Peer");
  17639. if (ast_strlen_zero(peer)) {
  17640. astman_send_error(s, m, "Peer: <name> missing.");
  17641. return 0;
  17642. }
  17643. a[0] = "sip";
  17644. a[1] = "show";
  17645. a[2] = "peer";
  17646. a[3] = peer;
  17647. _sip_show_peer(1, -1, s, m, 4, a);
  17648. astman_append(s, "\r\n" );
  17649. return 0;
  17650. }
  17651. /*! \brief Show one peer in detail */
  17652. static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17653. {
  17654. switch (cmd) {
  17655. case CLI_INIT:
  17656. e->command = "sip show peer";
  17657. e->usage =
  17658. "Usage: sip show peer <name> [load]\n"
  17659. " Shows all details on one SIP peer and the current status.\n"
  17660. " Option \"load\" forces lookup of peer in realtime storage.\n";
  17661. return NULL;
  17662. case CLI_GENERATE:
  17663. return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
  17664. }
  17665. return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
  17666. }
  17667. static void send_manager_peer_status(struct mansession *s, struct sip_peer *peer, const char *idText)
  17668. {
  17669. char time[128] = "";
  17670. char status[128] = "";
  17671. if (peer->maxms) {
  17672. if (peer->lastms < 0) {
  17673. snprintf(status, sizeof(status), "PeerStatus: Unreachable\r\n");
  17674. } else if (peer->lastms > peer->maxms) {
  17675. snprintf(status, sizeof(status), "PeerStatus: Lagged\r\n");
  17676. snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
  17677. } else if (peer->lastms) {
  17678. snprintf(status, sizeof(status), "PeerStatus: Reachable\r\n");
  17679. snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
  17680. } else {
  17681. snprintf(status, sizeof(status), "PeerStatus: Unknown\r\n");
  17682. }
  17683. } else {
  17684. snprintf(status, sizeof(status), "PeerStatus: Unmonitored\r\n");
  17685. }
  17686. astman_append(s,
  17687. "Event: PeerStatus\r\n"
  17688. "Privilege: System\r\n"
  17689. "ChannelType: SIP\r\n"
  17690. "Peer: SIP/%s\r\n"
  17691. "%s"
  17692. "%s"
  17693. "%s"
  17694. "\r\n",
  17695. peer->name, status, time, idText);
  17696. }
  17697. /*! \brief Show SIP peers in the manager API */
  17698. static int manager_sip_peer_status(struct mansession *s, const struct message *m)
  17699. {
  17700. const char *id = astman_get_header(m,"ActionID");
  17701. const char *peer_name = astman_get_header(m,"Peer");
  17702. char idText[256];
  17703. struct sip_peer *peer = NULL;
  17704. int num_peers = 0;
  17705. idText[0] = '\0';
  17706. if (!ast_strlen_zero(id)) {
  17707. snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
  17708. }
  17709. if (!ast_strlen_zero(peer_name)) {
  17710. /* strip SIP/ from the begining of the peer name */
  17711. if (strlen(peer_name) >= 4 && !strncasecmp("SIP/", peer_name, 4)) {
  17712. peer_name += 4;
  17713. }
  17714. peer = sip_find_peer(peer_name, NULL, TRUE, FINDPEERS, FALSE, 0);
  17715. if (!peer) {
  17716. astman_send_error(s, m, "No such peer");
  17717. return 0;
  17718. }
  17719. }
  17720. astman_send_listack(s, m, "Peer status will follow", "start");
  17721. if (!peer) {
  17722. struct ao2_iterator i = ao2_iterator_init(peers, 0);
  17723. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table for SIPpeerstatus"))) {
  17724. ao2_lock(peer);
  17725. send_manager_peer_status(s, peer, idText);
  17726. ao2_unlock(peer);
  17727. sip_unref_peer(peer, "unref peer for SIPpeerstatus");
  17728. ++num_peers;
  17729. }
  17730. ao2_iterator_destroy(&i);
  17731. } else {
  17732. ao2_lock(peer);
  17733. send_manager_peer_status(s, peer, idText);
  17734. ao2_unlock(peer);
  17735. sip_unref_peer(peer, "unref peer for SIPpeerstatus");
  17736. ++num_peers;
  17737. }
  17738. astman_send_list_complete_start(s, m, "SIPpeerstatusComplete", num_peers);
  17739. astman_send_list_complete_end(s);
  17740. return 0;
  17741. }
  17742. static void publish_qualify_peer_done(const char *id, const char *peer)
  17743. {
  17744. RAII_VAR(struct ast_json *, body, NULL, ast_json_unref);
  17745. if (ast_strlen_zero(id)) {
  17746. body = ast_json_pack("{s: s}", "Peer", peer);
  17747. } else {
  17748. body = ast_json_pack("{s: s, s: s}", "Peer", peer, "ActionID", id);
  17749. }
  17750. if (!body) {
  17751. return;
  17752. }
  17753. ast_manager_publish_event("SIPQualifyPeerDone", EVENT_FLAG_CALL, body);
  17754. }
  17755. /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
  17756. static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
  17757. {
  17758. struct sip_peer *peer;
  17759. int load_realtime;
  17760. if (argc < 4)
  17761. return CLI_SHOWUSAGE;
  17762. load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
  17763. if ((peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
  17764. const char *id = astman_get_header(m,"ActionID");
  17765. if (type != 0) {
  17766. astman_send_ack(s, m, "SIP peer found - will qualify");
  17767. }
  17768. sip_poke_peer(peer, 1);
  17769. publish_qualify_peer_done(id, argv[3]);
  17770. sip_unref_peer(peer, "qualify: done with peer");
  17771. } else if (type == 0) {
  17772. ast_cli(fd, "Peer '%s' not found\n", argv[3]);
  17773. } else {
  17774. astman_send_error(s, m, "Peer not found");
  17775. }
  17776. return CLI_SUCCESS;
  17777. }
  17778. /*! \brief Qualify SIP peers in the manager API */
  17779. static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
  17780. {
  17781. const char *a[4];
  17782. const char *peer;
  17783. peer = astman_get_header(m, "Peer");
  17784. if (ast_strlen_zero(peer)) {
  17785. astman_send_error(s, m, "Peer: <name> missing.");
  17786. return 0;
  17787. }
  17788. a[0] = "sip";
  17789. a[1] = "qualify";
  17790. a[2] = "peer";
  17791. a[3] = peer;
  17792. _sip_qualify_peer(1, -1, s, m, 4, a);
  17793. return 0;
  17794. }
  17795. /*! \brief Send an OPTIONS packet to a SIP peer */
  17796. static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17797. {
  17798. switch (cmd) {
  17799. case CLI_INIT:
  17800. e->command = "sip qualify peer";
  17801. e->usage =
  17802. "Usage: sip qualify peer <name> [load]\n"
  17803. " Requests a response from one SIP peer and the current status.\n"
  17804. " Option \"load\" forces lookup of peer in realtime storage.\n";
  17805. return NULL;
  17806. case CLI_GENERATE:
  17807. return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
  17808. }
  17809. return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
  17810. }
  17811. /*! \brief list peer mailboxes to CLI */
  17812. static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
  17813. {
  17814. struct sip_mailbox *mailbox;
  17815. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  17816. ast_str_append(mailbox_str, 0, "%s%s",
  17817. mailbox->id,
  17818. AST_LIST_NEXT(mailbox, entry) ? "," : "");
  17819. }
  17820. }
  17821. static struct _map_x_s faxecmodes[] = {
  17822. { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
  17823. { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
  17824. { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
  17825. { -1, NULL},
  17826. };
  17827. static const char *faxec2str(int faxec)
  17828. {
  17829. return map_x_s(faxecmodes, faxec, "Unknown");
  17830. }
  17831. /*! \brief Show one peer in detail (main function) */
  17832. static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
  17833. {
  17834. char status[30] = "";
  17835. char cbuf[256];
  17836. struct sip_peer *peer;
  17837. struct ast_str *codec_buf = ast_str_alloca(64);
  17838. struct ast_variable *v;
  17839. int x = 0, load_realtime;
  17840. int realtimepeers;
  17841. realtimepeers = ast_check_realtime("sippeers");
  17842. if (argc < 4)
  17843. return CLI_SHOWUSAGE;
  17844. load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
  17845. peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
  17846. if (s) { /* Manager */
  17847. if (peer) {
  17848. const char *id = astman_get_header(m, "ActionID");
  17849. astman_append(s, "Response: Success\r\n");
  17850. if (!ast_strlen_zero(id))
  17851. astman_append(s, "ActionID: %s\r\n", id);
  17852. } else {
  17853. snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
  17854. astman_send_error(s, m, cbuf);
  17855. return CLI_SUCCESS;
  17856. }
  17857. }
  17858. if (peer && type==0 ) { /* Normal listing */
  17859. struct ast_str *mailbox_str = ast_str_alloca(512);
  17860. struct ast_str *path;
  17861. struct sip_auth_container *credentials;
  17862. ao2_lock(peer);
  17863. credentials = peer->auth;
  17864. if (credentials) {
  17865. ao2_t_ref(credentials, +1, "Ref peer auth for show");
  17866. }
  17867. ao2_unlock(peer);
  17868. ast_cli(fd, "\n\n");
  17869. ast_cli(fd, " * Name : %s\n", peer->name);
  17870. ast_cli(fd, " Description : %s\n", peer->description);
  17871. if (realtimepeers) { /* Realtime is enabled */
  17872. ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
  17873. }
  17874. ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
  17875. ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
  17876. ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
  17877. if (credentials) {
  17878. struct sip_auth *auth;
  17879. AST_LIST_TRAVERSE(&credentials->list, auth, node) {
  17880. ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s %s\n",
  17881. auth->realm,
  17882. auth->username,
  17883. !ast_strlen_zero(auth->secret)
  17884. ? "<Secret set>"
  17885. : (!ast_strlen_zero(auth->md5secret)
  17886. ? "<MD5secret set>" : "<Not set>"));
  17887. }
  17888. ao2_t_ref(credentials, -1, "Unref peer auth for show");
  17889. }
  17890. ast_cli(fd, " Context : %s\n", peer->context);
  17891. ast_cli(fd, " Record On feature : %s\n", peer->record_on_feature);
  17892. ast_cli(fd, " Record Off feature : %s\n", peer->record_off_feature);
  17893. ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
  17894. ast_cli(fd, " Language : %s\n", peer->language);
  17895. ast_cli(fd, " Tonezone : %s\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
  17896. if (!ast_strlen_zero(peer->accountcode))
  17897. ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
  17898. ast_cli(fd, " AMA flags : %s\n", ast_channel_amaflags2string(peer->amaflags));
  17899. ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
  17900. ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
  17901. if (!ast_strlen_zero(peer->fromuser))
  17902. ast_cli(fd, " FromUser : %s\n", peer->fromuser);
  17903. if (!ast_strlen_zero(peer->fromdomain))
  17904. ast_cli(fd, " FromDomain : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
  17905. ast_cli(fd, " Callgroup : ");
  17906. print_group(fd, peer->callgroup, 0);
  17907. ast_cli(fd, " Pickupgroup : ");
  17908. print_group(fd, peer->pickupgroup, 0);
  17909. ast_cli(fd, " Named Callgr : ");
  17910. print_named_groups(fd, peer->named_callgroups, 0);
  17911. ast_cli(fd, " Nam. Pickupgr: ");
  17912. print_named_groups(fd, peer->named_pickupgroups, 0);
  17913. peer_mailboxes_to_str(&mailbox_str, peer);
  17914. ast_cli(fd, " MOH Suggest : %s\n", peer->mohsuggest);
  17915. ast_cli(fd, " Mailbox : %s\n", ast_str_buffer(mailbox_str));
  17916. ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
  17917. ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
  17918. ast_cli(fd, " Call limit : %d\n", peer->call_limit);
  17919. ast_cli(fd, " Max forwards : %d\n", peer->maxforwards);
  17920. if (peer->busy_level)
  17921. ast_cli(fd, " Busy level : %d\n", peer->busy_level);
  17922. ast_cli(fd, " Dynamic : %s\n", AST_CLI_YESNO(peer->host_dynamic));
  17923. ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
  17924. ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
  17925. ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
  17926. ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
  17927. ast_cli(fd, " Force rport : %s\n", force_rport_string(peer->flags));
  17928. ast_cli(fd, " Symmetric RTP: %s\n", comedia_string(peer->flags));
  17929. ast_cli(fd, " ACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->acl) == 0));
  17930. ast_cli(fd, " DirectMedACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->directmediaacl) == 0));
  17931. ast_cli(fd, " T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
  17932. ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
  17933. ast_cli(fd, " T.38 MaxDtgrm: %u\n", peer->t38_maxdatagram);
  17934. ast_cli(fd, " DirectMedia : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
  17935. ast_cli(fd, " PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
  17936. ast_cli(fd, " User=Phone : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
  17937. ast_cli(fd, " Video Support: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) || ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS)));
  17938. ast_cli(fd, " Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
  17939. ast_cli(fd, " Ign SDP ver : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
  17940. ast_cli(fd, " Trust RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
  17941. ast_cli(fd, " Send RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
  17942. ast_cli(fd, " Path support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEPATH)));
  17943. if ((path = sip_route_list(&peer->path, 1, 0))) {
  17944. ast_cli(fd, " Path : %s\n", ast_str_buffer(path));
  17945. ast_free(path);
  17946. }
  17947. ast_cli(fd, " TrustIDOutbnd: %s\n", trust_id_outbound2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND)));
  17948. ast_cli(fd, " Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
  17949. ast_cli(fd, " Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
  17950. if (peer->outboundproxy)
  17951. ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
  17952. peer->outboundproxy->force ? "(forced)" : "");
  17953. /* - is enumerated */
  17954. ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
  17955. ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
  17956. ast_cli(fd, " Timer B : %d\n", peer->timer_b);
  17957. ast_cli(fd, " ToHost : %s\n", peer->tohost);
  17958. ast_cli(fd, " Addr->IP : %s\n", ast_sockaddr_stringify(&peer->addr));
  17959. ast_cli(fd, " Defaddr->IP : %s\n", ast_sockaddr_stringify(&peer->defaddr));
  17960. ast_cli(fd, " Prim.Transp. : %s\n", sip_get_transport(peer->socket.type));
  17961. ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
  17962. if (!ast_strlen_zero(sip_cfg.regcontext))
  17963. ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
  17964. ast_cli(fd, " Def. Username: %s\n", peer->username);
  17965. ast_cli(fd, " SIP Options : ");
  17966. if (peer->sipoptions) {
  17967. int lastoption = -1;
  17968. for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
  17969. if (sip_options[x].id != lastoption) {
  17970. if (peer->sipoptions & sip_options[x].id)
  17971. ast_cli(fd, "%s ", sip_options[x].text);
  17972. lastoption = x;
  17973. }
  17974. }
  17975. } else
  17976. ast_cli(fd, "(none)");
  17977. ast_cli(fd, "\n");
  17978. ast_cli(fd, " Codecs : %s\n", ast_format_cap_get_names(peer->caps, &codec_buf));
  17979. ast_cli(fd, " Auto-Framing : %s\n", AST_CLI_YESNO(peer->autoframing));
  17980. ast_cli(fd, " Status : ");
  17981. peer_status(peer, status, sizeof(status));
  17982. ast_cli(fd, "%s\n", status);
  17983. ast_cli(fd, " Useragent : %s\n", peer->useragent);
  17984. ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
  17985. ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
  17986. ast_cli(fd, " Keepalive : %d ms\n", peer->keepalive * 1000);
  17987. if (peer->chanvars) {
  17988. ast_cli(fd, " Variables :\n");
  17989. for (v = peer->chanvars ; v ; v = v->next)
  17990. ast_cli(fd, " %s = %s\n", v->name, v->value);
  17991. }
  17992. ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
  17993. ast_cli(fd, " Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
  17994. ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
  17995. ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
  17996. ast_cli(fd, " RTP Engine : %s\n", peer->engine);
  17997. ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
  17998. ast_cli(fd, " Use Reason : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
  17999. ast_cli(fd, " Encryption : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
  18000. ast_cli(fd, "\n");
  18001. peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer ptr");
  18002. } else if (peer && type == 1) { /* manager listing */
  18003. char buffer[256];
  18004. struct ast_str *tmp_str = ast_str_alloca(512);
  18005. astman_append(s, "Channeltype: SIP\r\n");
  18006. astman_append(s, "ObjectName: %s\r\n", peer->name);
  18007. astman_append(s, "ChanObjectType: peer\r\n");
  18008. astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
  18009. astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
  18010. astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
  18011. astman_append(s, "Context: %s\r\n", peer->context);
  18012. if (!ast_strlen_zero(peer->subscribecontext)) {
  18013. astman_append(s, "SubscribeContext: %s\r\n", peer->subscribecontext);
  18014. }
  18015. astman_append(s, "Language: %s\r\n", peer->language);
  18016. astman_append(s, "ToneZone: %s\r\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
  18017. if (!ast_strlen_zero(peer->accountcode))
  18018. astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
  18019. astman_append(s, "AMAflags: %s\r\n", ast_channel_amaflags2string(peer->amaflags));
  18020. astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
  18021. if (!ast_strlen_zero(peer->fromuser))
  18022. astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
  18023. if (!ast_strlen_zero(peer->fromdomain))
  18024. astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
  18025. astman_append(s, "Callgroup: ");
  18026. astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
  18027. astman_append(s, "Pickupgroup: ");
  18028. astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
  18029. astman_append(s, "Named Callgroup: ");
  18030. astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_callgroups));
  18031. ast_str_reset(tmp_str);
  18032. astman_append(s, "Named Pickupgroup: ");
  18033. astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_pickupgroups));
  18034. ast_str_reset(tmp_str);
  18035. astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
  18036. peer_mailboxes_to_str(&tmp_str, peer);
  18037. astman_append(s, "VoiceMailbox: %s\r\n", ast_str_buffer(tmp_str));
  18038. astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
  18039. astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
  18040. astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
  18041. astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
  18042. astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
  18043. astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
  18044. astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
  18045. astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
  18046. astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
  18047. astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
  18048. astman_append(s, "SIP-Forcerport: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
  18049. (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "A" : "a") :
  18050. (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "Y" : "N"));
  18051. astman_append(s, "SIP-Comedia: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ?
  18052. (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "A" : "a") :
  18053. (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "Y" : "N"));
  18054. astman_append(s, "ACL: %s\r\n", (ast_acl_list_is_empty(peer->acl) ? "N" : "Y"));
  18055. astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
  18056. astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
  18057. astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
  18058. astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
  18059. astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
  18060. astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
  18061. astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
  18062. astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
  18063. astman_append(s, "SIP-T.38MaxDtgrm: %u\r\n", peer->t38_maxdatagram);
  18064. astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
  18065. astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
  18066. astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
  18067. astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
  18068. astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
  18069. astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
  18070. /* - is enumerated */
  18071. astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
  18072. astman_append(s, "ToHost: %s\r\n", peer->tohost);
  18073. astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
  18074. astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_sockaddr_stringify_addr(&peer->defaddr), ast_sockaddr_port(&peer->defaddr));
  18075. astman_append(s, "Default-Username: %s\r\n", peer->username);
  18076. if (!ast_strlen_zero(sip_cfg.regcontext))
  18077. astman_append(s, "RegExtension: %s\r\n", peer->regexten);
  18078. astman_append(s, "Codecs: %s\r\n", ast_format_cap_get_names(peer->caps, &codec_buf));
  18079. astman_append(s, "Status: ");
  18080. peer_status(peer, status, sizeof(status));
  18081. astman_append(s, "%s\r\n", status);
  18082. astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
  18083. astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
  18084. astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
  18085. astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
  18086. if (peer->chanvars) {
  18087. for (v = peer->chanvars ; v ; v = v->next) {
  18088. astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
  18089. }
  18090. }
  18091. astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
  18092. astman_append(s, "Description: %s\r\n", peer->description);
  18093. peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer");
  18094. } else {
  18095. ast_cli(fd, "Peer %s not found.\n", argv[3]);
  18096. ast_cli(fd, "\n");
  18097. }
  18098. return CLI_SUCCESS;
  18099. }
  18100. /*! \brief Do completion on user name */
  18101. static char *complete_sip_user(const char *word, int state)
  18102. {
  18103. char *result = NULL;
  18104. int wordlen = strlen(word);
  18105. int which = 0;
  18106. struct ao2_iterator user_iter;
  18107. struct sip_peer *user;
  18108. user_iter = ao2_iterator_init(peers, 0);
  18109. while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
  18110. ao2_lock(user);
  18111. if (!(user->type & SIP_TYPE_USER)) {
  18112. ao2_unlock(user);
  18113. sip_unref_peer(user, "complete sip user");
  18114. continue;
  18115. }
  18116. /* locking of the object is not required because only the name and flags are being compared */
  18117. if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
  18118. result = ast_strdup(user->name);
  18119. }
  18120. ao2_unlock(user);
  18121. sip_unref_peer(user, "complete sip user");
  18122. if (result) {
  18123. break;
  18124. }
  18125. }
  18126. ao2_iterator_destroy(&user_iter);
  18127. return result;
  18128. }
  18129. /*! \brief Support routine for 'sip show user' CLI */
  18130. static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
  18131. {
  18132. if (pos == 3)
  18133. return complete_sip_user(word, state);
  18134. return NULL;
  18135. }
  18136. /*! \brief Show one user in detail */
  18137. static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18138. {
  18139. char cbuf[256];
  18140. struct sip_peer *user;
  18141. struct ast_variable *v;
  18142. int load_realtime;
  18143. switch (cmd) {
  18144. case CLI_INIT:
  18145. e->command = "sip show user";
  18146. e->usage =
  18147. "Usage: sip show user <name> [load]\n"
  18148. " Shows all details on one SIP user and the current status.\n"
  18149. " Option \"load\" forces lookup of peer in realtime storage.\n";
  18150. return NULL;
  18151. case CLI_GENERATE:
  18152. return complete_sip_show_user(a->line, a->word, a->pos, a->n);
  18153. }
  18154. if (a->argc < 4)
  18155. return CLI_SHOWUSAGE;
  18156. /* Load from realtime storage? */
  18157. load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
  18158. if ((user = sip_find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
  18159. ao2_lock(user);
  18160. ast_cli(a->fd, "\n\n");
  18161. ast_cli(a->fd, " * Name : %s\n", user->name);
  18162. ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
  18163. ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
  18164. ast_cli(a->fd, " Context : %s\n", user->context);
  18165. ast_cli(a->fd, " Language : %s\n", user->language);
  18166. if (!ast_strlen_zero(user->accountcode))
  18167. ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
  18168. ast_cli(a->fd, " AMA flags : %s\n", ast_channel_amaflags2string(user->amaflags));
  18169. ast_cli(a->fd, " Tonezone : %s\n", user->zone[0] != '\0' ? user->zone : "<Not set>");
  18170. ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
  18171. ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
  18172. ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
  18173. ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
  18174. ast_cli(a->fd, " Callgroup : ");
  18175. print_group(a->fd, user->callgroup, 0);
  18176. ast_cli(a->fd, " Pickupgroup : ");
  18177. print_group(a->fd, user->pickupgroup, 0);
  18178. ast_cli(a->fd, " Named Callgr : ");
  18179. print_named_groups(a->fd, user->named_callgroups, 0);
  18180. ast_cli(a->fd, " Nam. Pickupgr: ");
  18181. print_named_groups(a->fd, user->named_pickupgroups, 0);
  18182. ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
  18183. ast_cli(a->fd, " ACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0));
  18184. ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
  18185. ast_cli(a->fd, " Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
  18186. ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
  18187. ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
  18188. ast_cli(a->fd, " RTP Engine : %s\n", user->engine);
  18189. ast_cli(a->fd, " Auto-Framing: %s \n", AST_CLI_YESNO(user->autoframing));
  18190. if (user->chanvars) {
  18191. ast_cli(a->fd, " Variables :\n");
  18192. for (v = user->chanvars ; v ; v = v->next)
  18193. ast_cli(a->fd, " %s = %s\n", v->name, v->value);
  18194. }
  18195. ast_cli(a->fd, "\n");
  18196. ao2_unlock(user);
  18197. sip_unref_peer(user, "sip show user");
  18198. } else {
  18199. ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
  18200. ast_cli(a->fd, "\n");
  18201. }
  18202. return CLI_SUCCESS;
  18203. }
  18204. static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18205. {
  18206. struct ast_str *cbuf;
  18207. struct ast_cb_names cbnames = {
  18208. 10,
  18209. {
  18210. "retrans_pkt",
  18211. "__sip_autodestruct",
  18212. "expire_register",
  18213. "auto_congest",
  18214. "sip_reg_timeout",
  18215. "sip_poke_peer_s",
  18216. "sip_poke_peer_now",
  18217. "sip_poke_noanswer",
  18218. "sip_reregister",
  18219. "sip_reinvite_retry"
  18220. },
  18221. {
  18222. retrans_pkt,
  18223. __sip_autodestruct,
  18224. expire_register,
  18225. auto_congest,
  18226. sip_reg_timeout,
  18227. sip_poke_peer_s,
  18228. sip_poke_peer_now,
  18229. sip_poke_noanswer,
  18230. sip_reregister,
  18231. sip_reinvite_retry
  18232. }
  18233. };
  18234. switch (cmd) {
  18235. case CLI_INIT:
  18236. e->command = "sip show sched";
  18237. e->usage =
  18238. "Usage: sip show sched\n"
  18239. " Shows stats on what's in the sched queue at the moment\n";
  18240. return NULL;
  18241. case CLI_GENERATE:
  18242. return NULL;
  18243. }
  18244. cbuf = ast_str_alloca(2048);
  18245. ast_cli(a->fd, "\n");
  18246. ast_sched_report(sched, &cbuf, &cbnames);
  18247. ast_cli(a->fd, "%s", ast_str_buffer(cbuf));
  18248. return CLI_SUCCESS;
  18249. }
  18250. /*! \brief Show SIP Registry (registrations with other SIP proxies */
  18251. static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18252. {
  18253. #define FORMAT2 "%-39.39s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
  18254. #define FORMAT "%-39.39s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
  18255. char host[80];
  18256. char user[80];
  18257. char tmpdat[256];
  18258. struct ast_tm tm;
  18259. int counter = 0;
  18260. struct ao2_iterator iter;
  18261. struct sip_registry *iterator;
  18262. switch (cmd) {
  18263. case CLI_INIT:
  18264. e->command = "sip show registry";
  18265. e->usage =
  18266. "Usage: sip show registry\n"
  18267. " Lists all registration requests and status.\n";
  18268. return NULL;
  18269. case CLI_GENERATE:
  18270. return NULL;
  18271. }
  18272. if (a->argc != 3)
  18273. return CLI_SHOWUSAGE;
  18274. ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
  18275. iter = ao2_iterator_init(registry_list, 0);
  18276. while ((iterator = ao2_t_iterator_next(&iter, "sip_show_registry iter"))) {
  18277. ao2_lock(iterator);
  18278. snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
  18279. snprintf(user, sizeof(user), "%s", iterator->username);
  18280. if (!ast_strlen_zero(iterator->regdomain)) {
  18281. snprintf(tmpdat, sizeof(tmpdat), "%s", user);
  18282. snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
  18283. if (iterator->regdomainport) {
  18284. snprintf(tmpdat, sizeof(tmpdat), "%s", user);
  18285. snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
  18286. if (iterator->regtime.tv_sec) {
  18287. ast_localtime(&iterator->regtime, &tm, NULL);
  18288. ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
  18289. } else
  18290. tmpdat[0] = '\0';
  18291. ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
  18292. ao2_unlock(iterator);
  18293. ao2_t_ref(iterator, -1, "sip_show_registry iter");
  18294. counter++;
  18295. }
  18296. ao2_iterator_destroy(&iter);
  18297. ast_cli(a->fd, "%d SIP registrations.\n", counter);
  18298. return CLI_SUCCESS;
  18299. #undef FORMAT
  18300. #undef FORMAT2
  18301. }
  18302. /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
  18303. \note This function does not tell the SIP device what's going on,
  18304. so use it with great care.
  18305. */
  18306. static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18307. {
  18308. struct sip_peer *peer;
  18309. int load_realtime = 0;
  18310. switch (cmd) {
  18311. case CLI_INIT:
  18312. e->command = "sip unregister";
  18313. e->usage =
  18314. "Usage: sip unregister <peer>\n"
  18315. " Unregister (force expiration) a SIP peer from the registry\n";
  18316. return NULL;
  18317. case CLI_GENERATE:
  18318. return complete_sip_unregister(a->line, a->word, a->pos, a->n);
  18319. }
  18320. if (a->argc != 3)
  18321. return CLI_SHOWUSAGE;
  18322. if ((peer = sip_find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
  18323. if (peer->expire > 0) {
  18324. AST_SCHED_DEL_UNREF(sched, peer->expire,
  18325. sip_unref_peer(peer, "remove register expire ref"));
  18326. expire_register(sip_ref_peer(peer, "ref for expire_register"));
  18327. ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
  18328. } else {
  18329. ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
  18330. }
  18331. sip_unref_peer(peer, "sip_unregister: sip_unref_peer via sip_unregister: done with peer from sip_find_peer call");
  18332. } else {
  18333. ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
  18334. }
  18335. return CLI_SUCCESS;
  18336. }
  18337. /*! \brief Callback for show_chanstats */
  18338. static int show_chanstats_cb(void *__cur, void *__arg, int flags)
  18339. {
  18340. #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
  18341. #define FORMAT "%-15.15s %-11.11s %-8.8s %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.4lf %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.4lf\n"
  18342. struct sip_pvt *cur = __cur;
  18343. struct ast_rtp_instance_stats stats;
  18344. char durbuf[10];
  18345. struct ast_channel *c;
  18346. struct __show_chan_arg *arg = __arg;
  18347. int fd = arg->fd;
  18348. sip_pvt_lock(cur);
  18349. c = cur->owner;
  18350. if (cur->subscribed != NONE) {
  18351. /* Subscriptions */
  18352. sip_pvt_unlock(cur);
  18353. return 0; /* don't care, we scan all channels */
  18354. }
  18355. if (!cur->rtp) {
  18356. if (sipdebug) {
  18357. ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n",
  18358. ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
  18359. invitestate2string[cur->invitestate].desc,
  18360. "-- No RTP active");
  18361. }
  18362. sip_pvt_unlock(cur);
  18363. return 0; /* don't care, we scan all channels */
  18364. }
  18365. if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
  18366. sip_pvt_unlock(cur);
  18367. ast_log(LOG_WARNING, "Could not get RTP stats.\n");
  18368. return 0;
  18369. }
  18370. if (c) {
  18371. ast_format_duration_hh_mm_ss(ast_channel_get_duration(c), durbuf, sizeof(durbuf));
  18372. } else {
  18373. durbuf[0] = '\0';
  18374. }
  18375. ast_cli(fd, FORMAT,
  18376. ast_sockaddr_stringify_addr(&cur->sa),
  18377. cur->callid,
  18378. durbuf,
  18379. stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
  18380. stats.rxcount > (unsigned int) 100000 ? "K":" ",
  18381. stats.rxploss,
  18382. (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
  18383. stats.rxjitter,
  18384. stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
  18385. stats.txcount > (unsigned int) 100000 ? "K":" ",
  18386. stats.txploss,
  18387. stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
  18388. stats.txjitter
  18389. );
  18390. arg->numchans++;
  18391. sip_pvt_unlock(cur);
  18392. return 0; /* don't care, we scan all channels */
  18393. }
  18394. /*! \brief SIP show channelstats CLI (main function) */
  18395. static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18396. {
  18397. struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
  18398. switch (cmd) {
  18399. case CLI_INIT:
  18400. e->command = "sip show channelstats";
  18401. e->usage =
  18402. "Usage: sip show channelstats\n"
  18403. " Lists all currently active SIP channel's RTCP statistics.\n"
  18404. " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
  18405. return NULL;
  18406. case CLI_GENERATE:
  18407. return NULL;
  18408. }
  18409. if (a->argc != 3)
  18410. return CLI_SHOWUSAGE;
  18411. ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
  18412. /* iterate on the container and invoke the callback on each item */
  18413. ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
  18414. ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
  18415. return CLI_SUCCESS;
  18416. }
  18417. #undef FORMAT
  18418. #undef FORMAT2
  18419. /*! \brief List global settings for the SIP channel */
  18420. static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18421. {
  18422. int realtimepeers;
  18423. int realtimeregs;
  18424. struct ast_str *codec_buf = ast_str_alloca(64);
  18425. const char *msg; /* temporary msg pointer */
  18426. struct sip_auth_container *credentials;
  18427. switch (cmd) {
  18428. case CLI_INIT:
  18429. e->command = "sip show settings";
  18430. e->usage =
  18431. "Usage: sip show settings\n"
  18432. " Provides detailed list of the configuration of the SIP channel.\n";
  18433. return NULL;
  18434. case CLI_GENERATE:
  18435. return NULL;
  18436. }
  18437. if (a->argc != 3)
  18438. return CLI_SHOWUSAGE;
  18439. realtimepeers = ast_check_realtime("sippeers");
  18440. realtimeregs = ast_check_realtime("sipregs");
  18441. ast_mutex_lock(&authl_lock);
  18442. credentials = authl;
  18443. if (credentials) {
  18444. ao2_t_ref(credentials, +1, "Ref global auth for show");
  18445. }
  18446. ast_mutex_unlock(&authl_lock);
  18447. ast_cli(a->fd, "\n\nGlobal Settings:\n");
  18448. ast_cli(a->fd, "----------------\n");
  18449. ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_sockaddr_stringify(&bindaddr));
  18450. if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
  18451. ast_cli(a->fd, " ** Additional Info:\n");
  18452. ast_cli(a->fd, " [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
  18453. }
  18454. ast_cli(a->fd, " TCP SIP Bindaddress: %s\n",
  18455. sip_cfg.tcp_enabled != FALSE ?
  18456. ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
  18457. "Disabled");
  18458. ast_cli(a->fd, " TLS SIP Bindaddress: %s\n",
  18459. default_tls_cfg.enabled != FALSE ?
  18460. ast_sockaddr_stringify(&sip_tls_desc.local_address) :
  18461. "Disabled");
  18462. ast_cli(a->fd, " RTP Bindaddress: %s\n",
  18463. !ast_sockaddr_isnull(&rtpbindaddr) ?
  18464. ast_sockaddr_stringify_addr(&rtpbindaddr) :
  18465. "Disabled");
  18466. ast_cli(a->fd, " Videosupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
  18467. ast_cli(a->fd, " Textsupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
  18468. ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
  18469. ast_cli(a->fd, " AutoCreate Peer: %s\n", autocreatepeer2str(sip_cfg.autocreatepeer));
  18470. ast_cli(a->fd, " Match Auth Username: %s\n", AST_CLI_YESNO(global_match_auth_username));
  18471. ast_cli(a->fd, " Allow unknown access: %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
  18472. ast_cli(a->fd, " Allow subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
  18473. ast_cli(a->fd, " Allow overlap dialing: %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
  18474. ast_cli(a->fd, " Allow promisc. redir: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
  18475. ast_cli(a->fd, " Enable call counters: %s\n", AST_CLI_YESNO(global_callcounter));
  18476. ast_cli(a->fd, " SIP domain support: %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
  18477. ast_cli(a->fd, " Path support : %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEPATH)));
  18478. ast_cli(a->fd, " Realm. auth: %s\n", AST_CLI_YESNO(credentials != NULL));
  18479. if (credentials) {
  18480. struct sip_auth *auth;
  18481. AST_LIST_TRAVERSE(&credentials->list, auth, node) {
  18482. ast_cli(a->fd, " Realm. auth entry: Realm %-15.15s User %-10.20s %s\n",
  18483. auth->realm,
  18484. auth->username,
  18485. !ast_strlen_zero(auth->secret)
  18486. ? "<Secret set>"
  18487. : (!ast_strlen_zero(auth->md5secret)
  18488. ? "<MD5secret set>" : "<Not set>"));
  18489. }
  18490. ao2_t_ref(credentials, -1, "Unref global auth for show");
  18491. }
  18492. ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
  18493. ast_cli(a->fd, " Use domains as realms: %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
  18494. ast_cli(a->fd, " Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
  18495. ast_cli(a->fd, " URI user is phone no: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
  18496. ast_cli(a->fd, " Always auth rejects: %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
  18497. ast_cli(a->fd, " Direct RTP setup: %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
  18498. ast_cli(a->fd, " User Agent: %s\n", global_useragent);
  18499. ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
  18500. ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
  18501. ast_cli(a->fd, " Reg. context: %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
  18502. ast_cli(a->fd, " Regexten on Qualify: %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
  18503. ast_cli(a->fd, " Trust RPID: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_TRUSTRPID)));
  18504. ast_cli(a->fd, " Send RPID: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_SENDRPID)));
  18505. ast_cli(a->fd, " Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
  18506. ast_cli(a->fd, " Send Diversion: %s\n", AST_CLI_YESNO(sip_cfg.send_diversion));
  18507. ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
  18508. if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
  18509. ast_cli(a->fd, " From: Domain: %s:%d\n", default_fromdomain, default_fromdomainport);
  18510. } else {
  18511. ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
  18512. }
  18513. ast_cli(a->fd, " Record SIP history: %s\n", AST_CLI_ONOFF(recordhistory));
  18514. ast_cli(a->fd, " Auth. Failure Events: %s\n", AST_CLI_ONOFF(global_authfailureevents));
  18515. ast_cli(a->fd, " T.38 support: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
  18516. ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
  18517. ast_cli(a->fd, " T.38 MaxDtgrm: %u\n", global_t38_maxdatagram);
  18518. if (!realtimepeers && !realtimeregs)
  18519. ast_cli(a->fd, " SIP realtime: Disabled\n" );
  18520. else
  18521. ast_cli(a->fd, " SIP realtime: Enabled\n" );
  18522. ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
  18523. ast_cli(a->fd, " Q.850 Reason header: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
  18524. ast_cli(a->fd, " Store SIP_CAUSE: %s\n", AST_CLI_YESNO(global_store_sip_cause));
  18525. ast_cli(a->fd, "\nNetwork QoS Settings:\n");
  18526. ast_cli(a->fd, "---------------------------\n");
  18527. ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
  18528. ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
  18529. ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
  18530. ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
  18531. ast_cli(a->fd, " 802.1p CoS SIP: %u\n", global_cos_sip);
  18532. ast_cli(a->fd, " 802.1p CoS RTP audio: %u\n", global_cos_audio);
  18533. ast_cli(a->fd, " 802.1p CoS RTP video: %u\n", global_cos_video);
  18534. ast_cli(a->fd, " 802.1p CoS RTP text: %u\n", global_cos_text);
  18535. ast_cli(a->fd, " Jitterbuffer enabled: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
  18536. if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
  18537. ast_cli(a->fd, " Jitterbuffer forced: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
  18538. ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
  18539. ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
  18540. ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
  18541. if (!strcasecmp(global_jbconf.impl, "adaptive")) {
  18542. ast_cli(a->fd, " Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
  18543. }
  18544. ast_cli(a->fd, " Jitterbuffer log: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
  18545. }
  18546. ast_cli(a->fd, "\nNetwork Settings:\n");
  18547. ast_cli(a->fd, "---------------------------\n");
  18548. /* determine if/how SIP address can be remapped */
  18549. if (localaddr == NULL)
  18550. msg = "Disabled, no localnet list";
  18551. else if (ast_sockaddr_isnull(&externaddr))
  18552. msg = "Disabled";
  18553. else if (!ast_strlen_zero(externhost))
  18554. msg = "Enabled using externhost";
  18555. else
  18556. msg = "Enabled using externaddr";
  18557. ast_cli(a->fd, " SIP address remapping: %s\n", msg);
  18558. ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
  18559. ast_cli(a->fd, " Externaddr: %s\n", ast_sockaddr_stringify(&externaddr));
  18560. ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
  18561. {
  18562. struct ast_ha *d;
  18563. const char *prefix = "Localnet:";
  18564. for (d = localaddr; d ; prefix = "", d = d->next) {
  18565. const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
  18566. const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
  18567. ast_cli(a->fd, " %-24s%s/%s\n", prefix, addr, mask);
  18568. }
  18569. }
  18570. ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
  18571. ast_cli(a->fd, "---------------------------\n");
  18572. ast_cli(a->fd, " Codecs: %s\n", ast_format_cap_get_names(sip_cfg.caps, &codec_buf));
  18573. ast_cli(a->fd, " Relax DTMF: %s\n", AST_CLI_YESNO(global_relaxdtmf));
  18574. ast_cli(a->fd, " RFC2833 Compensation: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
  18575. ast_cli(a->fd, " Symmetric RTP: %s\n", comedia_string(global_flags));
  18576. ast_cli(a->fd, " Compact SIP headers: %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
  18577. ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
  18578. ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
  18579. ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
  18580. ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
  18581. ast_cli(a->fd, " DNS SRV lookup: %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
  18582. ast_cli(a->fd, " Pedantic SIP support: %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
  18583. ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
  18584. ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
  18585. ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
  18586. ast_cli(a->fd, " Sub. min duration %d secs\n", min_subexpiry);
  18587. ast_cli(a->fd, " Sub. max duration: %d secs\n", max_subexpiry);
  18588. ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
  18589. ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
  18590. ast_cli(a->fd, " Outbound reg. retry 403:%d\n", global_reg_retry_403);
  18591. ast_cli(a->fd, " Notify ringing state: %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
  18592. if (sip_cfg.notifyringing) {
  18593. ast_cli(a->fd, " Include CID: %s%s\n",
  18594. AST_CLI_YESNO(sip_cfg.notifycid),
  18595. sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
  18596. }
  18597. ast_cli(a->fd, " Notify hold state: %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
  18598. ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
  18599. ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
  18600. ast_cli(a->fd, " Auto-Framing: %s\n", AST_CLI_YESNO(global_autoframing));
  18601. ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
  18602. sip_cfg.outboundproxy.force ? "(forced)" : "");
  18603. ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
  18604. ast_cli(a->fd, " Session Refresher: %s\n", strefresherparam2str(global_st_refresher));
  18605. ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
  18606. ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
  18607. ast_cli(a->fd, " Timer T1: %d\n", global_t1);
  18608. ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
  18609. ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
  18610. ast_cli(a->fd, " No premature media: %s\n", AST_CLI_YESNO(global_prematuremediafilter));
  18611. ast_cli(a->fd, " Max forwards: %d\n", sip_cfg.default_max_forwards);
  18612. ast_cli(a->fd, "\nDefault Settings:\n");
  18613. ast_cli(a->fd, "-----------------\n");
  18614. ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
  18615. ast_cli(a->fd, " Outbound transport: %s\n", sip_get_transport(default_primary_transport));
  18616. ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
  18617. ast_cli(a->fd, " Record on feature: %s\n", sip_cfg.default_record_on_feature);
  18618. ast_cli(a->fd, " Record off feature: %s\n", sip_cfg.default_record_off_feature);
  18619. ast_cli(a->fd, " Force rport: %s\n", force_rport_string(global_flags));
  18620. ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
  18621. ast_cli(a->fd, " Qualify: %d\n", default_qualify);
  18622. ast_cli(a->fd, " Keepalive: %d\n", default_keepalive);
  18623. ast_cli(a->fd, " Use ClientCode: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
  18624. ast_cli(a->fd, " Progress inband: %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_NO)));
  18625. ast_cli(a->fd, " Language: %s\n", default_language);
  18626. ast_cli(a->fd, " Tone zone: %s\n", default_zone[0] != '\0' ? default_zone : "<Not set>");
  18627. ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
  18628. ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
  18629. ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
  18630. if (realtimepeers || realtimeregs) {
  18631. ast_cli(a->fd, "\nRealtime SIP Settings:\n");
  18632. ast_cli(a->fd, "----------------------\n");
  18633. ast_cli(a->fd, " Realtime Peers: %s\n", AST_CLI_YESNO(realtimepeers));
  18634. ast_cli(a->fd, " Realtime Regs: %s\n", AST_CLI_YESNO(realtimeregs));
  18635. ast_cli(a->fd, " Cache Friends: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
  18636. ast_cli(a->fd, " Update: %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
  18637. ast_cli(a->fd, " Ignore Reg. Expire: %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
  18638. ast_cli(a->fd, " Save sys. name: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
  18639. ast_cli(a->fd, " Save path header: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_path));
  18640. ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
  18641. }
  18642. ast_cli(a->fd, "\n----\n");
  18643. return CLI_SUCCESS;
  18644. }
  18645. static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18646. {
  18647. #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
  18648. char host[80];
  18649. struct ao2_iterator iter;
  18650. struct sip_subscription_mwi *iterator;
  18651. switch (cmd) {
  18652. case CLI_INIT:
  18653. e->command = "sip show mwi";
  18654. e->usage =
  18655. "Usage: sip show mwi\n"
  18656. " Provides a list of MWI subscriptions and status.\n";
  18657. return NULL;
  18658. case CLI_GENERATE:
  18659. return NULL;
  18660. }
  18661. ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
  18662. iter = ao2_iterator_init(subscription_mwi_list, 0);
  18663. while ((iterator = ao2_t_iterator_next(&iter, "sip_show_mwi iter"))) {
  18664. ao2_lock(iterator);
  18665. snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
  18666. ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
  18667. ao2_unlock(iterator);
  18668. ao2_t_ref(iterator, -1, "sip_show_mwi iter");
  18669. }
  18670. ao2_iterator_destroy(&iter);
  18671. return CLI_SUCCESS;
  18672. #undef FORMAT
  18673. }
  18674. /*! \brief Show subscription type in string format */
  18675. static const char *subscription_type2str(enum subscriptiontype subtype)
  18676. {
  18677. int i;
  18678. for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
  18679. if (subscription_types[i].type == subtype) {
  18680. return subscription_types[i].text;
  18681. }
  18682. }
  18683. return subscription_types[0].text;
  18684. }
  18685. /*! \brief Find subscription type in array */
  18686. static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
  18687. {
  18688. int i;
  18689. for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
  18690. if (subscription_types[i].type == subtype) {
  18691. return &subscription_types[i];
  18692. }
  18693. }
  18694. return &subscription_types[0];
  18695. }
  18696. /*
  18697. * We try to structure all functions that loop on data structures as
  18698. * a handler for individual entries, and a mainloop that iterates
  18699. * on the main data structure. This way, moving the code to containers
  18700. * that support iteration through callbacks will be a lot easier.
  18701. */
  18702. #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
  18703. #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
  18704. #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-10.10s %-10.10s\n"
  18705. #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s %-10.10s\n"
  18706. /*! \brief callback for show channel|subscription */
  18707. static int show_channels_cb(void *__cur, void *__arg, int flags)
  18708. {
  18709. struct sip_pvt *cur = __cur;
  18710. struct __show_chan_arg *arg = __arg;
  18711. const struct ast_sockaddr *dst;
  18712. sip_pvt_lock(cur);
  18713. dst = sip_real_dst(cur);
  18714. /* XXX indentation preserved to reduce diff. Will be fixed later */
  18715. if (cur->subscribed == NONE && !arg->subscriptions) {
  18716. /* set if SIP transfer in progress */
  18717. const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
  18718. struct ast_str *codec_buf = ast_str_alloca(64);
  18719. ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
  18720. S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
  18721. cur->callid,
  18722. cur->owner ? ast_format_cap_get_names(ast_channel_nativeformats(cur->owner), &codec_buf) : "(nothing)",
  18723. AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
  18724. cur->needdestroy ? "(d)" : "",
  18725. cur->lastmsg ,
  18726. referstatus,
  18727. cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
  18728. );
  18729. arg->numchans++;
  18730. }
  18731. if (cur->subscribed != NONE && arg->subscriptions) {
  18732. struct ast_str *mailbox_str = ast_str_alloca(512);
  18733. if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
  18734. peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
  18735. ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
  18736. S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
  18737. cur->callid,
  18738. /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
  18739. cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
  18740. cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
  18741. subscription_type2str(cur->subscribed),
  18742. cur->subscribed == MWI_NOTIFICATION ? S_OR(ast_str_buffer(mailbox_str), "<none>") : "<none>",
  18743. cur->expiry
  18744. );
  18745. arg->numchans++;
  18746. }
  18747. sip_pvt_unlock(cur);
  18748. return 0; /* don't care, we scan all channels */
  18749. }
  18750. /*! \brief CLI for show channels or subscriptions.
  18751. * This is a new-style CLI handler so a single function contains
  18752. * the prototype for the function, the 'generator' to produce multiple
  18753. * entries in case it is required, and the actual handler for the command.
  18754. */
  18755. static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18756. {
  18757. struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
  18758. if (cmd == CLI_INIT) {
  18759. e->command = "sip show {channels|subscriptions}";
  18760. e->usage =
  18761. "Usage: sip show channels\n"
  18762. " Lists all currently active SIP calls (dialogs).\n"
  18763. "Usage: sip show subscriptions\n"
  18764. " Lists active SIP subscriptions.\n";
  18765. return NULL;
  18766. } else if (cmd == CLI_GENERATE)
  18767. return NULL;
  18768. if (a->argc != e->args)
  18769. return CLI_SHOWUSAGE;
  18770. arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
  18771. if (!arg.subscriptions)
  18772. ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
  18773. else
  18774. ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
  18775. /* iterate on the container and invoke the callback on each item */
  18776. ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
  18777. /* print summary information */
  18778. ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
  18779. (arg.subscriptions ? "subscription" : "dialog"),
  18780. ESS(arg.numchans)); /* ESS(n) returns an "s" if n>1 */
  18781. return CLI_SUCCESS;
  18782. #undef FORMAT
  18783. #undef FORMAT2
  18784. #undef FORMAT3
  18785. }
  18786. /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
  18787. * This is in charge of generating all strings that match a prefix in the
  18788. * given position. As many functions of this kind, each invokation has
  18789. * O(state) time complexity so be careful in using it.
  18790. */
  18791. static char *complete_sipch(const char *line, const char *word, int pos, int state)
  18792. {
  18793. int which=0;
  18794. struct sip_pvt *cur;
  18795. char *c = NULL;
  18796. int wordlen = strlen(word);
  18797. struct ao2_iterator i;
  18798. if (pos != 3) {
  18799. return NULL;
  18800. }
  18801. i = ao2_iterator_init(dialogs, 0);
  18802. while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  18803. sip_pvt_lock(cur);
  18804. if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
  18805. c = ast_strdup(cur->callid);
  18806. sip_pvt_unlock(cur);
  18807. dialog_unref(cur, "drop ref in iterator loop break");
  18808. break;
  18809. }
  18810. sip_pvt_unlock(cur);
  18811. dialog_unref(cur, "drop ref in iterator loop");
  18812. }
  18813. ao2_iterator_destroy(&i);
  18814. return c;
  18815. }
  18816. /*! \brief Do completion on peer name */
  18817. static char *complete_sip_peer(const char *word, int state, int flags2)
  18818. {
  18819. char *result = NULL;
  18820. int wordlen = strlen(word);
  18821. int which = 0;
  18822. struct ao2_iterator i = ao2_iterator_init(peers, 0);
  18823. struct sip_peer *peer;
  18824. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  18825. /* locking of the object is not required because only the name and flags are being compared */
  18826. if (!strncasecmp(word, peer->name, wordlen) &&
  18827. (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
  18828. ++which > state)
  18829. result = ast_strdup(peer->name);
  18830. sip_unref_peer(peer, "toss iterator peer ptr before break");
  18831. if (result) {
  18832. break;
  18833. }
  18834. }
  18835. ao2_iterator_destroy(&i);
  18836. return result;
  18837. }
  18838. /*! \brief Do completion on registered peer name */
  18839. static char *complete_sip_registered_peer(const char *word, int state, int flags2)
  18840. {
  18841. char *result = NULL;
  18842. int wordlen = strlen(word);
  18843. int which = 0;
  18844. struct ao2_iterator i;
  18845. struct sip_peer *peer;
  18846. i = ao2_iterator_init(peers, 0);
  18847. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  18848. if (!strncasecmp(word, peer->name, wordlen) &&
  18849. (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
  18850. ++which > state && peer->expire > 0)
  18851. result = ast_strdup(peer->name);
  18852. if (result) {
  18853. sip_unref_peer(peer, "toss iterator peer ptr before break");
  18854. break;
  18855. }
  18856. sip_unref_peer(peer, "toss iterator peer ptr");
  18857. }
  18858. ao2_iterator_destroy(&i);
  18859. return result;
  18860. }
  18861. /*! \brief Support routine for 'sip show history' CLI */
  18862. static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
  18863. {
  18864. if (pos == 3)
  18865. return complete_sipch(line, word, pos, state);
  18866. return NULL;
  18867. }
  18868. /*! \brief Support routine for 'sip show peer' CLI */
  18869. static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
  18870. {
  18871. if (pos == 3) {
  18872. return complete_sip_peer(word, state, 0);
  18873. }
  18874. return NULL;
  18875. }
  18876. /*! \brief Support routine for 'sip unregister' CLI */
  18877. static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
  18878. {
  18879. if (pos == 2)
  18880. return complete_sip_registered_peer(word, state, 0);
  18881. return NULL;
  18882. }
  18883. /*! \brief Support routine for 'sip notify' CLI */
  18884. static char *complete_sip_notify(const char *line, const char *word, int pos, int state)
  18885. {
  18886. char *c = NULL;
  18887. if (pos == 2) {
  18888. int which = 0;
  18889. char *cat = NULL;
  18890. int wordlen = strlen(word);
  18891. /* do completion for notify type */
  18892. if (!notify_types)
  18893. return NULL;
  18894. while ( (cat = ast_category_browse(notify_types, cat)) ) {
  18895. if (!strncasecmp(word, cat, wordlen) && ++which > state) {
  18896. c = ast_strdup(cat);
  18897. break;
  18898. }
  18899. }
  18900. return c;
  18901. }
  18902. if (pos > 2)
  18903. return complete_sip_peer(word, state, 0);
  18904. return NULL;
  18905. }
  18906. /*! \brief Show details of one active dialog */
  18907. static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18908. {
  18909. struct sip_pvt *cur;
  18910. size_t len;
  18911. int found = 0;
  18912. struct ao2_iterator i;
  18913. switch (cmd) {
  18914. case CLI_INIT:
  18915. e->command = "sip show channel";
  18916. e->usage =
  18917. "Usage: sip show channel <call-id>\n"
  18918. " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
  18919. return NULL;
  18920. case CLI_GENERATE:
  18921. return complete_sipch(a->line, a->word, a->pos, a->n);
  18922. }
  18923. if (a->argc != 4)
  18924. return CLI_SHOWUSAGE;
  18925. len = strlen(a->argv[3]);
  18926. i = ao2_iterator_init(dialogs, 0);
  18927. while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  18928. sip_pvt_lock(cur);
  18929. if (!strncasecmp(cur->callid, a->argv[3], len)) {
  18930. struct ast_str *strbuf;
  18931. struct ast_str *codec_buf = ast_str_alloca(64);
  18932. ast_cli(a->fd, "\n");
  18933. if (cur->subscribed != NONE) {
  18934. ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
  18935. } else {
  18936. ast_cli(a->fd, " * SIP Call\n");
  18937. }
  18938. ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
  18939. ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
  18940. ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? ast_channel_name(cur->owner) : "<none>");
  18941. ast_cli(a->fd, " Our Codec Capability: %s\n", ast_format_cap_get_names(cur->caps, &codec_buf));
  18942. ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
  18943. ast_cli(a->fd, " Their Codec Capability: %s\n", ast_format_cap_get_names(cur->peercaps, &codec_buf));
  18944. ast_cli(a->fd, " Joint Codec Capability: %s\n", ast_format_cap_get_names(cur->jointcaps, &codec_buf));
  18945. ast_cli(a->fd, " Format: %s\n", cur->owner ? ast_format_cap_get_names(ast_channel_nativeformats(cur->owner), &codec_buf) : "(nothing)" );
  18946. ast_cli(a->fd, " T.38 support %s\n", AST_CLI_YESNO(cur->udptl != NULL));
  18947. ast_cli(a->fd, " Video support %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
  18948. ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
  18949. ast_cli(a->fd, " Theoretical Address: %s\n", ast_sockaddr_stringify(&cur->sa));
  18950. ast_cli(a->fd, " Received Address: %s\n", ast_sockaddr_stringify(&cur->recv));
  18951. ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
  18952. ast_cli(a->fd, " Force rport: %s\n", force_rport_string(cur->flags));
  18953. if (ast_sockaddr_isnull(&cur->redirip)) {
  18954. ast_cli(a->fd,
  18955. " Audio IP: %s (local)\n",
  18956. ast_sockaddr_stringify_addr(&cur->ourip));
  18957. } else {
  18958. ast_cli(a->fd,
  18959. " Audio IP: %s (Outside bridge)\n",
  18960. ast_sockaddr_stringify_addr(&cur->redirip));
  18961. }
  18962. ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
  18963. ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
  18964. ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
  18965. if (!ast_strlen_zero(cur->username)) {
  18966. ast_cli(a->fd, " Username: %s\n", cur->username);
  18967. }
  18968. if (!ast_strlen_zero(cur->peername)) {
  18969. ast_cli(a->fd, " Peername: %s\n", cur->peername);
  18970. }
  18971. if (!ast_strlen_zero(cur->uri)) {
  18972. ast_cli(a->fd, " Original uri: %s\n", cur->uri);
  18973. }
  18974. if (!ast_strlen_zero(cur->cid_num)) {
  18975. ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
  18976. }
  18977. ast_cli(a->fd, " Need Destroy: %s\n", AST_CLI_YESNO(cur->needdestroy));
  18978. ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
  18979. ast_cli(a->fd, " Promiscuous Redir: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
  18980. if ((strbuf = sip_route_list(&cur->route, 1, 0))) {
  18981. ast_cli(a->fd, " Route: %s\n", ast_str_buffer(strbuf));
  18982. ast_free(strbuf);
  18983. }
  18984. ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
  18985. ast_cli(a->fd, " SIP Options: ");
  18986. if (cur->sipoptions) {
  18987. int x;
  18988. for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
  18989. if (cur->sipoptions & sip_options[x].id)
  18990. ast_cli(a->fd, "%s ", sip_options[x].text);
  18991. }
  18992. ast_cli(a->fd, "\n");
  18993. } else {
  18994. ast_cli(a->fd, "(none)\n");
  18995. }
  18996. if (!cur->stimer) {
  18997. ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
  18998. } else {
  18999. ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
  19000. if (cur->stimer->st_active == TRUE) {
  19001. ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
  19002. ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
  19003. ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
  19004. ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
  19005. ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
  19006. ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
  19007. ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
  19008. ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
  19009. }
  19010. }
  19011. /* add transport and media types */
  19012. ast_cli(a->fd, " Transport: %s\n", ast_transport2str(cur->socket.type));
  19013. ast_cli(a->fd, " Media: %s\n", cur->srtp ? "SRTP" : cur->rtp ? "RTP" : "None");
  19014. ast_cli(a->fd, "\n\n");
  19015. found++;
  19016. }
  19017. sip_pvt_unlock(cur);
  19018. ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
  19019. }
  19020. ao2_iterator_destroy(&i);
  19021. if (!found) {
  19022. ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
  19023. }
  19024. return CLI_SUCCESS;
  19025. }
  19026. /*! \brief Show history details of one dialog */
  19027. static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  19028. {
  19029. struct sip_pvt *cur;
  19030. size_t len;
  19031. int found = 0;
  19032. struct ao2_iterator i;
  19033. switch (cmd) {
  19034. case CLI_INIT:
  19035. e->command = "sip show history";
  19036. e->usage =
  19037. "Usage: sip show history <call-id>\n"
  19038. " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
  19039. return NULL;
  19040. case CLI_GENERATE:
  19041. return complete_sip_show_history(a->line, a->word, a->pos, a->n);
  19042. }
  19043. if (a->argc != 4) {
  19044. return CLI_SHOWUSAGE;
  19045. }
  19046. if (!recordhistory) {
  19047. ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
  19048. }
  19049. len = strlen(a->argv[3]);
  19050. i = ao2_iterator_init(dialogs, 0);
  19051. while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  19052. sip_pvt_lock(cur);
  19053. if (!strncasecmp(cur->callid, a->argv[3], len)) {
  19054. struct sip_history *hist;
  19055. int x = 0;
  19056. ast_cli(a->fd, "\n");
  19057. if (cur->subscribed != NONE) {
  19058. ast_cli(a->fd, " * Subscription\n");
  19059. } else {
  19060. ast_cli(a->fd, " * SIP Call\n");
  19061. }
  19062. if (cur->history) {
  19063. AST_LIST_TRAVERSE(cur->history, hist, list)
  19064. ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
  19065. }
  19066. if (x == 0) {
  19067. ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
  19068. }
  19069. found++;
  19070. }
  19071. sip_pvt_unlock(cur);
  19072. ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
  19073. }
  19074. ao2_iterator_destroy(&i);
  19075. if (!found) {
  19076. ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
  19077. }
  19078. return CLI_SUCCESS;
  19079. }
  19080. /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
  19081. static void sip_dump_history(struct sip_pvt *dialog)
  19082. {
  19083. int x = 0;
  19084. struct sip_history *hist;
  19085. static int errmsg = 0;
  19086. if (!dialog) {
  19087. return;
  19088. }
  19089. if (!option_debug && !sipdebug) {
  19090. if (!errmsg) {
  19091. ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
  19092. errmsg = 1;
  19093. }
  19094. return;
  19095. }
  19096. ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
  19097. if (dialog->subscribed) {
  19098. ast_debug(1, " * Subscription\n");
  19099. } else {
  19100. ast_debug(1, " * SIP Call\n");
  19101. }
  19102. if (dialog->history) {
  19103. AST_LIST_TRAVERSE(dialog->history, hist, list)
  19104. ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
  19105. }
  19106. if (!x) {
  19107. ast_debug(1, "Call '%s' has no history\n", dialog->callid);
  19108. }
  19109. ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
  19110. }
  19111. /*! \brief Receive SIP INFO Message */
  19112. static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
  19113. {
  19114. const char *buf = "";
  19115. unsigned int event;
  19116. const char *c = sip_get_header(req, "Content-Type");
  19117. /* Need to check the media/type */
  19118. if (!strcasecmp(c, "application/dtmf-relay") ||
  19119. !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
  19120. !strcasecmp(c, "application/dtmf")) {
  19121. unsigned int duration = 0;
  19122. if (!p->owner) { /* not a PBX call */
  19123. transmit_response(p, "481 Call leg/transaction does not exist", req);
  19124. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  19125. return;
  19126. }
  19127. /* If dtmf-relay or vnd.nortelnetworks.digits, parse the signal and duration;
  19128. * otherwise use the body as the signal */
  19129. if (strcasecmp(c, "application/dtmf")) {
  19130. const char *tmp;
  19131. if (ast_strlen_zero(buf = get_content_line(req, "Signal", '='))
  19132. && ast_strlen_zero(buf = get_content_line(req, "d", '='))) {
  19133. ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
  19134. "call %s\n", p->callid);
  19135. transmit_response(p, "200 OK", req);
  19136. return;
  19137. }
  19138. if (!ast_strlen_zero((tmp = get_content_line(req, "Duration", '=')))) {
  19139. sscanf(tmp, "%30u", &duration);
  19140. }
  19141. } else {
  19142. /* Type is application/dtmf, simply use what's in the message body */
  19143. buf = get_content(req);
  19144. }
  19145. /* An empty message body requires us to send a 200 OK */
  19146. if (ast_strlen_zero(buf)) {
  19147. transmit_response(p, "200 OK", req);
  19148. return;
  19149. }
  19150. if (!duration) {
  19151. duration = 100; /* 100 ms */
  19152. }
  19153. if (buf[0] == '*') {
  19154. event = 10;
  19155. } else if (buf[0] == '#') {
  19156. event = 11;
  19157. } else if (buf[0] == '!') {
  19158. event = 16;
  19159. } else if ('A' <= buf[0] && buf[0] <= 'D') {
  19160. event = 12 + buf[0] - 'A';
  19161. } else if ('a' <= buf[0] && buf[0] <= 'd') {
  19162. event = 12 + buf[0] - 'a';
  19163. } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
  19164. ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
  19165. "value for INFO message on call %s\n", p->callid);
  19166. transmit_response(p, "200 OK", req);
  19167. return;
  19168. }
  19169. if (event == 16) {
  19170. /* send a FLASH event */
  19171. struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
  19172. ast_queue_frame(p->owner, &f);
  19173. if (sipdebug) {
  19174. ast_verbose("* DTMF-relay event received: FLASH\n");
  19175. }
  19176. } else {
  19177. /* send a DTMF event */
  19178. struct ast_frame f = { AST_FRAME_DTMF, };
  19179. if (event < 10) {
  19180. f.subclass.integer = '0' + event;
  19181. } else if (event == 10) {
  19182. f.subclass.integer = '*';
  19183. } else if (event == 11) {
  19184. f.subclass.integer = '#';
  19185. } else {
  19186. f.subclass.integer = 'A' + (event - 12);
  19187. }
  19188. f.len = duration;
  19189. ast_queue_frame(p->owner, &f);
  19190. if (sipdebug) {
  19191. ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
  19192. }
  19193. }
  19194. transmit_response(p, "200 OK", req);
  19195. return;
  19196. } else if (!strcasecmp(c, "application/media_control+xml")) {
  19197. /* Eh, we'll just assume it's a fast picture update for now */
  19198. if (p->owner) {
  19199. ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
  19200. }
  19201. transmit_response(p, "200 OK", req);
  19202. return;
  19203. } else if (!ast_strlen_zero(c = sip_get_header(req, "X-ClientCode"))) {
  19204. /* Client code (from SNOM phone) */
  19205. if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
  19206. if (p->owner) {
  19207. ast_cdr_setuserfield(ast_channel_name(p->owner), c);
  19208. }
  19209. transmit_response(p, "200 OK", req);
  19210. } else {
  19211. transmit_response(p, "403 Forbidden", req);
  19212. }
  19213. return;
  19214. } else if (!ast_strlen_zero(c = sip_get_header(req, "Record"))) {
  19215. /* INFO messages generated by some phones to start/stop recording
  19216. * on phone calls.
  19217. */
  19218. char feat[AST_FEATURE_MAX_LEN];
  19219. int feat_res = -1;
  19220. int j;
  19221. struct ast_frame f = { AST_FRAME_DTMF, };
  19222. int suppress_warning = 0; /* Supress warning if the feature is blank */
  19223. if (!p->owner) { /* not a PBX call */
  19224. transmit_response(p, "481 Call leg/transaction does not exist", req);
  19225. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  19226. return;
  19227. }
  19228. /* first, get the feature string, if it exists */
  19229. if (p->relatedpeer) {
  19230. if (!strcasecmp(c, "on")) {
  19231. if (ast_strlen_zero(p->relatedpeer->record_on_feature)) {
  19232. suppress_warning = 1;
  19233. } else {
  19234. feat_res = ast_get_feature(p->owner, p->relatedpeer->record_on_feature, feat, sizeof(feat));
  19235. }
  19236. } else if (!strcasecmp(c, "off")) {
  19237. if (ast_strlen_zero(p->relatedpeer->record_off_feature)) {
  19238. suppress_warning = 1;
  19239. } else {
  19240. feat_res = ast_get_feature(p->owner, p->relatedpeer->record_off_feature, feat, sizeof(feat));
  19241. }
  19242. } else {
  19243. ast_log(LOG_ERROR, "Received INFO requesting to record with invalid value: %s\n", c);
  19244. }
  19245. }
  19246. if (feat_res || ast_strlen_zero(feat)) {
  19247. if (!suppress_warning) {
  19248. ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
  19249. }
  19250. /* 403 means that we don't support this feature, so don't request it again */
  19251. transmit_response(p, "403 Forbidden", req);
  19252. return;
  19253. }
  19254. /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
  19255. f.len = 100;
  19256. for (j = 0; j < strlen(feat); j++) {
  19257. f.subclass.integer = feat[j];
  19258. ast_queue_frame(p->owner, &f);
  19259. if (sipdebug) {
  19260. ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
  19261. }
  19262. }
  19263. ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
  19264. transmit_response(p, "200 OK", req);
  19265. return;
  19266. } else if (ast_strlen_zero(c = sip_get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
  19267. /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
  19268. transmit_response(p, "200 OK", req);
  19269. return;
  19270. }
  19271. /* Other type of INFO message, not really understood by Asterisk */
  19272. ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
  19273. transmit_response(p, "415 Unsupported media type", req);
  19274. return;
  19275. }
  19276. /*! \brief Enable SIP Debugging for a single IP */
  19277. static char *sip_do_debug_ip(int fd, const char *arg)
  19278. {
  19279. if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
  19280. return CLI_SHOWUSAGE;
  19281. }
  19282. ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
  19283. sipdebug |= sip_debug_console;
  19284. return CLI_SUCCESS;
  19285. }
  19286. /*! \brief Turn on SIP debugging for a given peer */
  19287. static char *sip_do_debug_peer(int fd, const char *arg)
  19288. {
  19289. struct sip_peer *peer = sip_find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
  19290. if (!peer) {
  19291. ast_cli(fd, "No such peer '%s'\n", arg);
  19292. } else if (ast_sockaddr_isnull(&peer->addr)) {
  19293. ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
  19294. } else {
  19295. ast_sockaddr_copy(&debugaddr, &peer->addr);
  19296. ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
  19297. sipdebug |= sip_debug_console;
  19298. }
  19299. if (peer) {
  19300. sip_unref_peer(peer, "sip_do_debug_peer: sip_unref_peer, from sip_find_peer call");
  19301. }
  19302. return CLI_SUCCESS;
  19303. }
  19304. /*! \brief Turn on SIP debugging (CLI command) */
  19305. static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  19306. {
  19307. int oldsipdebug = sipdebug & sip_debug_console;
  19308. const char *what;
  19309. if (cmd == CLI_INIT) {
  19310. e->command = "sip set debug {on|off|ip|peer}";
  19311. e->usage =
  19312. "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
  19313. " Globally disables dumping of SIP packets,\n"
  19314. " or enables it either globally or for a (single)\n"
  19315. " IP address or registered peer.\n";
  19316. return NULL;
  19317. } else if (cmd == CLI_GENERATE) {
  19318. if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
  19319. return complete_sip_peer(a->word, a->n, 0);
  19320. return NULL;
  19321. }
  19322. what = a->argv[e->args-1]; /* guaranteed to exist */
  19323. if (a->argc == e->args) { /* on/off */
  19324. if (!strcasecmp(what, "on")) {
  19325. sipdebug |= sip_debug_console;
  19326. sipdebug_text = 1; /*! \note this can be a special debug command - "sip debug text" or something */
  19327. memset(&debugaddr, 0, sizeof(debugaddr));
  19328. ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
  19329. return CLI_SUCCESS;
  19330. } else if (!strcasecmp(what, "off")) {
  19331. sipdebug &= ~sip_debug_console;
  19332. sipdebug_text = 0;
  19333. ast_cli(a->fd, "SIP Debugging Disabled\n");
  19334. return CLI_SUCCESS;
  19335. }
  19336. } else if (a->argc == e->args + 1) { /* ip/peer */
  19337. if (!strcasecmp(what, "ip"))
  19338. return sip_do_debug_ip(a->fd, a->argv[e->args]);
  19339. else if (!strcasecmp(what, "peer"))
  19340. return sip_do_debug_peer(a->fd, a->argv[e->args]);
  19341. }
  19342. return CLI_SHOWUSAGE; /* default, failure */
  19343. }
  19344. /*! \brief Cli command to send SIP notify to peer */
  19345. static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  19346. {
  19347. struct ast_variable *varlist;
  19348. int i;
  19349. switch (cmd) {
  19350. case CLI_INIT:
  19351. e->command = "sip notify";
  19352. e->usage =
  19353. "Usage: sip notify <type> <peer> [<peer>...]\n"
  19354. " Send a NOTIFY message to a SIP peer or peers\n"
  19355. " Message types are defined in sip_notify.conf\n";
  19356. return NULL;
  19357. case CLI_GENERATE:
  19358. return complete_sip_notify(a->line, a->word, a->pos, a->n);
  19359. }
  19360. if (a->argc < 4)
  19361. return CLI_SHOWUSAGE;
  19362. if (!notify_types) {
  19363. ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
  19364. return CLI_FAILURE;
  19365. }
  19366. varlist = ast_variable_browse(notify_types, a->argv[2]);
  19367. if (!varlist) {
  19368. ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
  19369. return CLI_FAILURE;
  19370. }
  19371. for (i = 3; i < a->argc; i++) {
  19372. struct sip_pvt *p;
  19373. char buf[512];
  19374. struct ast_variable *header, *var;
  19375. if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, 0))) {
  19376. ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
  19377. return CLI_FAILURE;
  19378. }
  19379. if (create_addr(p, a->argv[i], NULL, 1)) {
  19380. /* Maybe they're not registered, etc. */
  19381. dialog_unlink_all(p);
  19382. dialog_unref(p, "unref dialog inside for loop" );
  19383. /* sip_destroy(p); */
  19384. ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
  19385. continue;
  19386. }
  19387. /* Notify is outgoing call */
  19388. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  19389. sip_notify_alloc(p);
  19390. p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
  19391. for (var = varlist; var; var = var->next) {
  19392. ast_copy_string(buf, var->value, sizeof(buf));
  19393. ast_unescape_semicolon(buf);
  19394. if (!strcasecmp(var->name, "Content")) {
  19395. if (ast_str_strlen(p->notify->content))
  19396. ast_str_append(&p->notify->content, 0, "\r\n");
  19397. ast_str_append(&p->notify->content, 0, "%s", buf);
  19398. } else if (!strcasecmp(var->name, "Content-Length")) {
  19399. ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
  19400. } else {
  19401. header->next = ast_variable_new(var->name, buf, "");
  19402. header = header->next;
  19403. }
  19404. }
  19405. /* Now that we have the peer's address, set our ip and change callid */
  19406. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  19407. build_via(p);
  19408. change_callid_pvt(p, NULL);
  19409. ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
  19410. sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
  19411. transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
  19412. dialog_unref(p, "bump down the count of p since we're done with it.");
  19413. }
  19414. return CLI_SUCCESS;
  19415. }
  19416. /*! \brief Enable/Disable SIP History logging (CLI) */
  19417. static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  19418. {
  19419. switch (cmd) {
  19420. case CLI_INIT:
  19421. e->command = "sip set history {on|off}";
  19422. e->usage =
  19423. "Usage: sip set history {on|off}\n"
  19424. " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
  19425. " Use 'sip show history' to view the history of a call number.\n";
  19426. return NULL;
  19427. case CLI_GENERATE:
  19428. return NULL;
  19429. }
  19430. if (a->argc != e->args)
  19431. return CLI_SHOWUSAGE;
  19432. if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
  19433. recordhistory = TRUE;
  19434. ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
  19435. } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
  19436. recordhistory = FALSE;
  19437. ast_cli(a->fd, "SIP History Recording Disabled\n");
  19438. } else {
  19439. return CLI_SHOWUSAGE;
  19440. }
  19441. return CLI_SUCCESS;
  19442. }
  19443. /*! \brief Authenticate for outbound registration */
  19444. static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
  19445. {
  19446. char *header, *respheader;
  19447. char digest[1024];
  19448. p->authtries++;
  19449. sip_auth_headers(code, &header, &respheader);
  19450. memset(digest, 0, sizeof(digest));
  19451. if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
  19452. /* There's nothing to use for authentication */
  19453. /* No digest challenge in request */
  19454. if (sip_debug_test_pvt(p) && p->registry)
  19455. ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
  19456. /* No old challenge */
  19457. return -1;
  19458. }
  19459. if (p->do_history)
  19460. append_history(p, "RegistryAuth", "Try: %d", p->authtries);
  19461. if (sip_debug_test_pvt(p) && p->registry)
  19462. ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
  19463. return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
  19464. }
  19465. /*! \brief Add authentication on outbound SIP packet */
  19466. static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
  19467. {
  19468. char *header, *respheader;
  19469. char digest[1024];
  19470. if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
  19471. return -2;
  19472. p->authtries++;
  19473. sip_auth_headers(code, &header, &respheader);
  19474. ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
  19475. memset(digest, 0, sizeof(digest));
  19476. if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
  19477. /* No way to authenticate */
  19478. return -1;
  19479. }
  19480. /* Now we have a reply digest */
  19481. p->options->auth = digest;
  19482. p->options->authheader = respheader;
  19483. return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
  19484. }
  19485. /*! \brief reply to authentication for outbound registrations
  19486. \return Returns -1 if we have no auth
  19487. \note This is used for register= servers in sip.conf, SIP proxies we register
  19488. with for receiving calls from. */
  19489. static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
  19490. {
  19491. char tmp[512];
  19492. char *c;
  19493. char oldnonce[256];
  19494. /* table of recognised keywords, and places where they should be copied */
  19495. const struct x {
  19496. const char *key;
  19497. const ast_string_field *field;
  19498. } *i, keys[] = {
  19499. { "realm=", &p->realm },
  19500. { "nonce=", &p->nonce },
  19501. { "opaque=", &p->opaque },
  19502. { "qop=", &p->qop },
  19503. { "domain=", &p->domain },
  19504. { NULL, 0 },
  19505. };
  19506. ast_copy_string(tmp, sip_get_header(req, header), sizeof(tmp));
  19507. if (ast_strlen_zero(tmp))
  19508. return -1;
  19509. if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
  19510. ast_log(LOG_WARNING, "missing Digest.\n");
  19511. return -1;
  19512. }
  19513. c = tmp + strlen("Digest ");
  19514. ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
  19515. while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
  19516. for (i = keys; i->key != NULL; i++) {
  19517. char *src, *separator;
  19518. if (strncasecmp(c, i->key, strlen(i->key)) != 0)
  19519. continue;
  19520. /* Found. Skip keyword, take text in quotes or up to the separator. */
  19521. c += strlen(i->key);
  19522. if (*c == '"') {
  19523. src = ++c;
  19524. separator = "\"";
  19525. } else {
  19526. src = c;
  19527. separator = ",";
  19528. }
  19529. strsep(&c, separator); /* clear separator and move ptr */
  19530. ast_string_field_ptr_set(p, i->field, src);
  19531. break;
  19532. }
  19533. if (i->key == NULL) /* not found, try ',' */
  19534. strsep(&c, ",");
  19535. }
  19536. /* Reset nonce count */
  19537. if (strcmp(p->nonce, oldnonce))
  19538. p->noncecount = 0;
  19539. /* Save auth data for following registrations */
  19540. if (p->registry) {
  19541. struct sip_registry *r = p->registry;
  19542. if (strcmp(r->nonce, p->nonce)) {
  19543. ast_string_field_set(r, realm, p->realm);
  19544. ast_string_field_set(r, nonce, p->nonce);
  19545. ast_string_field_set(r, authdomain, p->domain);
  19546. ast_string_field_set(r, opaque, p->opaque);
  19547. ast_string_field_set(r, qop, p->qop);
  19548. r->noncecount = 0;
  19549. }
  19550. }
  19551. return build_reply_digest(p, sipmethod, digest, digest_len);
  19552. }
  19553. /*! \brief Build reply digest
  19554. \return Returns -1 if we have no auth
  19555. \note Build digest challenge for authentication of registrations and calls
  19556. Also used for authentication of BYE
  19557. */
  19558. static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
  19559. {
  19560. char a1[256];
  19561. char a2[256];
  19562. char a1_hash[256];
  19563. char a2_hash[256];
  19564. char resp[256];
  19565. char resp_hash[256];
  19566. char uri[256];
  19567. char opaque[256] = "";
  19568. char cnonce[80];
  19569. const char *username;
  19570. const char *secret;
  19571. const char *md5secret;
  19572. struct sip_auth *auth; /* Realm authentication credential */
  19573. struct sip_auth_container *credentials;
  19574. if (!ast_strlen_zero(p->domain))
  19575. snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == AST_TRANSPORT_TLS ? "sips" : "sip", p->domain);
  19576. else if (!ast_strlen_zero(p->uri))
  19577. ast_copy_string(uri, p->uri, sizeof(uri));
  19578. else
  19579. snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == AST_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
  19580. snprintf(cnonce, sizeof(cnonce), "%08lx", (unsigned long)ast_random());
  19581. /* Check if we have peer credentials */
  19582. ao2_lock(p);
  19583. credentials = p->peerauth;
  19584. if (credentials) {
  19585. ao2_t_ref(credentials, +1, "Ref peer auth for digest");
  19586. }
  19587. ao2_unlock(p);
  19588. auth = find_realm_authentication(credentials, p->realm);
  19589. if (!auth) {
  19590. /* If not, check global credentials */
  19591. if (credentials) {
  19592. ao2_t_ref(credentials, -1, "Unref peer auth for digest");
  19593. }
  19594. ast_mutex_lock(&authl_lock);
  19595. credentials = authl;
  19596. if (credentials) {
  19597. ao2_t_ref(credentials, +1, "Ref global auth for digest");
  19598. }
  19599. ast_mutex_unlock(&authl_lock);
  19600. auth = find_realm_authentication(credentials, p->realm);
  19601. }
  19602. if (auth) {
  19603. ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
  19604. username = auth->username;
  19605. secret = auth->secret;
  19606. md5secret = auth->md5secret;
  19607. if (sipdebug)
  19608. ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
  19609. } else {
  19610. /* No authentication, use peer or register= config */
  19611. username = p->authname;
  19612. secret = p->relatedpeer
  19613. && !ast_strlen_zero(p->relatedpeer->remotesecret)
  19614. ? p->relatedpeer->remotesecret : p->peersecret;
  19615. md5secret = p->peermd5secret;
  19616. }
  19617. if (ast_strlen_zero(username)) {
  19618. /* We have no authentication */
  19619. if (credentials) {
  19620. ao2_t_ref(credentials, -1, "Unref auth for digest");
  19621. }
  19622. return -1;
  19623. }
  19624. /* Calculate SIP digest response */
  19625. snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
  19626. snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
  19627. if (!ast_strlen_zero(md5secret))
  19628. ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
  19629. else
  19630. ast_md5_hash(a1_hash, a1);
  19631. ast_md5_hash(a2_hash, a2);
  19632. p->noncecount++;
  19633. if (!ast_strlen_zero(p->qop))
  19634. snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, (unsigned)p->noncecount, cnonce, "auth", a2_hash);
  19635. else
  19636. snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
  19637. ast_md5_hash(resp_hash, resp);
  19638. /* only include the opaque string if it's set */
  19639. if (!ast_strlen_zero(p->opaque)) {
  19640. snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
  19641. }
  19642. /* XXX We hard code our qop to "auth" for now. XXX */
  19643. if (!ast_strlen_zero(p->qop))
  19644. snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, (unsigned)p->noncecount);
  19645. else
  19646. snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);
  19647. append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
  19648. if (credentials) {
  19649. ao2_t_ref(credentials, -1, "Unref auth for digest");
  19650. }
  19651. return 0;
  19652. }
  19653. /*! \brief Read SIP header (dialplan function) */
  19654. static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
  19655. {
  19656. struct sip_pvt *p;
  19657. const char *content = NULL;
  19658. AST_DECLARE_APP_ARGS(args,
  19659. AST_APP_ARG(header);
  19660. AST_APP_ARG(number);
  19661. );
  19662. int i, number, start = 0;
  19663. if (!chan) {
  19664. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", function);
  19665. return -1;
  19666. }
  19667. if (ast_strlen_zero(data)) {
  19668. ast_log(LOG_WARNING, "This function requires a header name.\n");
  19669. return -1;
  19670. }
  19671. ast_channel_lock(chan);
  19672. if (!IS_SIP_TECH(ast_channel_tech(chan))) {
  19673. ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
  19674. ast_channel_unlock(chan);
  19675. return -1;
  19676. }
  19677. AST_STANDARD_APP_ARGS(args, data);
  19678. if (!args.number) {
  19679. number = 1;
  19680. } else {
  19681. sscanf(args.number, "%30d", &number);
  19682. if (number < 1)
  19683. number = 1;
  19684. }
  19685. p = ast_channel_tech_pvt(chan);
  19686. /* If there is no private structure, this channel is no longer alive */
  19687. if (!p) {
  19688. ast_channel_unlock(chan);
  19689. return -1;
  19690. }
  19691. for (i = 0; i < number; i++)
  19692. content = __get_header(&p->initreq, args.header, &start);
  19693. if (ast_strlen_zero(content)) {
  19694. ast_channel_unlock(chan);
  19695. return -1;
  19696. }
  19697. ast_copy_string(buf, content, len);
  19698. ast_channel_unlock(chan);
  19699. return 0;
  19700. }
  19701. static struct ast_custom_function sip_header_function = {
  19702. .name = "SIP_HEADER",
  19703. .read = func_header_read,
  19704. };
  19705. /*! \brief Dial plan function to check if domain is local */
  19706. static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  19707. {
  19708. if (ast_strlen_zero(data)) {
  19709. ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
  19710. return -1;
  19711. }
  19712. if (check_sip_domain(data, NULL, 0))
  19713. ast_copy_string(buf, data, len);
  19714. else
  19715. buf[0] = '\0';
  19716. return 0;
  19717. }
  19718. static struct ast_custom_function checksipdomain_function = {
  19719. .name = "CHECKSIPDOMAIN",
  19720. .read = func_check_sipdomain,
  19721. };
  19722. /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
  19723. static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  19724. {
  19725. struct sip_peer *peer;
  19726. char *colname;
  19727. if ((colname = strchr(data, ','))) {
  19728. *colname++ = '\0';
  19729. } else {
  19730. colname = "ip";
  19731. }
  19732. if (!(peer = sip_find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
  19733. return -1;
  19734. if (!strcasecmp(colname, "ip")) {
  19735. ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
  19736. } else if (!strcasecmp(colname, "port")) {
  19737. snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
  19738. } else if (!strcasecmp(colname, "status")) {
  19739. peer_status(peer, buf, len);
  19740. } else if (!strcasecmp(colname, "language")) {
  19741. ast_copy_string(buf, peer->language, len);
  19742. } else if (!strcasecmp(colname, "regexten")) {
  19743. ast_copy_string(buf, peer->regexten, len);
  19744. } else if (!strcasecmp(colname, "limit")) {
  19745. snprintf(buf, len, "%d", peer->call_limit);
  19746. } else if (!strcasecmp(colname, "busylevel")) {
  19747. snprintf(buf, len, "%d", peer->busy_level);
  19748. } else if (!strcasecmp(colname, "curcalls")) {
  19749. snprintf(buf, len, "%d", peer->inuse);
  19750. } else if (!strcasecmp(colname, "maxforwards")) {
  19751. snprintf(buf, len, "%d", peer->maxforwards);
  19752. } else if (!strcasecmp(colname, "accountcode")) {
  19753. ast_copy_string(buf, peer->accountcode, len);
  19754. } else if (!strcasecmp(colname, "callgroup")) {
  19755. ast_print_group(buf, len, peer->callgroup);
  19756. } else if (!strcasecmp(colname, "pickupgroup")) {
  19757. ast_print_group(buf, len, peer->pickupgroup);
  19758. } else if (!strcasecmp(colname, "namedcallgroup")) {
  19759. struct ast_str *tmp_str = ast_str_create(1024);
  19760. if (tmp_str) {
  19761. ast_copy_string(buf, ast_print_namedgroups(&tmp_str, peer->named_callgroups), len);
  19762. ast_free(tmp_str);
  19763. }
  19764. } else if (!strcasecmp(colname, "namedpickupgroup")) {
  19765. struct ast_str *tmp_str = ast_str_create(1024);
  19766. if (tmp_str) {
  19767. ast_copy_string(buf, ast_print_namedgroups(&tmp_str, peer->named_pickupgroups), len);
  19768. ast_free(tmp_str);
  19769. }
  19770. } else if (!strcasecmp(colname, "useragent")) {
  19771. ast_copy_string(buf, peer->useragent, len);
  19772. } else if (!strcasecmp(colname, "mailbox")) {
  19773. struct ast_str *mailbox_str = ast_str_alloca(512);
  19774. peer_mailboxes_to_str(&mailbox_str, peer);
  19775. ast_copy_string(buf, ast_str_buffer(mailbox_str), len);
  19776. } else if (!strcasecmp(colname, "context")) {
  19777. ast_copy_string(buf, peer->context, len);
  19778. } else if (!strcasecmp(colname, "expire")) {
  19779. snprintf(buf, len, "%d", peer->expire);
  19780. } else if (!strcasecmp(colname, "dynamic")) {
  19781. ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
  19782. } else if (!strcasecmp(colname, "callerid_name")) {
  19783. ast_copy_string(buf, peer->cid_name, len);
  19784. } else if (!strcasecmp(colname, "callerid_num")) {
  19785. ast_copy_string(buf, peer->cid_num, len);
  19786. } else if (!strcasecmp(colname, "codecs")) {
  19787. struct ast_str *codec_buf = ast_str_alloca(64);
  19788. ast_format_cap_get_names(peer->caps, &codec_buf);
  19789. ast_copy_string(buf, ast_str_buffer(codec_buf), len);
  19790. } else if (!strcasecmp(colname, "encryption")) {
  19791. snprintf(buf, len, "%u", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
  19792. } else if (!strncasecmp(colname, "chanvar[", 8)) {
  19793. char *chanvar=colname + 8;
  19794. struct ast_variable *v;
  19795. chanvar = strsep(&chanvar, "]");
  19796. for (v = peer->chanvars ; v ; v = v->next) {
  19797. if (!strcasecmp(v->name, chanvar)) {
  19798. ast_copy_string(buf, v->value, len);
  19799. }
  19800. }
  19801. } else if (!strncasecmp(colname, "codec[", 6)) {
  19802. char *codecnum;
  19803. struct ast_format *codec;
  19804. codecnum = colname + 6; /* move past the '[' */
  19805. codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
  19806. codec = ast_format_cap_get_format(peer->caps, atoi(codecnum));
  19807. if (codec) {
  19808. ast_copy_string(buf, ast_format_get_name(codec), len);
  19809. ao2_ref(codec, -1);
  19810. } else {
  19811. buf[0] = '\0';
  19812. }
  19813. } else {
  19814. buf[0] = '\0';
  19815. }
  19816. sip_unref_peer(peer, "sip_unref_peer from function_sippeer, just before return");
  19817. return 0;
  19818. }
  19819. /*! \brief Structure to declare a dialplan function: SIPPEER */
  19820. static struct ast_custom_function sippeer_function = {
  19821. .name = "SIPPEER",
  19822. .read = function_sippeer,
  19823. };
  19824. /*! \brief update redirecting information for a channel based on headers
  19825. *
  19826. */
  19827. static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
  19828. struct ast_party_redirecting *redirecting,
  19829. struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
  19830. {
  19831. char *redirecting_from_name = NULL;
  19832. char *redirecting_from_number = NULL;
  19833. char *redirecting_to_name = NULL;
  19834. char *redirecting_to_number = NULL;
  19835. char *reason_str = NULL;
  19836. int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
  19837. int is_response = req->method == SIP_RESPONSE;
  19838. int res = 0;
  19839. res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason, &reason_str);
  19840. if (res == -1) {
  19841. if (is_response) {
  19842. get_name_and_number(sip_get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
  19843. } else {
  19844. return;
  19845. }
  19846. }
  19847. /* At this point, all redirecting "from" info should be filled in appropriately
  19848. * on to the "to" info
  19849. */
  19850. if (is_response) {
  19851. parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
  19852. } else {
  19853. get_name_and_number(sip_get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
  19854. }
  19855. if (!ast_strlen_zero(redirecting_from_number)) {
  19856. ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
  19857. update_redirecting->from.number = 1;
  19858. redirecting->from.number.valid = 1;
  19859. ast_free(redirecting->from.number.str);
  19860. redirecting->from.number.str = redirecting_from_number;
  19861. }
  19862. if (!ast_strlen_zero(redirecting_from_name)) {
  19863. ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
  19864. update_redirecting->from.name = 1;
  19865. redirecting->from.name.valid = 1;
  19866. ast_free(redirecting->from.name.str);
  19867. redirecting->from.name.str = redirecting_from_name;
  19868. }
  19869. if (!ast_strlen_zero(p->cid_tag)) {
  19870. ast_free(redirecting->from.tag);
  19871. redirecting->from.tag = ast_strdup(p->cid_tag);
  19872. ast_free(redirecting->to.tag);
  19873. redirecting->to.tag = ast_strdup(p->cid_tag);
  19874. }
  19875. if (!ast_strlen_zero(redirecting_to_number)) {
  19876. ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
  19877. update_redirecting->to.number = 1;
  19878. redirecting->to.number.valid = 1;
  19879. ast_free(redirecting->to.number.str);
  19880. redirecting->to.number.str = redirecting_to_number;
  19881. }
  19882. if (!ast_strlen_zero(redirecting_to_name)) {
  19883. ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
  19884. update_redirecting->to.name = 1;
  19885. redirecting->to.name.valid = 1;
  19886. ast_free(redirecting->to.name.str);
  19887. redirecting->to.name.str = redirecting_to_name;
  19888. }
  19889. redirecting->reason.code = reason;
  19890. if (reason_str) {
  19891. ast_debug(3, "Got redirecting reason %s\n", reason_str);
  19892. ast_free(redirecting->reason.str);
  19893. redirecting->reason.str = reason_str;
  19894. }
  19895. }
  19896. /*! \brief Parse 302 Moved temporalily response
  19897. \todo XXX Doesn't redirect over TLS on sips: uri's.
  19898. If we get a redirect to a SIPS: uri, this needs to be going back to the
  19899. dialplan (this is a request for a secure signalling path).
  19900. Note that transport=tls is deprecated, but we need to support it on incoming requests.
  19901. */
  19902. static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
  19903. {
  19904. char contact[SIPBUFSIZE];
  19905. char *contact_name = NULL;
  19906. char *contact_number = NULL;
  19907. char *separator, *trans;
  19908. char *domain;
  19909. enum ast_transport transport = AST_TRANSPORT_UDP;
  19910. ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
  19911. if ((separator = strchr(contact, ',')))
  19912. *separator = '\0';
  19913. contact_number = get_in_brackets(contact);
  19914. if ((trans = strcasestr(contact_number, ";transport="))) {
  19915. trans += 11;
  19916. if ((separator = strchr(trans, ';')))
  19917. *separator = '\0';
  19918. if (!strncasecmp(trans, "tcp", 3))
  19919. transport = AST_TRANSPORT_TCP;
  19920. else if (!strncasecmp(trans, "tls", 3))
  19921. transport = AST_TRANSPORT_TLS;
  19922. else {
  19923. if (strncasecmp(trans, "udp", 3))
  19924. ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
  19925. /* This will assume UDP for all unknown transports */
  19926. transport = AST_TRANSPORT_UDP;
  19927. }
  19928. }
  19929. contact_number = remove_uri_parameters(contact_number);
  19930. if (p->socket.tcptls_session) {
  19931. ao2_ref(p->socket.tcptls_session, -1);
  19932. p->socket.tcptls_session = NULL;
  19933. } else if (p->socket.ws_session) {
  19934. ast_websocket_unref(p->socket.ws_session);
  19935. p->socket.ws_session = NULL;
  19936. }
  19937. set_socket_transport(&p->socket, transport);
  19938. if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
  19939. char *host = NULL;
  19940. if (!strncasecmp(contact_number, "sip:", 4))
  19941. contact_number += 4;
  19942. else if (!strncasecmp(contact_number, "sips:", 5))
  19943. contact_number += 5;
  19944. separator = strchr(contact_number, '/');
  19945. if (separator)
  19946. *separator = '\0';
  19947. if ((host = strchr(contact_number, '@'))) {
  19948. *host++ = '\0';
  19949. ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, sip_get_transport(transport), host);
  19950. if (p->owner)
  19951. ast_channel_call_forward_build(p->owner, "SIP/%s::::%s@%s", contact_number, sip_get_transport(transport), host);
  19952. } else {
  19953. ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", sip_get_transport(transport), contact_number);
  19954. if (p->owner)
  19955. ast_channel_call_forward_build(p->owner, "SIP/::::%s@%s", sip_get_transport(transport), contact_number);
  19956. }
  19957. } else {
  19958. separator = strchr(contact, '@');
  19959. if (separator) {
  19960. *separator++ = '\0';
  19961. domain = separator;
  19962. } else {
  19963. /* No username part */
  19964. domain = contact;
  19965. }
  19966. separator = strchr(contact, '/'); /* WHEN do we hae a forward slash in the URI? */
  19967. if (separator)
  19968. *separator = '\0';
  19969. if (!strncasecmp(contact_number, "sip:", 4))
  19970. contact_number += 4;
  19971. else if (!strncasecmp(contact_number, "sips:", 5))
  19972. contact_number += 5;
  19973. separator = strchr(contact_number, ';'); /* And username ; parameters? */
  19974. if (separator)
  19975. *separator = '\0';
  19976. ast_uri_decode(contact_number, ast_uri_sip_user);
  19977. if (set_call_forward) {
  19978. ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
  19979. if (p->owner) {
  19980. pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
  19981. ast_channel_call_forward_set(p->owner, contact_number);
  19982. }
  19983. }
  19984. }
  19985. /* We've gotten the number for the contact, now get the name */
  19986. if (*contact == '\"') {
  19987. contact_name = contact + 1;
  19988. if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
  19989. ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
  19990. }
  19991. *separator = '\0';
  19992. }
  19993. if (name && !ast_strlen_zero(contact_name)) {
  19994. *name = ast_strdup(contact_name);
  19995. }
  19996. if (number) {
  19997. *number = ast_strdup(contact_number);
  19998. }
  19999. }
  20000. /*! \brief Check pending actions on SIP call
  20001. *
  20002. * \note both sip_pvt and sip_pvt's owner channel (if present)
  20003. * must be locked for this function.
  20004. */
  20005. static void check_pendings(struct sip_pvt *p)
  20006. {
  20007. if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  20008. if (p->reinviteid > -1) {
  20009. /* Outstanding p->reinviteid timeout, so wait... */
  20010. return;
  20011. } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
  20012. /* if we can't BYE, then this is really a pending CANCEL */
  20013. p->invitestate = INV_CANCELLED;
  20014. transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
  20015. /* If the cancel occurred on an initial invite, cancel the pending BYE */
  20016. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  20017. ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
  20018. }
  20019. /* Actually don't destroy us yet, wait for the 487 on our original
  20020. INVITE, but do set an autodestruct just in case we never get it. */
  20021. } else {
  20022. /* We have a pending outbound invite, don't send something
  20023. * new in-transaction, unless it is a pending reinvite, then
  20024. * by the time we are called here, we should probably just hang up. */
  20025. if (p->pendinginvite && !p->ongoing_reinvite)
  20026. return;
  20027. if (p->owner) {
  20028. ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
  20029. }
  20030. /* Perhaps there is an SD change INVITE outstanding */
  20031. transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
  20032. ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
  20033. }
  20034. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20035. } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
  20036. /* if we can't REINVITE, hold it for later */
  20037. if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
  20038. ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
  20039. } else {
  20040. ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
  20041. /* Didn't get to reinvite yet, so do it now */
  20042. transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
  20043. ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
  20044. }
  20045. }
  20046. }
  20047. /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
  20048. to avoid race conditions between asterisk servers.
  20049. Called from the scheduler.
  20050. */
  20051. static int sip_reinvite_retry(const void *data)
  20052. {
  20053. struct sip_pvt *p = (struct sip_pvt *) data;
  20054. struct ast_channel *owner;
  20055. sip_pvt_lock(p); /* called from schedule thread which requires a lock */
  20056. while ((owner = p->owner) && ast_channel_trylock(owner)) {
  20057. sip_pvt_unlock(p);
  20058. usleep(1);
  20059. sip_pvt_lock(p);
  20060. }
  20061. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  20062. p->waitid = -1;
  20063. check_pendings(p);
  20064. sip_pvt_unlock(p);
  20065. if (owner) {
  20066. ast_channel_unlock(owner);
  20067. }
  20068. dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
  20069. return 0;
  20070. }
  20071. /*!
  20072. * \brief Handle authentication challenge for SIP UPDATE
  20073. *
  20074. * This function is only called upon the receipt of a 401/407 response to an UPDATE.
  20075. */
  20076. static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20077. {
  20078. if (p->options) {
  20079. p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
  20080. }
  20081. if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
  20082. ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", sip_get_header(&p->initreq, "From"));
  20083. }
  20084. }
  20085. static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
  20086. {
  20087. struct cc_epa_entry *cc_entry = epa_entry->instance_data;
  20088. struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
  20089. find_sip_monitor_instance_by_suspension_entry, epa_entry);
  20090. const char *min_expires;
  20091. if (!monitor_instance) {
  20092. ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
  20093. return;
  20094. }
  20095. if (resp != 423) {
  20096. ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
  20097. "Received error response to our PUBLISH");
  20098. ao2_ref(monitor_instance, -1);
  20099. return;
  20100. }
  20101. /* Allrighty, the other end doesn't like our Expires value. They think it's
  20102. * too small, so let's see if they've provided a more sensible value. If they
  20103. * haven't, then we'll just double our Expires value and see if they like that
  20104. * instead.
  20105. *
  20106. * XXX Ideally this logic could be placed into its own function so that SUBSCRIBE,
  20107. * PUBLISH, and REGISTER could all benefit from the same shared code.
  20108. */
  20109. min_expires = sip_get_header(req, "Min-Expires");
  20110. if (ast_strlen_zero(min_expires)) {
  20111. pvt->expiry *= 2;
  20112. if (pvt->expiry < 0) {
  20113. /* You dork! You overflowed! */
  20114. ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
  20115. "PUBLISH expiry overflowed");
  20116. ao2_ref(monitor_instance, -1);
  20117. return;
  20118. }
  20119. } else if (sscanf(min_expires, "%30d", &pvt->expiry) != 1) {
  20120. ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
  20121. "Min-Expires has non-numeric value");
  20122. ao2_ref(monitor_instance, -1);
  20123. return;
  20124. }
  20125. /* At this point, we have most certainly changed pvt->expiry, so try transmitting
  20126. * again
  20127. */
  20128. transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
  20129. ao2_ref(monitor_instance, -1);
  20130. }
  20131. static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20132. {
  20133. struct sip_epa_entry *epa_entry = p->epa_entry;
  20134. const char *etag = sip_get_header(req, "Sip-ETag");
  20135. ast_assert(epa_entry != NULL);
  20136. if (resp == 401 || resp == 407) {
  20137. ast_string_field_set(p, theirtag, NULL);
  20138. if (p->options) {
  20139. p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
  20140. }
  20141. if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
  20142. ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", sip_get_header(&p->initreq, "From"));
  20143. pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
  20144. sip_alreadygone(p);
  20145. }
  20146. return;
  20147. }
  20148. if (resp == 501 || resp == 405) {
  20149. mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
  20150. }
  20151. if (resp == 200) {
  20152. p->authtries = 0;
  20153. /* If I've read section 6, item 6 of RFC 3903 correctly,
  20154. * an ESC will only generate a new etag when it sends a 200 OK
  20155. */
  20156. if (!ast_strlen_zero(etag)) {
  20157. ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
  20158. }
  20159. /* The nominal case. Everything went well. Everybody is happy.
  20160. * Each EPA will have a specific action to take as a result of this
  20161. * development, so ... callbacks!
  20162. */
  20163. if (epa_entry->static_data->handle_ok) {
  20164. epa_entry->static_data->handle_ok(p, req, epa_entry);
  20165. }
  20166. } else {
  20167. /* Rather than try to make individual callbacks for each error
  20168. * type, there is just a single error callback. The callback
  20169. * can distinguish between error messages and do what it needs to
  20170. */
  20171. if (epa_entry->static_data->handle_error) {
  20172. epa_entry->static_data->handle_error(p, resp, req, epa_entry);
  20173. }
  20174. }
  20175. }
  20176. /*!
  20177. * \internal
  20178. * \brief Set hangup source and cause.
  20179. *
  20180. * \param p SIP private.
  20181. * \param cause Hangup cause to queue. Zero if no cause.
  20182. *
  20183. * \pre p and p->owner are locked.
  20184. *
  20185. * \return Nothing
  20186. */
  20187. static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
  20188. {
  20189. struct ast_channel *owner = p->owner;
  20190. const char *name = ast_strdupa(ast_channel_name(owner));
  20191. /* Cannot hold any channel/private locks when calling. */
  20192. ast_channel_ref(owner);
  20193. ast_channel_unlock(owner);
  20194. sip_pvt_unlock(p);
  20195. ast_set_hangupsource(owner, name, 0);
  20196. if (cause) {
  20197. ast_queue_hangup_with_cause(owner, cause);
  20198. } else {
  20199. ast_queue_hangup(owner);
  20200. }
  20201. ast_channel_unref(owner);
  20202. /* Relock things. */
  20203. owner = sip_pvt_lock_full(p);
  20204. if (owner) {
  20205. ast_channel_unref(owner);
  20206. }
  20207. }
  20208. /*! \brief Handle SIP response to INVITE dialogue */
  20209. static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20210. {
  20211. int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
  20212. int res = 0;
  20213. int xmitres = 0;
  20214. int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  20215. char *p_hdrval;
  20216. int rtn;
  20217. struct ast_party_connected_line connected;
  20218. struct ast_set_party_connected_line update_connected;
  20219. if (reinvite) {
  20220. ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
  20221. } else {
  20222. ast_debug(4, "SIP response %d to standard invite\n", resp);
  20223. }
  20224. if (p->alreadygone) { /* This call is already gone */
  20225. ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
  20226. return;
  20227. }
  20228. /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
  20229. /* Don't auto congest anymore since we've gotten something useful back */
  20230. AST_SCHED_DEL_UNREF(sched, p->initid, dialog_unref(p, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
  20231. /* RFC3261 says we must treat every 1xx response (but not 100)
  20232. that we don't recognize as if it was 183.
  20233. */
  20234. if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183) {
  20235. resp = 183;
  20236. }
  20237. /* For INVITE, treat all 2XX responses as we would a 200 response */
  20238. if ((resp >= 200) && (resp < 300)) {
  20239. resp = 200;
  20240. }
  20241. /* Any response between 100 and 199 is PROCEEDING */
  20242. if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING) {
  20243. p->invitestate = INV_PROCEEDING;
  20244. }
  20245. /* Final response, not 200 ? */
  20246. if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA )) {
  20247. p->invitestate = INV_COMPLETED;
  20248. }
  20249. if ((resp >= 200 && reinvite)) {
  20250. p->ongoing_reinvite = 0;
  20251. if (p->reinviteid > -1) {
  20252. AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
  20253. }
  20254. }
  20255. /* Final response, clear out pending invite */
  20256. if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
  20257. p->pendinginvite = 0;
  20258. }
  20259. /* If this is a response to our initial INVITE, we need to set what we can use
  20260. * for this peer.
  20261. */
  20262. if (!reinvite) {
  20263. set_pvt_allowed_methods(p, req);
  20264. }
  20265. switch (resp) {
  20266. case 100: /* Trying */
  20267. case 101: /* Dialog establishment */
  20268. if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p)) {
  20269. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  20270. }
  20271. check_pendings(p);
  20272. break;
  20273. case 180: /* 180 Ringing */
  20274. case 182: /* 182 Queued */
  20275. if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p)) {
  20276. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  20277. }
  20278. /* Store Route-set from provisional SIP responses so
  20279. * early-dialog request can be routed properly
  20280. * */
  20281. parse_ok_contact(p, req);
  20282. if (!reinvite) {
  20283. build_route(p, req, 1, resp);
  20284. }
  20285. if (!req->ignore && p->owner) {
  20286. if (get_rpid(p, req)) {
  20287. /* Queue a connected line update */
  20288. ast_party_connected_line_init(&connected);
  20289. memset(&update_connected, 0, sizeof(update_connected));
  20290. update_connected.id.number = 1;
  20291. connected.id.number.valid = 1;
  20292. connected.id.number.str = (char *) p->cid_num;
  20293. connected.id.number.presentation = p->callingpres;
  20294. update_connected.id.name = 1;
  20295. connected.id.name.valid = 1;
  20296. connected.id.name.str = (char *) p->cid_name;
  20297. connected.id.name.presentation = p->callingpres;
  20298. /* Invalidate any earlier private connected id representation */
  20299. ast_set_party_id_all(&update_connected.priv);
  20300. connected.id.tag = (char *) p->cid_tag;
  20301. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  20302. ast_channel_queue_connected_line_update(p->owner, &connected,
  20303. &update_connected);
  20304. }
  20305. sip_handle_cc(p, req, AST_CC_CCNR);
  20306. ast_queue_control(p->owner, AST_CONTROL_RINGING);
  20307. if (ast_channel_state(p->owner) != AST_STATE_UP) {
  20308. ast_setstate(p->owner, AST_STATE_RINGING);
  20309. }
  20310. }
  20311. if (find_sdp(req)) {
  20312. if (p->invitestate != INV_CANCELLED) {
  20313. p->invitestate = INV_EARLY_MEDIA;
  20314. }
  20315. res = process_sdp(p, req, SDP_T38_NONE);
  20316. if (!req->ignore && p->owner) {
  20317. /* Queue a progress frame only if we have SDP in 180 or 182 */
  20318. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  20319. /* We have not sent progress, but we have been sent progress so enable early media */
  20320. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  20321. }
  20322. ast_rtp_instance_activate(p->rtp);
  20323. }
  20324. check_pendings(p);
  20325. break;
  20326. case 181: /* Call Is Being Forwarded */
  20327. if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
  20328. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  20329. /* Store Route-set from provisional SIP responses so
  20330. * early-dialog request can be routed properly
  20331. * */
  20332. parse_ok_contact(p, req);
  20333. if (!reinvite) {
  20334. build_route(p, req, 1, resp);
  20335. }
  20336. if (!req->ignore && p->owner) {
  20337. struct ast_party_redirecting redirecting;
  20338. struct ast_set_party_redirecting update_redirecting;
  20339. ast_party_redirecting_init(&redirecting);
  20340. memset(&update_redirecting, 0, sizeof(update_redirecting));
  20341. change_redirecting_information(p, req, &redirecting, &update_redirecting,
  20342. FALSE);
  20343. /* Invalidate any earlier private redirecting id representations */
  20344. ast_set_party_id_all(&update_redirecting.priv_orig);
  20345. ast_set_party_id_all(&update_redirecting.priv_from);
  20346. ast_set_party_id_all(&update_redirecting.priv_to);
  20347. ast_channel_queue_redirecting_update(p->owner, &redirecting,
  20348. &update_redirecting);
  20349. ast_party_redirecting_free(&redirecting);
  20350. sip_handle_cc(p, req, AST_CC_CCNR);
  20351. }
  20352. check_pendings(p);
  20353. break;
  20354. case 183: /* Session progress */
  20355. if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p)) {
  20356. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  20357. }
  20358. /* Store Route-set from provisional SIP responses so
  20359. * early-dialog request can be routed properly
  20360. * */
  20361. parse_ok_contact(p, req);
  20362. if (!reinvite) {
  20363. build_route(p, req, 1, resp);
  20364. }
  20365. if (!req->ignore && p->owner) {
  20366. if (get_rpid(p, req)) {
  20367. /* Queue a connected line update */
  20368. ast_party_connected_line_init(&connected);
  20369. memset(&update_connected, 0, sizeof(update_connected));
  20370. update_connected.id.number = 1;
  20371. connected.id.number.valid = 1;
  20372. connected.id.number.str = (char *) p->cid_num;
  20373. connected.id.number.presentation = p->callingpres;
  20374. update_connected.id.name = 1;
  20375. connected.id.name.valid = 1;
  20376. connected.id.name.str = (char *) p->cid_name;
  20377. connected.id.name.presentation = p->callingpres;
  20378. /* Invalidate any earlier private connected id representation */
  20379. ast_set_party_id_all(&update_connected.priv);
  20380. connected.id.tag = (char *) p->cid_tag;
  20381. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  20382. ast_channel_queue_connected_line_update(p->owner, &connected,
  20383. &update_connected);
  20384. }
  20385. sip_handle_cc(p, req, AST_CC_CCNR);
  20386. }
  20387. if (find_sdp(req)) {
  20388. if (p->invitestate != INV_CANCELLED) {
  20389. p->invitestate = INV_EARLY_MEDIA;
  20390. }
  20391. res = process_sdp(p, req, SDP_T38_NONE);
  20392. if (!req->ignore && p->owner) {
  20393. /* Queue a progress frame */
  20394. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  20395. /* We have not sent progress, but we have been sent progress so enable early media */
  20396. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  20397. }
  20398. ast_rtp_instance_activate(p->rtp);
  20399. } else {
  20400. /* Alcatel PBXs are known to send 183s with no SDP after sending
  20401. * a 100 Trying response. We're just going to treat this sort of thing
  20402. * the same as we would treat a 180 Ringing
  20403. */
  20404. if (!req->ignore && p->owner) {
  20405. ast_queue_control(p->owner, AST_CONTROL_RINGING);
  20406. }
  20407. }
  20408. check_pendings(p);
  20409. break;
  20410. case 200: /* 200 OK on invite - someone's answering our call */
  20411. if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p)) {
  20412. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  20413. }
  20414. p->authtries = 0;
  20415. if (find_sdp(req)) {
  20416. if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore) {
  20417. if (!reinvite) {
  20418. /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
  20419. /* For re-invites, we try to recover */
  20420. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20421. p->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  20422. if (p->owner) {
  20423. ast_channel_hangupcause_set(p->owner, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  20424. sip_queue_hangup_cause(p, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  20425. }
  20426. }
  20427. }
  20428. ast_rtp_instance_activate(p->rtp);
  20429. } else if (!reinvite) {
  20430. struct ast_sockaddr remote_address = {{0,}};
  20431. ast_rtp_instance_get_requested_target_address(p->rtp, &remote_address);
  20432. if (ast_sockaddr_isnull(&remote_address) || (!ast_strlen_zero(p->theirprovtag) && strcmp(p->theirtag, p->theirprovtag))) {
  20433. ast_log(LOG_WARNING, "Received response: \"200 OK\" from '%s' without SDP\n", p->relatedpeer->name);
  20434. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20435. ast_rtp_instance_activate(p->rtp);
  20436. }
  20437. }
  20438. if (!req->ignore && p->owner) {
  20439. int rpid_changed;
  20440. rpid_changed = get_rpid(p, req);
  20441. if (rpid_changed || !reinvite) {
  20442. /* Queue a connected line update */
  20443. ast_party_connected_line_init(&connected);
  20444. memset(&update_connected, 0, sizeof(update_connected));
  20445. if (rpid_changed
  20446. || !ast_strlen_zero(p->cid_num)
  20447. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  20448. update_connected.id.number = 1;
  20449. connected.id.number.valid = 1;
  20450. connected.id.number.str = (char *) p->cid_num;
  20451. connected.id.number.presentation = p->callingpres;
  20452. }
  20453. if (rpid_changed
  20454. || !ast_strlen_zero(p->cid_name)
  20455. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  20456. update_connected.id.name = 1;
  20457. connected.id.name.valid = 1;
  20458. connected.id.name.str = (char *) p->cid_name;
  20459. connected.id.name.presentation = p->callingpres;
  20460. }
  20461. if (update_connected.id.number || update_connected.id.name) {
  20462. /* Invalidate any earlier private connected id representation */
  20463. ast_set_party_id_all(&update_connected.priv);
  20464. connected.id.tag = (char *) p->cid_tag;
  20465. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  20466. ast_channel_queue_connected_line_update(p->owner, &connected,
  20467. &update_connected);
  20468. }
  20469. }
  20470. }
  20471. /* Parse contact header for continued conversation */
  20472. /* When we get 200 OK, we know which device (and IP) to contact for this call */
  20473. /* This is important when we have a SIP proxy between us and the phone */
  20474. if (outgoing) {
  20475. update_call_counter(p, DEC_CALL_RINGING);
  20476. parse_ok_contact(p, req);
  20477. /* Save Record-Route for any later requests we make on this dialogue */
  20478. if (!reinvite) {
  20479. build_route(p, req, 1, resp);
  20480. }
  20481. if(set_address_from_contact(p)) {
  20482. /* Bad contact - we don't know how to reach this device */
  20483. /* We need to ACK, but then send a bye */
  20484. if (sip_route_empty(&p->route) && !req->ignore) {
  20485. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20486. }
  20487. }
  20488. }
  20489. if (!req->ignore && p->owner) {
  20490. if (!reinvite && !res) {
  20491. ast_queue_control(p->owner, AST_CONTROL_ANSWER);
  20492. } else { /* RE-invite */
  20493. if (p->t38.state == T38_DISABLED || p->t38.state == T38_REJECTED) {
  20494. ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
  20495. } else {
  20496. ast_queue_frame(p->owner, &ast_null_frame);
  20497. }
  20498. }
  20499. } else {
  20500. /* It's possible we're getting an 200 OK after we've tried to disconnect
  20501. by sending CANCEL */
  20502. /* First send ACK, then send bye */
  20503. if (!req->ignore) {
  20504. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20505. }
  20506. }
  20507. /* Check for Session-Timers related headers */
  20508. if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE) {
  20509. p_hdrval = (char*)sip_get_header(req, "Session-Expires");
  20510. if (!ast_strlen_zero(p_hdrval)) {
  20511. /* UAS supports Session-Timers */
  20512. enum st_refresher_param st_ref_param;
  20513. int tmp_st_interval = 0;
  20514. rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
  20515. if (rtn != 0) {
  20516. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20517. } else if (tmp_st_interval < st_get_se(p, FALSE)) {
  20518. ast_log(LOG_WARNING, "Got Session-Expires less than local Min-SE in 200 OK, tearing down call\n");
  20519. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20520. }
  20521. if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
  20522. p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
  20523. } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
  20524. p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
  20525. } else {
  20526. ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
  20527. }
  20528. if (tmp_st_interval) {
  20529. p->stimer->st_interval = tmp_st_interval;
  20530. }
  20531. p->stimer->st_active = TRUE;
  20532. p->stimer->st_active_peer_ua = TRUE;
  20533. start_session_timer(p);
  20534. } else {
  20535. /* UAS doesn't support Session-Timers */
  20536. if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
  20537. p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
  20538. p->stimer->st_active_peer_ua = FALSE;
  20539. start_session_timer(p);
  20540. }
  20541. }
  20542. }
  20543. /* If I understand this right, the branch is different for a non-200 ACK only */
  20544. p->invitestate = INV_TERMINATED;
  20545. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  20546. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
  20547. check_pendings(p);
  20548. break;
  20549. case 407: /* Proxy authentication */
  20550. case 401: /* Www auth */
  20551. /* First we ACK */
  20552. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20553. if (p->options) {
  20554. p->options->auth_type = resp;
  20555. }
  20556. /* Then we AUTH */
  20557. ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
  20558. if (!req->ignore) {
  20559. if (p->authtries < MAX_AUTHTRIES) {
  20560. p->invitestate = INV_CALLING;
  20561. }
  20562. if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
  20563. ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", sip_get_header(&p->initreq, "From"));
  20564. pvt_set_needdestroy(p, "failed to authenticate on INVITE");
  20565. sip_alreadygone(p);
  20566. if (p->owner) {
  20567. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  20568. }
  20569. }
  20570. }
  20571. break;
  20572. case 403: /* Forbidden */
  20573. /* First we ACK */
  20574. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20575. ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", sip_get_header(&p->initreq, "From"));
  20576. if (!req->ignore && p->owner) {
  20577. sip_queue_hangup_cause(p, hangup_sip2cause(resp));
  20578. }
  20579. break;
  20580. case 414: /* Bad request URI */
  20581. case 493: /* Undecipherable */
  20582. case 404: /* Not found */
  20583. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20584. if (p->owner && !req->ignore) {
  20585. sip_queue_hangup_cause(p, hangup_sip2cause(resp));
  20586. }
  20587. break;
  20588. case 481: /* Call leg does not exist */
  20589. /* Could be REFER caused INVITE with replaces */
  20590. ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
  20591. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20592. if (p->owner) {
  20593. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  20594. }
  20595. break;
  20596. case 422: /* Session-Timers: Session interval too small */
  20597. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20598. ast_string_field_set(p, theirtag, NULL);
  20599. proc_422_rsp(p, req);
  20600. break;
  20601. case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
  20602. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20603. append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
  20604. ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
  20605. if (p->owner && !req->ignore) {
  20606. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  20607. }
  20608. break;
  20609. case 480: /* Temporarily unavailable. */
  20610. /* RFC 3261 encourages setting the reason phrase to something indicative
  20611. * of why the endpoint is not available. We will make this readable via the
  20612. * redirecting reason.
  20613. */
  20614. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20615. append_history(p, "TempUnavailable", "Endpoint is temporarily unavailable.");
  20616. if (p->owner && !req->ignore) {
  20617. struct ast_party_redirecting redirecting;
  20618. struct ast_set_party_redirecting update_redirecting;
  20619. ast_party_redirecting_set_init(&redirecting, ast_channel_redirecting(p->owner));
  20620. memset(&update_redirecting, 0, sizeof(update_redirecting));
  20621. redirecting.reason.code = sip_reason_str_to_code(rest);
  20622. redirecting.reason.str = ast_strdup(rest);
  20623. ast_channel_queue_redirecting_update(p->owner, &redirecting, &update_redirecting);
  20624. ast_party_redirecting_free(&redirecting);
  20625. ast_queue_control(p->owner, AST_CONTROL_BUSY);
  20626. }
  20627. break;
  20628. case 487: /* Cancelled transaction */
  20629. /* We have sent CANCEL on an outbound INVITE
  20630. This transaction is already scheduled to be killed by sip_hangup().
  20631. */
  20632. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20633. if (p->owner && !req->ignore) {
  20634. ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
  20635. append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
  20636. } else if (!req->ignore) {
  20637. update_call_counter(p, DEC_CALL_LIMIT);
  20638. append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
  20639. }
  20640. check_pendings(p);
  20641. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20642. break;
  20643. case 415: /* Unsupported media type */
  20644. case 488: /* Not acceptable here */
  20645. case 606: /* Not Acceptable */
  20646. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20647. if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
  20648. change_t38_state(p, T38_REJECTED);
  20649. /* Try to reset RTP timers */
  20650. /* XXX Why is this commented away??? */
  20651. //ast_rtp_set_rtptimers_onhold(p->rtp);
  20652. /* Trigger a reinvite back to audio */
  20653. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  20654. } else {
  20655. /* We can't set up this call, so give up */
  20656. if (p->owner && !req->ignore) {
  20657. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  20658. }
  20659. }
  20660. break;
  20661. case 491: /* Pending */
  20662. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20663. if (p->owner && !req->ignore) {
  20664. if (ast_channel_state(p->owner) != AST_STATE_UP) {
  20665. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  20666. } else {
  20667. /* This is a re-invite that failed. */
  20668. /* Reset the flag after a while
  20669. */
  20670. int wait;
  20671. /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
  20672. * if not owner of call, wait 0 to 2 seconds */
  20673. if (p->outgoing_call) {
  20674. wait = 2100 + ast_random() % 2000;
  20675. } else {
  20676. wait = ast_random() % 2000;
  20677. }
  20678. p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, dialog_ref(p, "passing dialog ptr into sched structure based on waitid for sip_reinvite_retry."));
  20679. ast_debug(2, "Reinvite race. Scheduled sip_reinvite_retry in %d secs in handle_response_invite (waitid %d, dialog '%s')\n",
  20680. wait, p->waitid, p->callid);
  20681. }
  20682. }
  20683. break;
  20684. case 408: /* Request timeout */
  20685. case 405: /* Not allowed */
  20686. case 501: /* Not implemented */
  20687. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20688. if (p->owner) {
  20689. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  20690. }
  20691. break;
  20692. }
  20693. if (xmitres == XMIT_ERROR) {
  20694. ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
  20695. }
  20696. }
  20697. /* \brief Handle SIP response in NOTIFY transaction
  20698. We've sent a NOTIFY, now handle responses to it
  20699. */
  20700. static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20701. {
  20702. switch (resp) {
  20703. case 200: /* Notify accepted */
  20704. /* They got the notify, this is the end */
  20705. if (p->owner) {
  20706. if (p->refer) {
  20707. ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
  20708. } else {
  20709. ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", ast_channel_name(p->owner));
  20710. }
  20711. } else {
  20712. if (p->subscribed == NONE && !p->refer) {
  20713. ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
  20714. pvt_set_needdestroy(p, "received 200 response");
  20715. }
  20716. if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
  20717. struct state_notify_data data = {
  20718. .state = p->laststate,
  20719. .device_state_info = p->last_device_state_info,
  20720. .presence_state = p->last_presence_state,
  20721. .presence_subtype = p->last_presence_subtype,
  20722. .presence_message = p->last_presence_message,
  20723. };
  20724. /* Ready to send the next state we have on queue */
  20725. ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
  20726. extensionstate_update(p->context, p->exten, &data, p, TRUE);
  20727. }
  20728. }
  20729. break;
  20730. case 401: /* Not www-authorized on SIP method */
  20731. case 407: /* Proxy auth */
  20732. if (!p->notify) {
  20733. break; /* Only device notify can use NOTIFY auth */
  20734. }
  20735. ast_string_field_set(p, theirtag, NULL);
  20736. if (ast_strlen_zero(p->authname)) {
  20737. ast_log(LOG_WARNING, "Asked to authenticate NOTIFY to %s but we have no matching peer or realm auth!\n", ast_sockaddr_stringify(&p->recv));
  20738. pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
  20739. }
  20740. if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
  20741. ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", sip_get_header(&p->initreq, "From"));
  20742. pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
  20743. }
  20744. break;
  20745. case 481: /* Call leg does not exist */
  20746. pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
  20747. break;
  20748. }
  20749. }
  20750. /* \brief Handle SIP response in SUBSCRIBE transaction */
  20751. static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20752. {
  20753. if (p->subscribed == CALL_COMPLETION) {
  20754. struct sip_monitor_instance *monitor_instance;
  20755. if (resp < 300) {
  20756. return;
  20757. }
  20758. /* Final failure response received. */
  20759. monitor_instance = ao2_callback(sip_monitor_instances, 0,
  20760. find_sip_monitor_instance_by_subscription_pvt, p);
  20761. if (monitor_instance) {
  20762. ast_cc_monitor_failed(monitor_instance->core_id,
  20763. monitor_instance->device_name,
  20764. "Received error response to our SUBSCRIBE");
  20765. }
  20766. return;
  20767. }
  20768. if (p->subscribed != MWI_NOTIFICATION) {
  20769. return;
  20770. }
  20771. if (!p->mwi) {
  20772. return;
  20773. }
  20774. switch (resp) {
  20775. case 200: /* Subscription accepted */
  20776. ast_debug(3, "Got 200 OK on subscription for MWI\n");
  20777. set_pvt_allowed_methods(p, req);
  20778. if (p->options) {
  20779. if (p->options->outboundproxy) {
  20780. ao2_ref(p->options->outboundproxy, -1);
  20781. }
  20782. ast_free(p->options);
  20783. p->options = NULL;
  20784. }
  20785. p->mwi->subscribed = 1;
  20786. if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ao2_t_bump(p->mwi, "mwi ast_sched_add"))) < 0) {
  20787. ao2_t_ref(p->mwi, -1, "mwi ast_sched_add < 0");
  20788. }
  20789. break;
  20790. case 401:
  20791. case 407:
  20792. ast_string_field_set(p, theirtag, NULL);
  20793. if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
  20794. ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", sip_get_header(&p->initreq, "From"));
  20795. p->mwi->call = NULL;
  20796. ao2_t_ref(p->mwi, -1, "failed to authenticate SUBSCRIBE");
  20797. pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
  20798. }
  20799. break;
  20800. case 403:
  20801. transmit_response_with_date(p, "200 OK", req);
  20802. ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
  20803. p->mwi->call = NULL;
  20804. ao2_t_ref(p->mwi, -1, "received 403 response");
  20805. pvt_set_needdestroy(p, "received 403 response");
  20806. sip_alreadygone(p);
  20807. break;
  20808. case 404:
  20809. ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
  20810. p->mwi->call = NULL;
  20811. ao2_t_ref(p->mwi, -1, "received 404 response");
  20812. pvt_set_needdestroy(p, "received 404 response");
  20813. break;
  20814. case 481:
  20815. ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
  20816. p->mwi->call = NULL;
  20817. ao2_t_ref(p->mwi, -1, "received 481 response");
  20818. pvt_set_needdestroy(p, "received 481 response");
  20819. break;
  20820. case 400: /* Bad Request */
  20821. case 414: /* Request URI too long */
  20822. case 493: /* Undecipherable */
  20823. case 500:
  20824. case 501:
  20825. ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
  20826. p->mwi->call = NULL;
  20827. ao2_t_ref(p->mwi, -1, "received 500/501 response");
  20828. pvt_set_needdestroy(p, "received serious error (500/501/493/414/400) response");
  20829. break;
  20830. }
  20831. }
  20832. /* \brief Handle SIP response in REFER transaction
  20833. We've sent a REFER, now handle responses to it
  20834. */
  20835. static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20836. {
  20837. enum ast_control_transfer message = AST_TRANSFER_FAILED;
  20838. /* If no refer structure exists, then do nothing */
  20839. if (!p->refer)
  20840. return;
  20841. switch (resp) {
  20842. case 202: /* Transfer accepted */
  20843. /* We need to do something here */
  20844. /* The transferee is now sending INVITE to target */
  20845. p->refer->status = REFER_ACCEPTED;
  20846. /* Now wait for next message */
  20847. ast_debug(3, "Got 202 accepted on transfer\n");
  20848. /* We should hang along, waiting for NOTIFY's here */
  20849. break;
  20850. case 401: /* Not www-authorized on SIP method */
  20851. case 407: /* Proxy auth */
  20852. if (ast_strlen_zero(p->authname)) {
  20853. ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
  20854. ast_sockaddr_stringify(&p->recv));
  20855. if (p->owner) {
  20856. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20857. }
  20858. pvt_set_needdestroy(p, "unable to authenticate REFER");
  20859. }
  20860. if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
  20861. ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", sip_get_header(&p->initreq, "From"));
  20862. p->refer->status = REFER_NOAUTH;
  20863. if (p->owner) {
  20864. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20865. }
  20866. pvt_set_needdestroy(p, "failed to authenticate REFER");
  20867. }
  20868. break;
  20869. case 405: /* Method not allowed */
  20870. /* Return to the current call onhold */
  20871. /* Status flag needed to be reset */
  20872. ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
  20873. pvt_set_needdestroy(p, "received 405 response");
  20874. p->refer->status = REFER_FAILED;
  20875. if (p->owner) {
  20876. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20877. }
  20878. break;
  20879. case 481: /* Call leg does not exist */
  20880. /* A transfer with Replaces did not work */
  20881. /* OEJ: We should Set flag, cancel the REFER, go back
  20882. to original call - but right now we can't */
  20883. ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
  20884. if (p->owner)
  20885. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  20886. pvt_set_needdestroy(p, "received 481 response");
  20887. break;
  20888. case 500: /* Server error */
  20889. case 501: /* Method not implemented */
  20890. /* Return to the current call onhold */
  20891. /* Status flag needed to be reset */
  20892. ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
  20893. pvt_set_needdestroy(p, "received 500/501 response");
  20894. p->refer->status = REFER_FAILED;
  20895. if (p->owner) {
  20896. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20897. }
  20898. break;
  20899. case 603: /* Transfer declined */
  20900. ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
  20901. p->refer->status = REFER_FAILED;
  20902. pvt_set_needdestroy(p, "received 603 response");
  20903. if (p->owner) {
  20904. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20905. }
  20906. break;
  20907. default:
  20908. /* We should treat unrecognized 9xx as 900. 400 is actually
  20909. specified as a possible response, but any 4-6xx is
  20910. theoretically possible. */
  20911. if (resp < 299) { /* 1xx cases don't get here */
  20912. ast_log(LOG_WARNING, "SIP transfer to %s had unexpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
  20913. } else {
  20914. ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
  20915. }
  20916. p->refer->status = REFER_FAILED;
  20917. pvt_set_needdestroy(p, "received failure response");
  20918. if (p->owner) {
  20919. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20920. }
  20921. break;
  20922. }
  20923. }
  20924. /*! \brief Handle responses on REGISTER to services */
  20925. static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20926. {
  20927. int expires, expires_ms;
  20928. struct sip_registry *r;
  20929. r = p->registry;
  20930. switch (resp) {
  20931. case 401: /* Unauthorized */
  20932. if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
  20933. ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
  20934. pvt_set_needdestroy(p, "failed to authenticate REGISTER");
  20935. }
  20936. break;
  20937. case 403: /* Forbidden */
  20938. if (global_reg_retry_403) {
  20939. ast_log(LOG_NOTICE, "Treating 403 response to REGISTER as non-fatal for %s@%s\n",
  20940. p->registry->username, p->registry->hostname);
  20941. ast_string_field_set(r, nonce, "");
  20942. ast_string_field_set(p, nonce, "");
  20943. break;
  20944. }
  20945. ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
  20946. AST_SCHED_DEL_UNREF(sched, r->timeout, ao2_t_ref(r, -1, "reg ptr unref from handle_response_register 403"));
  20947. r->regstate = REG_STATE_NOAUTH;
  20948. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  20949. pvt_set_needdestroy(p, "received 403 response");
  20950. break;
  20951. case 404: /* Not found */
  20952. ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
  20953. pvt_set_needdestroy(p, "received 404 response");
  20954. if (r->call)
  20955. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
  20956. r->regstate = REG_STATE_REJECTED;
  20957. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  20958. AST_SCHED_DEL_UNREF(sched, r->timeout, ao2_t_ref(r, -1, "reg ptr unref from handle_response_register 404"));
  20959. break;
  20960. case 407: /* Proxy auth */
  20961. if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
  20962. ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", sip_get_header(&p->initreq, "From"), p->authtries);
  20963. pvt_set_needdestroy(p, "failed to authenticate REGISTER");
  20964. }
  20965. break;
  20966. case 408: /* Request timeout */
  20967. /* Got a timeout response, so reset the counter of failed responses */
  20968. if (r) {
  20969. r->regattempts = 0;
  20970. } else {
  20971. ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
  20972. }
  20973. break;
  20974. case 423: /* Interval too brief */
  20975. r->expiry = atoi(sip_get_header(req, "Min-Expires"));
  20976. ast_log(LOG_WARNING, "Got 423 Interval too brief for service %s@%s, minimum is %d seconds\n", p->registry->username, p->registry->hostname, r->expiry);
  20977. AST_SCHED_DEL_UNREF(sched, r->timeout, ao2_t_ref(r, -1, "reg ptr unref from handle_response_register 423"));
  20978. if (r->call) {
  20979. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
  20980. pvt_set_needdestroy(p, "received 423 response");
  20981. }
  20982. if (r->expiry > max_expiry) {
  20983. ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
  20984. r->expiry = r->configured_expiry;
  20985. r->regstate = REG_STATE_REJECTED;
  20986. } else {
  20987. r->regstate = REG_STATE_UNREGISTERED;
  20988. transmit_register(r, SIP_REGISTER, NULL, NULL);
  20989. }
  20990. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  20991. break;
  20992. case 400: /* Bad request */
  20993. case 414: /* Request URI too long */
  20994. case 493: /* Undecipherable */
  20995. case 479: /* Kamailio/OpenSIPS: Not able to process the URI - address is wrong in register*/
  20996. ast_log(LOG_WARNING, "Got error %d on register to %s@%s, giving up (check config)\n", resp, p->registry->username, p->registry->hostname);
  20997. pvt_set_needdestroy(p, "received 4xx response");
  20998. if (r->call)
  20999. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 4xx");
  21000. r->regstate = REG_STATE_REJECTED;
  21001. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  21002. AST_SCHED_DEL_UNREF(sched, r->timeout, ao2_t_ref(r, -1, "reg ptr unref from handle_response_register 479"));
  21003. break;
  21004. case 200: /* 200 OK */
  21005. if (!r) {
  21006. ast_log(LOG_WARNING, "Got 200 OK on REGISTER, but there isn't a registry entry for '%s' (we probably already got the OK)\n", S_OR(p->peername, p->username));
  21007. pvt_set_needdestroy(p, "received erroneous 200 response");
  21008. return 0;
  21009. }
  21010. r->regstate = REG_STATE_REGISTERED;
  21011. r->regtime = ast_tvnow(); /* Reset time of last successful registration */
  21012. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  21013. r->regattempts = 0;
  21014. ast_debug(1, "Registration successful\n");
  21015. if (r->timeout > -1) {
  21016. ast_debug(1, "Cancelling timeout %d\n", r->timeout);
  21017. }
  21018. AST_SCHED_DEL_UNREF(sched, r->timeout, ao2_t_ref(r, -1, "reg ptr unref from handle_response_register 200"));
  21019. if (r->call)
  21020. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
  21021. ao2_t_replace(p->registry, NULL, "unref registry entry p->registry");
  21022. /* destroy dialog now to avoid interference with next register */
  21023. pvt_set_needdestroy(p, "Registration successfull");
  21024. /* set us up for re-registering
  21025. * figure out how long we got registered for
  21026. * according to section 6.13 of RFC, contact headers override
  21027. * expires headers, so check those first */
  21028. expires = 0;
  21029. /* XXX todo: try to save the extra call */
  21030. if (!ast_strlen_zero(sip_get_header(req, "Contact"))) {
  21031. const char *contact = NULL;
  21032. const char *tmptmp = NULL;
  21033. int start = 0;
  21034. for(;;) {
  21035. contact = __get_header(req, "Contact", &start);
  21036. /* this loop ensures we get a contact header about our register request */
  21037. if(!ast_strlen_zero(contact)) {
  21038. if( (tmptmp=strstr(contact, p->our_contact))) {
  21039. contact=tmptmp;
  21040. break;
  21041. }
  21042. } else
  21043. break;
  21044. }
  21045. tmptmp = strcasestr(contact, "expires=");
  21046. if (tmptmp) {
  21047. if (sscanf(tmptmp + 8, "%30d", &expires) != 1) {
  21048. expires = 0;
  21049. }
  21050. }
  21051. }
  21052. if (!expires)
  21053. expires=atoi(sip_get_header(req, "expires"));
  21054. if (!expires)
  21055. expires=default_expiry;
  21056. expires_ms = expires * 1000;
  21057. if (expires <= EXPIRY_GUARD_LIMIT)
  21058. expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
  21059. else
  21060. expires_ms -= EXPIRY_GUARD_SECS * 1000;
  21061. if (sipdebug)
  21062. ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
  21063. r->refresh= (int) expires_ms / 1000;
  21064. /* Schedule re-registration before we expire */
  21065. AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
  21066. ao2_t_ref(_data, -1, "unref in REPLACE del fail"),
  21067. ao2_t_ref(r, -1, "unref in REPLACE add fail"),
  21068. ao2_t_ref(r, +1, "The Addition side of REPLACE"));
  21069. }
  21070. return 1;
  21071. }
  21072. /*! \brief Handle qualification responses (OPTIONS) */
  21073. static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
  21074. {
  21075. struct sip_peer *peer = /* sip_ref_peer( */ p->relatedpeer /* , "bump refcount on p, as it is being used in this function(handle_response_peerpoke)")*/ ; /* hope this is already refcounted! */
  21076. int statechanged, is_reachable, was_reachable;
  21077. int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
  21078. /*
  21079. * Compute the response time to a ping (goes in peer->lastms.)
  21080. * -1 means did not respond, 0 means unknown,
  21081. * 1..maxms is a valid response, >maxms means late response.
  21082. */
  21083. if (pingtime < 1) { /* zero = unknown, so round up to 1 */
  21084. pingtime = 1;
  21085. }
  21086. if (!peer->maxms) { /* this should never happens */
  21087. pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
  21088. return;
  21089. }
  21090. /* Now determine new state and whether it has changed.
  21091. * Use some helper variables to simplify the writing
  21092. * of the expressions.
  21093. */
  21094. was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
  21095. is_reachable = pingtime <= peer->maxms;
  21096. statechanged = peer->lastms == 0 /* yes, unknown before */
  21097. || was_reachable != is_reachable;
  21098. peer->lastms = pingtime;
  21099. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  21100. if (statechanged) {
  21101. const char *s = is_reachable ? "Reachable" : "Lagged";
  21102. char str_lastms[20];
  21103. snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
  21104. ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
  21105. peer->name, s, pingtime, peer->maxms);
  21106. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  21107. if (sip_cfg.peer_rtupdate) {
  21108. ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
  21109. }
  21110. if (peer->endpoint) {
  21111. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  21112. ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_ONLINE);
  21113. blob = ast_json_pack("{s: s, s: i}",
  21114. "peer_status", s,
  21115. "time", pingtime);
  21116. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  21117. }
  21118. if (is_reachable && sip_cfg.regextenonqualify) {
  21119. register_peer_exten(peer, TRUE);
  21120. }
  21121. }
  21122. pvt_set_needdestroy(p, "got OPTIONS response");
  21123. /* Try again eventually */
  21124. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
  21125. is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
  21126. sip_poke_peer_s, peer,
  21127. sip_unref_peer(_data, "removing poke peer ref"),
  21128. sip_unref_peer(peer, "removing poke peer ref"),
  21129. sip_ref_peer(peer, "adding poke peer ref"));
  21130. }
  21131. /*!
  21132. * \internal
  21133. * \brief Handle responses to INFO messages
  21134. *
  21135. * \note The INFO method MUST NOT change the state of calls or
  21136. * related sessions (RFC 2976).
  21137. */
  21138. static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  21139. {
  21140. int sipmethod = SIP_INFO;
  21141. switch (resp) {
  21142. case 401: /* Not www-authorized on SIP method */
  21143. case 407: /* Proxy auth required */
  21144. ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
  21145. ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
  21146. break;
  21147. case 405: /* Method not allowed */
  21148. case 501: /* Not Implemented */
  21149. mark_method_unallowed(&p->allowed_methods, sipmethod);
  21150. if (p->relatedpeer) {
  21151. mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
  21152. }
  21153. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
  21154. ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
  21155. break;
  21156. default:
  21157. if (300 <= resp && resp < 700) {
  21158. ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
  21159. sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
  21160. }
  21161. break;
  21162. }
  21163. }
  21164. /*!
  21165. * \internal
  21166. * \brief Handle auth requests to a MESSAGE request
  21167. * \return TRUE if authentication failed.
  21168. */
  21169. static int do_message_auth(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  21170. {
  21171. char *header;
  21172. char *respheader;
  21173. char digest[1024];
  21174. if (p->options) {
  21175. p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
  21176. }
  21177. if (p->authtries == MAX_AUTHTRIES) {
  21178. ast_log(LOG_NOTICE, "Failed to authenticate MESSAGE with host '%s'\n",
  21179. ast_sockaddr_stringify(&p->sa));
  21180. return -1;
  21181. }
  21182. ++p->authtries;
  21183. sip_auth_headers((resp == 401 ? WWW_AUTH : PROXY_AUTH), &header, &respheader);
  21184. memset(digest, 0, sizeof(digest));
  21185. if (reply_digest(p, req, header, SIP_MESSAGE, digest, sizeof(digest))) {
  21186. /* There's nothing to use for authentication */
  21187. ast_debug(1, "Nothing to use for MESSAGE authentication\n");
  21188. return -1;
  21189. }
  21190. if (p->do_history) {
  21191. append_history(p, "MessageAuth", "Try: %d", p->authtries);
  21192. }
  21193. transmit_message(p, 0, 1);
  21194. return 0;
  21195. }
  21196. /*!
  21197. * \internal
  21198. * \brief Handle responses to MESSAGE messages
  21199. *
  21200. * \note The MESSAGE method should not change the state of calls
  21201. * or related sessions if associated with a dialog. (Implied by
  21202. * RFC 3428 Section 2).
  21203. */
  21204. static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  21205. {
  21206. int sipmethod = SIP_MESSAGE;
  21207. int in_dialog = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  21208. switch (resp) {
  21209. case 401: /* Not www-authorized on SIP method */
  21210. case 407: /* Proxy auth required */
  21211. if (do_message_auth(p, resp, rest, req, seqno) && !in_dialog) {
  21212. pvt_set_needdestroy(p, "MESSAGE authentication failed");
  21213. }
  21214. break;
  21215. case 405: /* Method not allowed */
  21216. case 501: /* Not Implemented */
  21217. mark_method_unallowed(&p->allowed_methods, sipmethod);
  21218. if (p->relatedpeer) {
  21219. mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
  21220. }
  21221. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
  21222. ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
  21223. if (!in_dialog) {
  21224. pvt_set_needdestroy(p, "MESSAGE not implemented or allowed");
  21225. }
  21226. break;
  21227. default:
  21228. if (100 <= resp && resp < 200) {
  21229. /* Must allow provisional responses for out-of-dialog requests. */
  21230. } else if (200 <= resp && resp < 300) {
  21231. p->authtries = 0; /* Reset authentication counter */
  21232. if (!in_dialog) {
  21233. pvt_set_needdestroy(p, "MESSAGE delivery accepted");
  21234. }
  21235. } else if (300 <= resp && resp < 700) {
  21236. ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
  21237. sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
  21238. if (!in_dialog) {
  21239. pvt_set_needdestroy(p, (300 <= resp && resp < 600)
  21240. ? "MESSAGE delivery failed" : "MESSAGE delivery refused");
  21241. }
  21242. }
  21243. break;
  21244. }
  21245. }
  21246. /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
  21247. static void stop_media_flows(struct sip_pvt *p)
  21248. {
  21249. /* Immediately stop RTP, VRTP and UDPTL as applicable */
  21250. if (p->rtp)
  21251. ast_rtp_instance_stop(p->rtp);
  21252. if (p->vrtp)
  21253. ast_rtp_instance_stop(p->vrtp);
  21254. if (p->trtp)
  21255. ast_rtp_instance_stop(p->trtp);
  21256. if (p->udptl)
  21257. ast_udptl_stop(p->udptl);
  21258. }
  21259. /*! \brief Handle SIP response in dialogue
  21260. \note only called by handle_incoming */
  21261. static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  21262. {
  21263. struct ast_channel *owner;
  21264. int sipmethod;
  21265. const char *c = sip_get_header(req, "Cseq");
  21266. /* GCC 4.2 complains if I try to cast c as a char * when passing it to ast_skip_nonblanks, so make a copy of it */
  21267. char *c_copy = ast_strdupa(c);
  21268. /* Skip the Cseq and its subsequent spaces */
  21269. const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
  21270. if (!msg)
  21271. msg = "";
  21272. sipmethod = find_sip_method(msg);
  21273. owner = p->owner;
  21274. if (owner) {
  21275. const char *rp = NULL, *rh = NULL;
  21276. ast_channel_hangupcause_set(owner, 0);
  21277. if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = sip_get_header(req, "Reason"))) {
  21278. rh = ast_skip_blanks(rh);
  21279. if (!strncasecmp(rh, "Q.850", 5)) {
  21280. int cause = ast_channel_hangupcause(owner);
  21281. rp = strstr(rh, "cause=");
  21282. if (rp && sscanf(rp + 6, "%30d", &cause) == 1) {
  21283. ast_channel_hangupcause_set(owner, cause & 0x7f);
  21284. if (req->debug)
  21285. ast_verbose("Using Reason header for cause code: %d\n", ast_channel_hangupcause(owner));
  21286. }
  21287. }
  21288. }
  21289. if (!ast_channel_hangupcause(owner))
  21290. ast_channel_hangupcause_set(owner, hangup_sip2cause(resp));
  21291. }
  21292. if (p->socket.type == AST_TRANSPORT_UDP) {
  21293. int ack_res = FALSE;
  21294. /* Acknowledge whatever it is destined for */
  21295. if ((resp >= 100) && (resp <= 199)) {
  21296. /* NON-INVITE messages do not ack a 1XX response. RFC 3261 section 17.1.2.2 */
  21297. if (sipmethod == SIP_INVITE) {
  21298. ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
  21299. }
  21300. } else {
  21301. ack_res = __sip_ack(p, seqno, 0, sipmethod);
  21302. }
  21303. if (ack_res == FALSE) {
  21304. /* RFC 3261 13.2.2.4 and 17.1.1.2 - We must re-send ACKs to re-transmitted final responses */
  21305. if (sipmethod == SIP_INVITE && resp >= 200) {
  21306. transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
  21307. }
  21308. append_history(p, "Ignore", "Ignoring this retransmit\n");
  21309. return;
  21310. }
  21311. }
  21312. /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
  21313. if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
  21314. p->pendinginvite = 0;
  21315. }
  21316. /* Get their tag if we haven't already */
  21317. if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
  21318. char tag[128];
  21319. gettag(req, "To", tag, sizeof(tag));
  21320. ast_string_field_set(p, theirtag, tag);
  21321. } else {
  21322. /* Store theirtag to track for changes when 200 responses to invites are received without SDP */
  21323. ast_string_field_set(p, theirprovtag, p->theirtag);
  21324. }
  21325. /* This needs to be configurable on a channel/peer level,
  21326. not mandatory for all communication. Sadly enough, NAT implementations
  21327. are not so stable so we can always rely on these headers.
  21328. Temporarily disabled, while waiting for fix.
  21329. Fix assigned to Rizzo :-)
  21330. */
  21331. /* check_via_response(p, req); */
  21332. /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
  21333. * in response to a BYE, then we should end the current dialog
  21334. * and session. It is known that at least one phone manufacturer
  21335. * potentially will send a 404 in response to a BYE, so we'll be
  21336. * liberal in what we accept and end the dialog and session if we
  21337. * receive any of those responses to a BYE.
  21338. */
  21339. if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
  21340. pvt_set_needdestroy(p, "received 4XX response to a BYE");
  21341. return;
  21342. }
  21343. if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
  21344. /* We don't really care what the response is, just that it replied back.
  21345. Well, as long as it's not a 100 response... since we might
  21346. need to hang around for something more "definitive" */
  21347. if (resp != 100)
  21348. handle_response_peerpoke(p, resp, req);
  21349. } else if (sipmethod == SIP_REFER && resp >= 200) {
  21350. handle_response_refer(p, resp, rest, req, seqno);
  21351. } else if (sipmethod == SIP_PUBLISH) {
  21352. /* SIP PUBLISH transcends this morass of doodoo and instead
  21353. * we just always call the response handler. Good gravy!
  21354. */
  21355. handle_response_publish(p, resp, rest, req, seqno);
  21356. } else if (sipmethod == SIP_INFO) {
  21357. /* More good gravy! */
  21358. handle_response_info(p, resp, rest, req, seqno);
  21359. } else if (sipmethod == SIP_MESSAGE) {
  21360. /* More good gravy! */
  21361. handle_response_message(p, resp, rest, req, seqno);
  21362. } else if (sipmethod == SIP_NOTIFY) {
  21363. /* The gravy train continues to roll */
  21364. handle_response_notify(p, resp, rest, req, seqno);
  21365. } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  21366. switch(resp) {
  21367. case 100: /* 100 Trying */
  21368. case 101: /* 101 Dialog establishment */
  21369. case 183: /* 183 Session Progress */
  21370. case 180: /* 180 Ringing */
  21371. case 182: /* 182 Queued */
  21372. case 181: /* 181 Call Is Being Forwarded */
  21373. if (sipmethod == SIP_INVITE)
  21374. handle_response_invite(p, resp, rest, req, seqno);
  21375. break;
  21376. case 200: /* 200 OK */
  21377. p->authtries = 0; /* Reset authentication counter */
  21378. if (sipmethod == SIP_INVITE) {
  21379. handle_response_invite(p, resp, rest, req, seqno);
  21380. } else if (sipmethod == SIP_REGISTER) {
  21381. handle_response_register(p, resp, rest, req, seqno);
  21382. } else if (sipmethod == SIP_SUBSCRIBE) {
  21383. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  21384. handle_response_subscribe(p, resp, rest, req, seqno);
  21385. } else if (sipmethod == SIP_BYE) { /* Ok, we're ready to go */
  21386. pvt_set_needdestroy(p, "received 200 response");
  21387. ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  21388. }
  21389. break;
  21390. case 401: /* Not www-authorized on SIP method */
  21391. case 407: /* Proxy auth required */
  21392. if (sipmethod == SIP_INVITE)
  21393. handle_response_invite(p, resp, rest, req, seqno);
  21394. else if (sipmethod == SIP_SUBSCRIBE)
  21395. handle_response_subscribe(p, resp, rest, req, seqno);
  21396. else if (p->registry && sipmethod == SIP_REGISTER)
  21397. handle_response_register(p, resp, rest, req, seqno);
  21398. else if (sipmethod == SIP_UPDATE) {
  21399. handle_response_update(p, resp, rest, req, seqno);
  21400. } else if (sipmethod == SIP_BYE) {
  21401. if (p->options)
  21402. p->options->auth_type = resp;
  21403. if (ast_strlen_zero(p->authname)) {
  21404. ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
  21405. msg, ast_sockaddr_stringify(&p->recv));
  21406. pvt_set_needdestroy(p, "unable to authenticate BYE");
  21407. } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
  21408. ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, sip_get_header(&p->initreq, "From"));
  21409. pvt_set_needdestroy(p, "failed to authenticate BYE");
  21410. }
  21411. } else {
  21412. ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, sip_get_header(req, "To"));
  21413. pvt_set_needdestroy(p, "received 407 response");
  21414. }
  21415. break;
  21416. case 403: /* Forbidden - we failed authentication */
  21417. if (sipmethod == SIP_INVITE)
  21418. handle_response_invite(p, resp, rest, req, seqno);
  21419. else if (sipmethod == SIP_SUBSCRIBE)
  21420. handle_response_subscribe(p, resp, rest, req, seqno);
  21421. else if (p->registry && sipmethod == SIP_REGISTER)
  21422. handle_response_register(p, resp, rest, req, seqno);
  21423. else {
  21424. ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
  21425. pvt_set_needdestroy(p, "received 403 response");
  21426. }
  21427. break;
  21428. case 400: /* Bad Request */
  21429. case 414: /* Request URI too long */
  21430. case 493: /* Undecipherable */
  21431. case 404: /* Not found */
  21432. if (p->registry && sipmethod == SIP_REGISTER)
  21433. handle_response_register(p, resp, rest, req, seqno);
  21434. else if (sipmethod == SIP_INVITE)
  21435. handle_response_invite(p, resp, rest, req, seqno);
  21436. else if (sipmethod == SIP_SUBSCRIBE)
  21437. handle_response_subscribe(p, resp, rest, req, seqno);
  21438. else if (owner)
  21439. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  21440. break;
  21441. case 423: /* Interval too brief */
  21442. if (sipmethod == SIP_REGISTER)
  21443. handle_response_register(p, resp, rest, req, seqno);
  21444. break;
  21445. case 408: /* Request timeout - terminate dialog */
  21446. if (sipmethod == SIP_INVITE)
  21447. handle_response_invite(p, resp, rest, req, seqno);
  21448. else if (sipmethod == SIP_REGISTER)
  21449. handle_response_register(p, resp, rest, req, seqno);
  21450. else if (sipmethod == SIP_BYE) {
  21451. pvt_set_needdestroy(p, "received 408 response");
  21452. ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
  21453. } else {
  21454. if (owner)
  21455. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  21456. pvt_set_needdestroy(p, "received 408 response");
  21457. }
  21458. break;
  21459. case 428:
  21460. case 422: /* Session-Timers: Session Interval Too Small */
  21461. if (sipmethod == SIP_INVITE) {
  21462. handle_response_invite(p, resp, rest, req, seqno);
  21463. }
  21464. break;
  21465. case 480:
  21466. if (sipmethod == SIP_INVITE) {
  21467. handle_response_invite(p, resp, rest, req, seqno);
  21468. } else if (sipmethod == SIP_SUBSCRIBE) {
  21469. handle_response_subscribe(p, resp, rest, req, seqno);
  21470. } else if (owner) {
  21471. /* No specific handler. Default to congestion */
  21472. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  21473. }
  21474. break;
  21475. case 481: /* Call leg does not exist */
  21476. if (sipmethod == SIP_INVITE) {
  21477. handle_response_invite(p, resp, rest, req, seqno);
  21478. } else if (sipmethod == SIP_SUBSCRIBE) {
  21479. handle_response_subscribe(p, resp, rest, req, seqno);
  21480. } else if (sipmethod == SIP_BYE) {
  21481. /* The other side has no transaction to bye,
  21482. just assume it's all right then */
  21483. ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
  21484. } else if (sipmethod == SIP_CANCEL) {
  21485. /* The other side has no transaction to cancel,
  21486. just assume it's all right then */
  21487. ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
  21488. } else {
  21489. ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
  21490. /* Guessing that this is not an important request */
  21491. }
  21492. break;
  21493. case 487:
  21494. if (sipmethod == SIP_INVITE)
  21495. handle_response_invite(p, resp, rest, req, seqno);
  21496. break;
  21497. case 415: /* Unsupported media type */
  21498. case 488: /* Not acceptable here - codec error */
  21499. case 606: /* Not Acceptable */
  21500. if (sipmethod == SIP_INVITE)
  21501. handle_response_invite(p, resp, rest, req, seqno);
  21502. break;
  21503. case 491: /* Pending */
  21504. if (sipmethod == SIP_INVITE)
  21505. handle_response_invite(p, resp, rest, req, seqno);
  21506. else {
  21507. ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
  21508. pvt_set_needdestroy(p, "received 491 response");
  21509. }
  21510. break;
  21511. case 405: /* Method not allowed */
  21512. case 501: /* Not Implemented */
  21513. mark_method_unallowed(&p->allowed_methods, sipmethod);
  21514. if (p->relatedpeer) {
  21515. mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
  21516. }
  21517. if (sipmethod == SIP_INVITE)
  21518. handle_response_invite(p, resp, rest, req, seqno);
  21519. else
  21520. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
  21521. break;
  21522. default:
  21523. if ((resp >= 200) && (resp < 300)) { /* on any 2XX response do the following */
  21524. if (sipmethod == SIP_INVITE) {
  21525. handle_response_invite(p, resp, rest, req, seqno);
  21526. }
  21527. } else if ((resp >= 300) && (resp < 700)) {
  21528. /* Fatal response */
  21529. if ((resp != 487))
  21530. ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
  21531. if (sipmethod == SIP_INVITE)
  21532. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  21533. /* XXX Locking issues?? XXX */
  21534. switch(resp) {
  21535. case 300: /* Multiple Choices */
  21536. case 301: /* Moved permanently */
  21537. case 302: /* Moved temporarily */
  21538. case 305: /* Use Proxy */
  21539. if (p->owner) {
  21540. struct ast_party_redirecting redirecting;
  21541. struct ast_set_party_redirecting update_redirecting;
  21542. ast_party_redirecting_init(&redirecting);
  21543. memset(&update_redirecting, 0, sizeof(update_redirecting));
  21544. change_redirecting_information(p, req, &redirecting,
  21545. &update_redirecting, TRUE);
  21546. ast_channel_set_redirecting(p->owner, &redirecting,
  21547. &update_redirecting);
  21548. ast_party_redirecting_free(&redirecting);
  21549. }
  21550. /* Fall through */
  21551. case 486: /* Busy here */
  21552. case 600: /* Busy everywhere */
  21553. case 603: /* Decline */
  21554. if (p->owner) {
  21555. sip_handle_cc(p, req, AST_CC_CCBS);
  21556. ast_queue_control(p->owner, AST_CONTROL_BUSY);
  21557. }
  21558. break;
  21559. case 482: /* Loop Detected */
  21560. case 404: /* Not Found */
  21561. case 410: /* Gone */
  21562. case 400: /* Bad Request */
  21563. case 500: /* Server error */
  21564. if (sipmethod == SIP_SUBSCRIBE) {
  21565. handle_response_subscribe(p, resp, rest, req, seqno);
  21566. break;
  21567. }
  21568. /* Fall through */
  21569. case 502: /* Bad gateway */
  21570. case 503: /* Service Unavailable */
  21571. case 504: /* Server Timeout */
  21572. if (owner)
  21573. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  21574. break;
  21575. case 484: /* Address Incomplete */
  21576. if (owner && sipmethod != SIP_BYE) {
  21577. switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
  21578. case SIP_PAGE2_ALLOWOVERLAP_YES:
  21579. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  21580. break;
  21581. default:
  21582. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
  21583. break;
  21584. }
  21585. }
  21586. break;
  21587. default:
  21588. /* Send hangup */
  21589. if (owner && sipmethod != SIP_BYE)
  21590. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  21591. break;
  21592. }
  21593. /* ACK on invite */
  21594. if (sipmethod == SIP_INVITE)
  21595. transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  21596. sip_alreadygone(p);
  21597. if (!p->owner) {
  21598. pvt_set_needdestroy(p, "transaction completed");
  21599. }
  21600. } else if ((resp >= 100) && (resp < 200)) {
  21601. if (sipmethod == SIP_INVITE) {
  21602. if (!req->ignore && sip_cancel_destroy(p))
  21603. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  21604. if (find_sdp(req))
  21605. process_sdp(p, req, SDP_T38_NONE);
  21606. if (p->owner) {
  21607. /* Queue a progress frame */
  21608. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  21609. }
  21610. }
  21611. } else
  21612. ast_log(LOG_NOTICE, "Don't know how to handle a %d %s response from %s\n", resp, rest, p->owner ? ast_channel_name(p->owner) : ast_sockaddr_stringify(&p->sa));
  21613. }
  21614. } else {
  21615. /* Responses to OUTGOING SIP requests on INCOMING calls
  21616. get handled here. As well as out-of-call message responses */
  21617. if (req->debug)
  21618. ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
  21619. if (sipmethod == SIP_INVITE && resp == 200) {
  21620. /* Tags in early session is replaced by the tag in 200 OK, which is
  21621. the final reply to our INVITE */
  21622. char tag[128];
  21623. gettag(req, "To", tag, sizeof(tag));
  21624. ast_string_field_set(p, theirtag, tag);
  21625. }
  21626. switch(resp) {
  21627. case 200:
  21628. if (sipmethod == SIP_INVITE) {
  21629. handle_response_invite(p, resp, rest, req, seqno);
  21630. } else if (sipmethod == SIP_CANCEL) {
  21631. ast_debug(1, "Got 200 OK on CANCEL\n");
  21632. /* Wait for 487, then destroy */
  21633. } else if (sipmethod == SIP_BYE) {
  21634. pvt_set_needdestroy(p, "transaction completed");
  21635. }
  21636. break;
  21637. case 401: /* www-auth */
  21638. case 407:
  21639. if (sipmethod == SIP_INVITE)
  21640. handle_response_invite(p, resp, rest, req, seqno);
  21641. else if (sipmethod == SIP_BYE) {
  21642. if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
  21643. ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, sip_get_header(&p->initreq, "From"));
  21644. pvt_set_needdestroy(p, "failed to authenticate BYE");
  21645. }
  21646. }
  21647. break;
  21648. case 481: /* Call leg does not exist */
  21649. if (sipmethod == SIP_INVITE) {
  21650. /* Re-invite failed */
  21651. handle_response_invite(p, resp, rest, req, seqno);
  21652. } else if (sipmethod == SIP_BYE) {
  21653. pvt_set_needdestroy(p, "received 481 response");
  21654. } else if (sipdebug) {
  21655. ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
  21656. }
  21657. break;
  21658. case 501: /* Not Implemented */
  21659. if (sipmethod == SIP_INVITE)
  21660. handle_response_invite(p, resp, rest, req, seqno);
  21661. break;
  21662. default: /* Errors without handlers */
  21663. if ((resp >= 100) && (resp < 200)) {
  21664. if (sipmethod == SIP_INVITE) { /* re-invite */
  21665. if (!req->ignore && sip_cancel_destroy(p))
  21666. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  21667. }
  21668. } else if ((resp >= 200) && (resp < 300)) { /* on any unrecognized 2XX response do the following */
  21669. if (sipmethod == SIP_INVITE) {
  21670. handle_response_invite(p, resp, rest, req, seqno);
  21671. }
  21672. } else if ((resp >= 300) && (resp < 700)) {
  21673. if ((resp != 487))
  21674. ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
  21675. switch(resp) {
  21676. case 415: /* Unsupported media type */
  21677. case 488: /* Not acceptable here - codec error */
  21678. case 603: /* Decline */
  21679. case 500: /* Server error */
  21680. case 502: /* Bad gateway */
  21681. case 503: /* Service Unavailable */
  21682. case 504: /* Server timeout */
  21683. /* re-invite failed */
  21684. if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
  21685. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  21686. break;
  21687. }
  21688. }
  21689. break;
  21690. }
  21691. }
  21692. }
  21693. /*! \brief SIP pickup support function
  21694. * Starts in a new thread, then pickup the call
  21695. */
  21696. static void *sip_pickup_thread(void *stuff)
  21697. {
  21698. struct ast_channel *chan;
  21699. chan = stuff;
  21700. if (ast_pickup_call(chan)) {
  21701. ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
  21702. } else {
  21703. ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
  21704. }
  21705. ast_hangup(chan);
  21706. ast_channel_unref(chan);
  21707. chan = NULL;
  21708. return NULL;
  21709. }
  21710. /*! \brief Pickup a call using the subsystem in features.c
  21711. * This is executed in a separate thread
  21712. */
  21713. static int sip_pickup(struct ast_channel *chan)
  21714. {
  21715. pthread_t threadid;
  21716. ast_channel_ref(chan);
  21717. if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
  21718. ast_debug(1, "Unable to start Group pickup thread on channel %s\n", ast_channel_name(chan));
  21719. ast_channel_unref(chan);
  21720. return -1;
  21721. }
  21722. ast_debug(1, "Started Group pickup thread on channel %s\n", ast_channel_name(chan));
  21723. return 0;
  21724. }
  21725. /*! \brief Get tag from packet
  21726. *
  21727. * \return Returns the pointer to the provided tag buffer,
  21728. * or NULL if the tag was not found.
  21729. */
  21730. static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
  21731. {
  21732. const char *thetag;
  21733. if (!tagbuf)
  21734. return NULL;
  21735. tagbuf[0] = '\0'; /* reset the buffer */
  21736. thetag = sip_get_header(req, header);
  21737. thetag = strcasestr(thetag, ";tag=");
  21738. if (thetag) {
  21739. thetag += 5;
  21740. ast_copy_string(tagbuf, thetag, tagbufsize);
  21741. return strsep(&tagbuf, ";");
  21742. }
  21743. return NULL;
  21744. }
  21745. static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
  21746. {
  21747. struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
  21748. find_sip_monitor_instance_by_subscription_pvt, pvt);
  21749. const char *status = get_content_line(req, "cc-state", ':');
  21750. struct cc_epa_entry *cc_entry;
  21751. char *uri;
  21752. if (!monitor_instance) {
  21753. transmit_response(pvt, "400 Bad Request", req);
  21754. return -1;
  21755. }
  21756. if (ast_strlen_zero(status)) {
  21757. ao2_ref(monitor_instance, -1);
  21758. transmit_response(pvt, "400 Bad Request", req);
  21759. return -1;
  21760. }
  21761. if (!strcmp(status, "queued")) {
  21762. /* We've been told that we're queued. This is the endpoint's way of telling
  21763. * us that it has accepted our CC request. We need to alert the core of this
  21764. * development
  21765. */
  21766. ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
  21767. transmit_response(pvt, "200 OK", req);
  21768. ao2_ref(monitor_instance, -1);
  21769. return 0;
  21770. }
  21771. /* It's open! Yay! */
  21772. uri = get_content_line(req, "cc-URI", ':');
  21773. if (ast_strlen_zero(uri)) {
  21774. uri = get_in_brackets((char *)sip_get_header(req, "From"));
  21775. }
  21776. ast_string_field_set(monitor_instance, notify_uri, uri);
  21777. if (monitor_instance->suspension_entry) {
  21778. cc_entry = monitor_instance->suspension_entry->instance_data;
  21779. if (cc_entry->current_state == CC_CLOSED) {
  21780. /* If we've created a suspension entry and the current state is closed, then that means
  21781. * we got a notice from the CC core earlier to suspend monitoring, but because this particular
  21782. * call leg had not yet notified us that it was ready for recall, it meant that we
  21783. * could not yet send a PUBLISH. Now, however, we can.
  21784. */
  21785. construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
  21786. sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
  21787. transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
  21788. } else {
  21789. ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
  21790. }
  21791. } else {
  21792. ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
  21793. }
  21794. ao2_ref(monitor_instance, -1);
  21795. transmit_response(pvt, "200 OK", req);
  21796. return 0;
  21797. }
  21798. /*! \brief Handle incoming notifications */
  21799. static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
  21800. {
  21801. /* This is mostly a skeleton for future improvements */
  21802. /* Mostly created to return proper answers on notifications on outbound REFER's */
  21803. int res = 0;
  21804. const char *event = sip_get_header(req, "Event");
  21805. char *sep;
  21806. if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
  21807. *sep++ = '\0';
  21808. }
  21809. if (sipdebug)
  21810. ast_debug(2, "Got NOTIFY Event: %s\n", event);
  21811. if (!strcmp(event, "refer")) {
  21812. /* Save nesting depth for now, since there might be other events we will
  21813. support in the future */
  21814. /* Handle REFER notifications */
  21815. char *buf, *cmd, *code;
  21816. int respcode;
  21817. int success = TRUE;
  21818. /* EventID for each transfer... EventID is basically the REFER cseq
  21819. We are getting notifications on a call that we transferred
  21820. We should hangup when we are getting a 200 OK in a sipfrag
  21821. Check if we have an owner of this event */
  21822. /* Check the content type */
  21823. if (strncasecmp(sip_get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
  21824. /* We need a sipfrag */
  21825. transmit_response(p, "400 Bad request", req);
  21826. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21827. return -1;
  21828. }
  21829. /* Get the text of the attachment */
  21830. if (ast_strlen_zero(buf = get_content(req))) {
  21831. ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
  21832. transmit_response(p, "400 Bad request", req);
  21833. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21834. return -1;
  21835. }
  21836. /*
  21837. From the RFC...
  21838. A minimal, but complete, implementation can respond with a single
  21839. NOTIFY containing either the body:
  21840. SIP/2.0 100 Trying
  21841. if the subscription is pending, the body:
  21842. SIP/2.0 200 OK
  21843. if the reference was successful, the body:
  21844. SIP/2.0 503 Service Unavailable
  21845. if the reference failed, or the body:
  21846. SIP/2.0 603 Declined
  21847. if the REFER request was accepted before approval to follow the
  21848. reference could be obtained and that approval was subsequently denied
  21849. (see Section 2.4.7).
  21850. If there are several REFERs in the same dialog, we need to
  21851. match the ID of the event header...
  21852. */
  21853. ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
  21854. cmd = ast_skip_blanks(buf);
  21855. code = cmd;
  21856. /* We are at SIP/2.0 */
  21857. while(*code && (*code > 32)) { /* Search white space */
  21858. code++;
  21859. }
  21860. *code++ = '\0';
  21861. code = ast_skip_blanks(code);
  21862. sep = code;
  21863. sep++;
  21864. while(*sep && (*sep > 32)) { /* Search white space */
  21865. sep++;
  21866. }
  21867. *sep++ = '\0'; /* Response string */
  21868. respcode = atoi(code);
  21869. switch (respcode) {
  21870. case 200: /* OK: The new call is up, hangup this call */
  21871. /* Hangup the call that we are replacing */
  21872. break;
  21873. case 301: /* Moved permenantly */
  21874. case 302: /* Moved temporarily */
  21875. /* Do we get the header in the packet in this case? */
  21876. success = FALSE;
  21877. break;
  21878. case 503: /* Service Unavailable: The new call failed */
  21879. case 603: /* Declined: Not accepted */
  21880. /* Cancel transfer, continue the current call */
  21881. success = FALSE;
  21882. break;
  21883. case 0: /* Parse error */
  21884. /* Cancel transfer, continue the current call */
  21885. ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
  21886. success = FALSE;
  21887. break;
  21888. default:
  21889. if (respcode < 200) {
  21890. /* ignore provisional responses */
  21891. success = -1;
  21892. } else {
  21893. ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
  21894. success = FALSE;
  21895. }
  21896. break;
  21897. }
  21898. if (success == FALSE) {
  21899. ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
  21900. }
  21901. if (p->owner && success != -1) {
  21902. enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
  21903. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  21904. }
  21905. /* Confirm that we received this packet */
  21906. transmit_response(p, "200 OK", req);
  21907. } else if (!strcmp(event, "message-summary")) {
  21908. const char *mailbox = NULL;
  21909. char *c = ast_strdupa(get_content_line(req, "Voice-Message", ':'));
  21910. if (!p->mwi) {
  21911. struct sip_peer *peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
  21912. if (peer) {
  21913. mailbox = ast_strdupa(peer->unsolicited_mailbox);
  21914. sip_unref_peer(peer, "removing unsolicited mwi ref");
  21915. }
  21916. } else {
  21917. mailbox = p->mwi->mailbox;
  21918. }
  21919. if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
  21920. char *old = strsep(&c, " ");
  21921. char *new = strsep(&old, "/");
  21922. ast_publish_mwi_state(mailbox, "SIP_Remote", atoi(new), atoi(old));
  21923. transmit_response(p, "200 OK", req);
  21924. } else {
  21925. transmit_response(p, "489 Bad event", req);
  21926. res = -1;
  21927. }
  21928. } else if (!strcmp(event, "keep-alive")) {
  21929. /* Used by Sipura/Linksys for NAT pinhole,
  21930. * just confirm that we received the packet. */
  21931. transmit_response(p, "200 OK", req);
  21932. } else if (!strcmp(event, "call-completion")) {
  21933. res = handle_cc_notify(p, req);
  21934. } else {
  21935. /* We don't understand this event. */
  21936. transmit_response(p, "489 Bad event", req);
  21937. res = -1;
  21938. }
  21939. if (!p->lastinvite)
  21940. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21941. return res;
  21942. }
  21943. /*! \brief Handle incoming OPTIONS request
  21944. An OPTIONS request should be answered like an INVITE from the same UA, including SDP
  21945. */
  21946. static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
  21947. {
  21948. const char *msg;
  21949. enum sip_get_dest_result gotdest;
  21950. int res;
  21951. if (p->lastinvite) {
  21952. /* if this is a request in an active dialog, just confirm that the dialog exists. */
  21953. transmit_response_with_allow(p, "200 OK", req, 0);
  21954. return 0;
  21955. }
  21956. if (sip_cfg.auth_options_requests) {
  21957. /* Do authentication if this OPTIONS request began the dialog */
  21958. copy_request(&p->initreq, req);
  21959. set_pvt_allowed_methods(p, req);
  21960. res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
  21961. if (res == AUTH_CHALLENGE_SENT) {
  21962. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21963. return 0;
  21964. }
  21965. if (res < 0) { /* Something failed in authentication */
  21966. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
  21967. transmit_response(p, "403 Forbidden", req);
  21968. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21969. return 0;
  21970. }
  21971. }
  21972. /* must go through authentication before getting here */
  21973. gotdest = get_destination(p, req, NULL);
  21974. build_contact(p, req, 1);
  21975. if (ast_strlen_zero(p->context))
  21976. ast_string_field_set(p, context, sip_cfg.default_context);
  21977. if (ast_shutting_down()) {
  21978. /*
  21979. * Not taking any new calls at this time.
  21980. * Likely a server availability OPTIONS poll.
  21981. */
  21982. msg = "503 Unavailable";
  21983. } else {
  21984. msg = "404 Not Found";
  21985. switch (gotdest) {
  21986. case SIP_GET_DEST_INVALID_URI:
  21987. msg = "416 Unsupported URI scheme";
  21988. break;
  21989. case SIP_GET_DEST_EXTEN_MATCHMORE:
  21990. case SIP_GET_DEST_REFUSED:
  21991. case SIP_GET_DEST_EXTEN_NOT_FOUND:
  21992. //msg = "404 Not Found";
  21993. break;
  21994. case SIP_GET_DEST_EXTEN_FOUND:
  21995. msg = "200 OK";
  21996. break;
  21997. }
  21998. }
  21999. transmit_response_with_allow(p, msg, req, 0);
  22000. /* Destroy if this OPTIONS was the opening request, but not if
  22001. it's in the middle of a normal call flow. */
  22002. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22003. return 0;
  22004. }
  22005. /*! \brief Handle the transfer part of INVITE with a replaces: header,
  22006. *
  22007. * This is used for call-pickup and for attended transfers initiated on
  22008. * remote endpoints (i.e. a REFER received on a remote server).
  22009. *
  22010. * \note p and p->owner are locked upon entering this function. If the
  22011. * call pickup or attended transfer is successful, then p->owner will
  22012. * be unlocked upon exiting this function. This is communicated to the
  22013. * caller through the nounlock parameter.
  22014. *
  22015. * \param p The sip_pvt where the INVITE with Replaces was received
  22016. * \param req The incoming INVITE
  22017. * \param[out] nounlock Indicator if p->owner should remained locked. On successful transfer, this will be set true.
  22018. * \param replaces_pvt sip_pvt referenced by Replaces header
  22019. * \param replaces_chan replaces_pvt's owner channel
  22020. * \retval 0 Success
  22021. * \retval non-zero Failure
  22022. */
  22023. static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req,
  22024. int *nounlock, struct sip_pvt *replaces_pvt, struct ast_channel *replaces_chan)
  22025. {
  22026. struct ast_channel *c;
  22027. RAII_VAR(struct ast_bridge *, bridge, NULL, ao2_cleanup);
  22028. if (req->ignore) {
  22029. return 0;
  22030. }
  22031. if (!p->owner) {
  22032. /* What to do if no channel ??? */
  22033. ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
  22034. transmit_response_reliable(p, "503 Service Unavailable", req);
  22035. append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
  22036. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22037. return 1;
  22038. }
  22039. append_history(p, "Xfer", "INVITE/Replace received");
  22040. c = ast_channel_ref(p->owner);
  22041. /* Fake call progress */
  22042. transmit_response(p, "100 Trying", req);
  22043. ast_setstate(c, AST_STATE_RING);
  22044. ast_debug(4, "Invite/Replaces: preparing to replace %s with %s\n", ast_channel_name(replaces_chan), ast_channel_name(c));
  22045. *nounlock = 1;
  22046. ast_channel_unlock(c);
  22047. sip_pvt_unlock(p);
  22048. ast_raw_answer(c);
  22049. ast_channel_lock(replaces_chan);
  22050. bridge = ast_channel_get_bridge(replaces_chan);
  22051. ast_channel_unlock(replaces_chan);
  22052. if (bridge) {
  22053. if (ast_bridge_impart(bridge, c, replaces_chan, NULL,
  22054. AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
  22055. ast_hangup(c);
  22056. }
  22057. } else {
  22058. ast_channel_move(replaces_chan, c);
  22059. ast_hangup(c);
  22060. }
  22061. sip_pvt_lock(p);
  22062. return 0;
  22063. }
  22064. /*! \note No channel or pvt locks should be held while calling this function. */
  22065. static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
  22066. {
  22067. struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
  22068. struct ast_app *pickup = pbx_findapp("Pickup");
  22069. if (!pickup) {
  22070. ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
  22071. return -1;
  22072. }
  22073. ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
  22074. ast_debug(2, "About to call Pickup(%s)\n", ast_str_buffer(str));
  22075. /* There is no point in capturing the return value since pickup_exec
  22076. doesn't return anything meaningful unless the passed data is an empty
  22077. string (which in our case it will not be) */
  22078. pbx_exec(channel, pickup, ast_str_buffer(str));
  22079. return 0;
  22080. }
  22081. /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
  22082. static int sip_t38_abort(const void *data)
  22083. {
  22084. struct sip_pvt *p = (struct sip_pvt *) data;
  22085. sip_pvt_lock(p);
  22086. /* an application may have taken ownership of the T.38 negotiation on this
  22087. * channel while we were waiting to grab the lock... if it did, the scheduler
  22088. * id will have been reset to -1, which is our indication that we do *not*
  22089. * want to abort the negotiation process
  22090. */
  22091. if (p->t38id != -1) {
  22092. change_t38_state(p, T38_REJECTED);
  22093. transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
  22094. p->t38id = -1;
  22095. dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
  22096. }
  22097. sip_pvt_unlock(p);
  22098. return 0;
  22099. }
  22100. /*!
  22101. * \brief bare-bones support for SIP UPDATE
  22102. *
  22103. * XXX This is not even close to being RFC 3311-compliant. We don't advertise
  22104. * that we support the UPDATE method, so no one should ever try sending us
  22105. * an UPDATE anyway. However, Asterisk can send an UPDATE to change connected
  22106. * line information, so we need to be prepared to handle this. The way we distinguish
  22107. * such an UPDATE is through the X-Asterisk-rpid-update header.
  22108. *
  22109. * Actually updating the media session may be some future work.
  22110. */
  22111. static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
  22112. {
  22113. if (ast_strlen_zero(sip_get_header(req, "X-Asterisk-rpid-update"))) {
  22114. transmit_response(p, "501 Method Not Implemented", req);
  22115. return 0;
  22116. }
  22117. if (!p->owner) {
  22118. transmit_response(p, "481 Call/Transaction Does Not Exist", req);
  22119. return 0;
  22120. }
  22121. if (get_rpid(p, req)) {
  22122. struct ast_party_connected_line connected;
  22123. struct ast_set_party_connected_line update_connected;
  22124. ast_party_connected_line_init(&connected);
  22125. memset(&update_connected, 0, sizeof(update_connected));
  22126. update_connected.id.number = 1;
  22127. connected.id.number.valid = 1;
  22128. connected.id.number.str = (char *) p->cid_num;
  22129. connected.id.number.presentation = p->callingpres;
  22130. update_connected.id.name = 1;
  22131. connected.id.name.valid = 1;
  22132. connected.id.name.str = (char *) p->cid_name;
  22133. connected.id.name.presentation = p->callingpres;
  22134. /* Invalidate any earlier private connected id representation */
  22135. ast_set_party_id_all(&update_connected.priv);
  22136. connected.id.tag = (char *) p->cid_tag;
  22137. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
  22138. ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
  22139. }
  22140. transmit_response(p, "200 OK", req);
  22141. return 0;
  22142. }
  22143. /*
  22144. * \internal \brief Check Session Timers for an INVITE request
  22145. *
  22146. * \retval 0 ok
  22147. * \retval -1 failure
  22148. */
  22149. static int handle_request_invite_st(struct sip_pvt *p, struct sip_request *req,
  22150. const char *required, int reinvite)
  22151. {
  22152. const char *p_uac_se_hdr; /* UAC's Session-Expires header string */
  22153. const char *p_uac_min_se; /* UAC's requested Min-SE interval (char string) */
  22154. int uac_max_se = -1; /* UAC's Session-Expires in integer format */
  22155. int uac_min_se = -1; /* UAC's Min-SE in integer format */
  22156. int st_active = FALSE; /* Session-Timer on/off boolean */
  22157. int st_interval = 0; /* Session-Timer negotiated refresh interval */
  22158. enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO; /* Session-Timer refresher */
  22159. int dlg_min_se = -1;
  22160. int dlg_max_se = global_max_se;
  22161. int rtn;
  22162. /* Session-Timers */
  22163. if ((p->sipoptions & SIP_OPT_TIMER)) {
  22164. enum st_refresher_param st_ref_param = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
  22165. /* The UAC has requested session-timers for this session. Negotiate
  22166. the session refresh interval and who will be the refresher */
  22167. ast_debug(2, "Incoming INVITE with 'timer' option supported\n");
  22168. /* Allocate Session-Timers struct w/in the dialog */
  22169. if (!p->stimer) {
  22170. sip_st_alloc(p);
  22171. }
  22172. /* Parse the Session-Expires header */
  22173. p_uac_se_hdr = sip_get_header(req, "Session-Expires");
  22174. if (!ast_strlen_zero(p_uac_se_hdr)) {
  22175. ast_debug(2, "INVITE also has \"Session-Expires\" header.\n");
  22176. rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
  22177. tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
  22178. if (rtn != 0) {
  22179. transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
  22180. return -1;
  22181. }
  22182. }
  22183. /* Parse the Min-SE header */
  22184. p_uac_min_se = sip_get_header(req, "Min-SE");
  22185. if (!ast_strlen_zero(p_uac_min_se)) {
  22186. ast_debug(2, "INVITE also has \"Min-SE\" header.\n");
  22187. rtn = parse_minse(p_uac_min_se, &uac_min_se);
  22188. if (rtn != 0) {
  22189. transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
  22190. return -1;
  22191. }
  22192. }
  22193. dlg_min_se = st_get_se(p, FALSE);
  22194. switch (st_get_mode(p, 1)) {
  22195. case SESSION_TIMER_MODE_ACCEPT:
  22196. case SESSION_TIMER_MODE_ORIGINATE:
  22197. if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
  22198. transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
  22199. return -1;
  22200. }
  22201. p->stimer->st_active_peer_ua = TRUE;
  22202. st_active = TRUE;
  22203. if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
  22204. tmp_st_ref = st_get_refresher(p);
  22205. }
  22206. dlg_max_se = st_get_se(p, TRUE);
  22207. if (uac_max_se > 0) {
  22208. if (dlg_max_se >= uac_min_se) {
  22209. st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
  22210. } else {
  22211. st_interval = uac_max_se;
  22212. }
  22213. } else if (uac_min_se > 0) {
  22214. st_interval = MAX(dlg_max_se, uac_min_se);
  22215. } else {
  22216. st_interval = dlg_max_se;
  22217. }
  22218. break;
  22219. case SESSION_TIMER_MODE_REFUSE:
  22220. if (p->reqsipoptions & SIP_OPT_TIMER) {
  22221. transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
  22222. ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
  22223. return -1;
  22224. }
  22225. break;
  22226. default:
  22227. ast_log(LOG_ERROR, "Internal Error %u at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
  22228. break;
  22229. }
  22230. } else {
  22231. /* The UAC did not request session-timers. Asterisk (UAS), will now decide
  22232. (based on session-timer-mode in sip.conf) whether to run session-timers for
  22233. this session or not. */
  22234. switch (st_get_mode(p, 1)) {
  22235. case SESSION_TIMER_MODE_ORIGINATE:
  22236. st_active = TRUE;
  22237. st_interval = st_get_se(p, TRUE);
  22238. tmp_st_ref = SESSION_TIMER_REFRESHER_US;
  22239. p->stimer->st_active_peer_ua = (p->sipoptions & SIP_OPT_TIMER) ? TRUE : FALSE;
  22240. break;
  22241. default:
  22242. break;
  22243. }
  22244. }
  22245. if (reinvite == 0) {
  22246. /* Session-Timers: Start session refresh timer based on negotiation/config */
  22247. if (st_active == TRUE) {
  22248. p->stimer->st_active = TRUE;
  22249. p->stimer->st_interval = st_interval;
  22250. p->stimer->st_ref = tmp_st_ref;
  22251. }
  22252. } else {
  22253. if (p->stimer->st_active == TRUE) {
  22254. /* Session-Timers: A re-invite request sent within a dialog will serve as
  22255. a refresh request, no matter whether the re-invite was sent for refreshing
  22256. the session or modifying it.*/
  22257. ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
  22258. /* The UAC may be adjusting the session-timers mid-session */
  22259. if (st_interval > 0) {
  22260. p->stimer->st_interval = st_interval;
  22261. p->stimer->st_ref = tmp_st_ref;
  22262. }
  22263. }
  22264. }
  22265. return 0;
  22266. }
  22267. /*!
  22268. * \brief Handle incoming INVITE request
  22269. * \note If the INVITE has a Replaces header, it is part of an
  22270. * attended transfer. If so, we do not go through the dial
  22271. * plan but try to find the active call and masquerade
  22272. * into it
  22273. */
  22274. static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *recount, const char *e, int *nounlock)
  22275. {
  22276. int res = INV_REQ_SUCCESS;
  22277. int gotdest;
  22278. const char *p_replaces;
  22279. char *replace_id = NULL;
  22280. const char *required;
  22281. unsigned int required_profile = 0;
  22282. struct ast_channel *c = NULL; /* New channel */
  22283. struct sip_peer *authpeer = NULL; /* Matching Peer */
  22284. int reinvite = 0;
  22285. struct ast_party_redirecting redirecting;
  22286. struct ast_set_party_redirecting update_redirecting;
  22287. int supported_start = 0;
  22288. int require_start = 0;
  22289. char unsupported[256] = { 0, };
  22290. struct {
  22291. char exten[AST_MAX_EXTENSION];
  22292. char context[AST_MAX_CONTEXT];
  22293. } pickup = {
  22294. .exten = "",
  22295. };
  22296. RAII_VAR(struct sip_pvt *, replaces_pvt, NULL, ao2_cleanup);
  22297. RAII_VAR(struct ast_channel *, replaces_chan, NULL, ao2_cleanup);
  22298. /* Find out what they support */
  22299. if (!p->sipoptions) {
  22300. const char *supported = NULL;
  22301. do {
  22302. supported = __get_header(req, "Supported", &supported_start);
  22303. if (!ast_strlen_zero(supported)) {
  22304. p->sipoptions |= parse_sip_options(supported, NULL, 0);
  22305. }
  22306. } while (!ast_strlen_zero(supported));
  22307. }
  22308. /* Find out what they require */
  22309. do {
  22310. required = __get_header(req, "Require", &require_start);
  22311. if (!ast_strlen_zero(required)) {
  22312. required_profile |= parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
  22313. }
  22314. } while (!ast_strlen_zero(required));
  22315. /* If there are any options required that we do not support,
  22316. * then send a 420 with only those unsupported options listed */
  22317. if (!ast_strlen_zero(unsupported)) {
  22318. transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
  22319. ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
  22320. p->invitestate = INV_COMPLETED;
  22321. if (!p->lastinvite) {
  22322. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22323. }
  22324. res = -1;
  22325. goto request_invite_cleanup;
  22326. }
  22327. /* The option tags may be present in Supported: or Require: headers.
  22328. Include the Require: option tags for further processing as well */
  22329. p->sipoptions |= required_profile;
  22330. p->reqsipoptions = required_profile;
  22331. /* Check if this is a loop */
  22332. if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED) && ast_channel_state(p->owner) != AST_STATE_UP) {
  22333. /* This is a call to ourself. Send ourselves an error code and stop
  22334. processing immediately, as SIP really has no good mechanism for
  22335. being able to call yourself */
  22336. /* If pedantic is on, we need to check the tags. If they're different, this is
  22337. in fact a forked call through a SIP proxy somewhere. */
  22338. int different;
  22339. const char *initial_rlpart2 = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
  22340. const char *this_rlpart2 = REQ_OFFSET_TO_STR(req, rlpart2);
  22341. if (sip_cfg.pedanticsipchecking)
  22342. different = sip_uri_cmp(initial_rlpart2, this_rlpart2);
  22343. else
  22344. different = strcmp(initial_rlpart2, this_rlpart2);
  22345. if (!different) {
  22346. transmit_response(p, "482 Loop Detected", req);
  22347. p->invitestate = INV_COMPLETED;
  22348. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22349. res = INV_REQ_FAILED;
  22350. goto request_invite_cleanup;
  22351. } else {
  22352. /*! This is a spiral. What we need to do is to just change the outgoing INVITE
  22353. * so that it now routes to the new Request URI. Since we created the INVITE ourselves
  22354. * that should be all we need to do.
  22355. *
  22356. * \todo XXX This needs to be reviewed. YOu don't change the request URI really, you route the packet
  22357. * correctly instead...
  22358. */
  22359. char *uri = ast_strdupa(this_rlpart2);
  22360. char *at = strchr(uri, '@');
  22361. char *peerorhost;
  22362. ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlpart2, this_rlpart2);
  22363. transmit_response(p, "100 Trying", req);
  22364. if (at) {
  22365. *at = '\0';
  22366. }
  22367. /* Parse out "sip:" */
  22368. if ((peerorhost = strchr(uri, ':'))) {
  22369. *peerorhost++ = '\0';
  22370. }
  22371. ast_string_field_set(p, theirtag, NULL);
  22372. /* Treat this as if there were a call forward instead...
  22373. */
  22374. ast_channel_call_forward_set(p->owner, peerorhost);
  22375. ast_queue_control(p->owner, AST_CONTROL_BUSY);
  22376. res = INV_REQ_FAILED;
  22377. goto request_invite_cleanup;
  22378. }
  22379. }
  22380. if (!req->ignore && p->pendinginvite) {
  22381. if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
  22382. /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
  22383. * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
  22384. * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
  22385. * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
  22386. * credentials based on one we challenged earlier.
  22387. *
  22388. * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
  22389. * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
  22390. * from the previous transaction from the list of outstanding packets.
  22391. */
  22392. __sip_ack(p, p->pendinginvite, 1, 0);
  22393. } else {
  22394. /* We already have a pending invite. Sorry. You are on hold. */
  22395. p->glareinvite = seqno;
  22396. transmit_response_reliable(p, "491 Request Pending", req);
  22397. check_via(p, req);
  22398. ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
  22399. /* Don't destroy dialog here */
  22400. res = INV_REQ_FAILED;
  22401. goto request_invite_cleanup;
  22402. }
  22403. }
  22404. p_replaces = sip_get_header(req, "Replaces");
  22405. if (!ast_strlen_zero(p_replaces)) {
  22406. /* We have a replaces header */
  22407. char *ptr;
  22408. char *fromtag = NULL;
  22409. char *totag = NULL;
  22410. char *start, *to;
  22411. int error = 0;
  22412. if (p->owner) {
  22413. ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
  22414. transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
  22415. check_via(p, req);
  22416. copy_request(&p->initreq, req);
  22417. /* Do not destroy existing call */
  22418. res = INV_REQ_ERROR;
  22419. goto request_invite_cleanup;
  22420. }
  22421. if (sipdebug)
  22422. ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
  22423. /* Create a buffer we can manipulate */
  22424. replace_id = ast_strdupa(p_replaces);
  22425. ast_uri_decode(replace_id, ast_uri_sip_user);
  22426. if (!sip_refer_alloc(p)) {
  22427. transmit_response_reliable(p, "500 Server Internal Error", req);
  22428. append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
  22429. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22430. p->invitestate = INV_COMPLETED;
  22431. res = INV_REQ_ERROR;
  22432. check_via(p, req);
  22433. copy_request(&p->initreq, req);
  22434. goto request_invite_cleanup;
  22435. }
  22436. /* Todo: (When we find phones that support this)
  22437. if the replaces header contains ";early-only"
  22438. we can only replace the call in early
  22439. stage, not after it's up.
  22440. If it's not in early mode, 486 Busy.
  22441. */
  22442. /* Skip leading whitespace */
  22443. replace_id = ast_skip_blanks(replace_id);
  22444. start = replace_id;
  22445. while ( (ptr = strsep(&start, ";")) ) {
  22446. ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
  22447. if ( (to = strcasestr(ptr, "to-tag=") ) )
  22448. totag = to + 7; /* skip the keyword */
  22449. else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
  22450. fromtag = to + 9; /* skip the keyword */
  22451. fromtag = strsep(&fromtag, "&"); /* trim what ? */
  22452. }
  22453. }
  22454. if (sipdebug)
  22455. ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
  22456. replace_id,
  22457. fromtag ? fromtag : "<no from tag>",
  22458. totag ? totag : "<no to tag>");
  22459. /* Try to find call that we are replacing.
  22460. If we have a Replaces header, we need to cancel that call if we succeed with this call.
  22461. First we cheat a little and look for a magic call-id from phones that support
  22462. dialog-info+xml so we can do technology independent pickup... */
  22463. if (strncmp(replace_id, "pickup-", 7) == 0) {
  22464. RAII_VAR(struct sip_pvt *, subscription, NULL, ao2_cleanup);
  22465. RAII_VAR(struct ast_channel *, subscription_chan, NULL, ao2_cleanup);
  22466. replace_id += 7; /* Worst case we are looking at \0 */
  22467. if (get_sip_pvt_from_replaces(replace_id, totag, fromtag, &subscription, &subscription_chan)) {
  22468. ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
  22469. transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
  22470. error = 1;
  22471. } else {
  22472. SCOPED_LOCK(lock, subscription, sip_pvt_lock, sip_pvt_unlock);
  22473. ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
  22474. ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
  22475. ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
  22476. }
  22477. }
  22478. if (!error && ast_strlen_zero(pickup.exten) && get_sip_pvt_from_replaces(replace_id,
  22479. totag, fromtag, &replaces_pvt, &replaces_chan)) {
  22480. ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
  22481. transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
  22482. error = 1;
  22483. }
  22484. /* The matched call is the call from the transferer to Asterisk .
  22485. We want to bridge the bridged part of the call to the
  22486. incoming invite, thus taking over the refered call */
  22487. if (replaces_pvt == p) {
  22488. ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
  22489. transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
  22490. error = 1;
  22491. }
  22492. if (!error && ast_strlen_zero(pickup.exten) && !replaces_chan) {
  22493. /* Oops, someting wrong anyway, no owner, no call */
  22494. ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
  22495. /* Check for better return code */
  22496. transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
  22497. error = 1;
  22498. }
  22499. if (!error && ast_strlen_zero(pickup.exten) &&
  22500. ast_channel_state(replaces_chan) != AST_STATE_RINGING &&
  22501. ast_channel_state(replaces_chan) != AST_STATE_RING &&
  22502. ast_channel_state(replaces_chan) != AST_STATE_UP) {
  22503. ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
  22504. transmit_response_reliable(p, "603 Declined (Replaces)", req);
  22505. error = 1;
  22506. }
  22507. if (error) { /* Give up this dialog */
  22508. append_history(p, "Xfer", "INVITE/Replace Failed.");
  22509. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22510. p->invitestate = INV_COMPLETED;
  22511. res = INV_REQ_ERROR;
  22512. check_via(p, req);
  22513. copy_request(&p->initreq, req);
  22514. goto request_invite_cleanup;
  22515. }
  22516. }
  22517. /* Check if this is an INVITE that sets up a new dialog or
  22518. a re-invite in an existing dialog */
  22519. if (!req->ignore) {
  22520. int newcall = (p->initreq.headers ? TRUE : FALSE);
  22521. if (sip_cancel_destroy(p))
  22522. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  22523. /* This also counts as a pending invite */
  22524. p->pendinginvite = seqno;
  22525. check_via(p, req);
  22526. copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
  22527. if (sipdebug)
  22528. ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  22529. if (!p->owner) { /* Not a re-invite */
  22530. if (req->debug)
  22531. ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
  22532. if (newcall)
  22533. append_history(p, "Invite", "New call: %s", p->callid);
  22534. parse_ok_contact(p, req);
  22535. } else { /* Re-invite on existing call */
  22536. ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
  22537. if (get_rpid(p, req)) {
  22538. struct ast_party_connected_line connected;
  22539. struct ast_set_party_connected_line update_connected;
  22540. ast_party_connected_line_init(&connected);
  22541. memset(&update_connected, 0, sizeof(update_connected));
  22542. update_connected.id.number = 1;
  22543. connected.id.number.valid = 1;
  22544. connected.id.number.str = (char *) p->cid_num;
  22545. connected.id.number.presentation = p->callingpres;
  22546. update_connected.id.name = 1;
  22547. connected.id.name.valid = 1;
  22548. connected.id.name.str = (char *) p->cid_name;
  22549. connected.id.name.presentation = p->callingpres;
  22550. /* Invalidate any earlier private connected id representation */
  22551. ast_set_party_id_all(&update_connected.priv);
  22552. connected.id.tag = (char *) p->cid_tag;
  22553. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
  22554. ast_channel_queue_connected_line_update(p->owner, &connected,
  22555. &update_connected);
  22556. }
  22557. /* Handle SDP here if we already have an owner */
  22558. if (find_sdp(req)) {
  22559. if (process_sdp(p, req, SDP_T38_INITIATE)) {
  22560. if (!ast_strlen_zero(sip_get_header(req, "Content-Encoding"))) {
  22561. /* Asterisk does not yet support any Content-Encoding methods. Always
  22562. * attempt to process the sdp, but return a 415 if a Content-Encoding header
  22563. * was present after processing failed. */
  22564. transmit_response_reliable(p, "415 Unsupported Media type", req);
  22565. } else {
  22566. transmit_response_reliable(p, "488 Not acceptable here", req);
  22567. }
  22568. if (!p->lastinvite)
  22569. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22570. res = INV_REQ_ERROR;
  22571. goto request_invite_cleanup;
  22572. }
  22573. ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
  22574. } else {
  22575. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  22576. ast_format_cap_append_from_cap(p->jointcaps, p->caps, AST_MEDIA_TYPE_UNKNOWN);
  22577. ast_debug(1, "Hm.... No sdp for the moment\n");
  22578. /* Some devices signal they want to be put off hold by sending a re-invite
  22579. *without* an SDP, which is supposed to mean "Go back to your state"
  22580. and since they put os on remote hold, we go back to off hold */
  22581. if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  22582. ast_queue_unhold(p->owner);
  22583. /* Activate a re-invite */
  22584. ast_queue_frame(p->owner, &ast_null_frame);
  22585. change_hold_state(p, req, FALSE, 0);
  22586. }
  22587. }
  22588. if (p->do_history) /* This is a response, note what it was for */
  22589. append_history(p, "ReInv", "Re-invite received");
  22590. }
  22591. } else if (req->debug)
  22592. ast_verbose("Ignoring this INVITE request\n");
  22593. if (!p->lastinvite && !req->ignore && !p->owner) {
  22594. /* This is a new invite */
  22595. /* Handle authentication if this is our first invite */
  22596. int cc_recall_core_id = -1;
  22597. set_pvt_allowed_methods(p, req);
  22598. res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
  22599. if (res == AUTH_CHALLENGE_SENT) {
  22600. p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
  22601. goto request_invite_cleanup;
  22602. }
  22603. if (res < 0) { /* Something failed in authentication */
  22604. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
  22605. transmit_response_reliable(p, "403 Forbidden", req);
  22606. p->invitestate = INV_COMPLETED;
  22607. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22608. goto request_invite_cleanup;
  22609. }
  22610. /* Successful authentication and peer matching so record the peer related to this pvt (for easy access to peer settings) */
  22611. if (p->relatedpeer) {
  22612. p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
  22613. }
  22614. if (authpeer) {
  22615. p->relatedpeer = sip_ref_peer(authpeer, "setting dialog's relatedpeer pointer");
  22616. }
  22617. req->authenticated = 1;
  22618. /* We have a successful authentication, process the SDP portion if there is one */
  22619. if (find_sdp(req)) {
  22620. if (process_sdp(p, req, SDP_T38_INITIATE)) {
  22621. /* Asterisk does not yet support any Content-Encoding methods. Always
  22622. * attempt to process the sdp, but return a 415 if a Content-Encoding header
  22623. * was present after processing fails. */
  22624. if (!ast_strlen_zero(sip_get_header(req, "Content-Encoding"))) {
  22625. transmit_response_reliable(p, "415 Unsupported Media type", req);
  22626. } else {
  22627. /* Unacceptable codecs */
  22628. transmit_response_reliable(p, "488 Not acceptable here", req);
  22629. }
  22630. p->invitestate = INV_COMPLETED;
  22631. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22632. ast_debug(1, "No compatible codecs for this SIP call.\n");
  22633. res = INV_REQ_ERROR;
  22634. goto request_invite_cleanup;
  22635. }
  22636. } else { /* No SDP in invite, call control session */
  22637. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  22638. ast_format_cap_append_from_cap(p->jointcaps, p->caps, AST_MEDIA_TYPE_UNKNOWN);
  22639. ast_debug(2, "No SDP in Invite, third party call control\n");
  22640. }
  22641. /* Initialize the context if it hasn't been already */
  22642. if (ast_strlen_zero(p->context))
  22643. ast_string_field_set(p, context, sip_cfg.default_context);
  22644. /* Check number of concurrent calls -vs- incoming limit HERE */
  22645. ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
  22646. if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
  22647. if (res < 0) {
  22648. ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
  22649. transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
  22650. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22651. p->invitestate = INV_COMPLETED;
  22652. res = AUTH_SESSION_LIMIT;
  22653. }
  22654. goto request_invite_cleanup;
  22655. }
  22656. gotdest = get_destination(p, NULL, &cc_recall_core_id); /* Get destination right away */
  22657. extract_uri(p, req); /* Get the Contact URI */
  22658. build_contact(p, req, 1); /* Build our contact header */
  22659. if (p->rtp) {
  22660. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  22661. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  22662. }
  22663. if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) { /* No matching extension found */
  22664. switch(gotdest) {
  22665. case SIP_GET_DEST_INVALID_URI:
  22666. transmit_response_reliable(p, "416 Unsupported URI scheme", req);
  22667. break;
  22668. case SIP_GET_DEST_EXTEN_MATCHMORE:
  22669. if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
  22670. == SIP_PAGE2_ALLOWOVERLAP_YES) {
  22671. transmit_response_reliable(p, "484 Address Incomplete", req);
  22672. break;
  22673. }
  22674. /*
  22675. * XXX We would have to implement collecting more digits in
  22676. * chan_sip for any other schemes of overlap dialing.
  22677. *
  22678. * For SIP_PAGE2_ALLOWOVERLAP_DTMF it is better to do this in
  22679. * the dialplan using the Incomplete application rather than
  22680. * having the channel driver do it.
  22681. */
  22682. /* Fall through */
  22683. case SIP_GET_DEST_EXTEN_NOT_FOUND:
  22684. {
  22685. char *decoded_exten = ast_strdupa(p->exten);
  22686. transmit_response_reliable(p, "404 Not Found", req);
  22687. ast_uri_decode(decoded_exten, ast_uri_sip_user);
  22688. ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
  22689. " '%s' rejected because extension not found in context '%s'.\n",
  22690. S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
  22691. }
  22692. break;
  22693. case SIP_GET_DEST_REFUSED:
  22694. default:
  22695. transmit_response_reliable(p, "403 Forbidden", req);
  22696. } /* end switch */
  22697. p->invitestate = INV_COMPLETED;
  22698. update_call_counter(p, DEC_CALL_LIMIT);
  22699. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22700. res = INV_REQ_FAILED;
  22701. goto request_invite_cleanup;
  22702. } else {
  22703. /* If no extension was specified, use the s one */
  22704. /* Basically for calling to IP/Host name only */
  22705. if (ast_strlen_zero(p->exten))
  22706. ast_string_field_set(p, exten, "s");
  22707. /* Initialize our tag */
  22708. make_our_tag(p);
  22709. if (handle_request_invite_st(p, req, required, reinvite)) {
  22710. p->invitestate = INV_COMPLETED;
  22711. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22712. res = INV_REQ_ERROR;
  22713. goto request_invite_cleanup;
  22714. }
  22715. /* First invitation - create the channel. Allocation
  22716. * failures are handled below. */
  22717. c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL, NULL, p->logger_callid);
  22718. if (cc_recall_core_id != -1) {
  22719. ast_setup_cc_recall_datastore(c, cc_recall_core_id);
  22720. ast_cc_agent_set_interfaces_chanvar(c);
  22721. }
  22722. *recount = 1;
  22723. /* Save Record-Route for any later requests we make on this dialogue */
  22724. build_route(p, req, 0, 0);
  22725. if (c) {
  22726. ast_party_redirecting_init(&redirecting);
  22727. memset(&update_redirecting, 0, sizeof(update_redirecting));
  22728. change_redirecting_information(p, req, &redirecting, &update_redirecting,
  22729. FALSE); /*Will return immediately if no Diversion header is present */
  22730. ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
  22731. ast_party_redirecting_free(&redirecting);
  22732. }
  22733. }
  22734. } else {
  22735. ast_party_redirecting_init(&redirecting);
  22736. memset(&update_redirecting, 0, sizeof(update_redirecting));
  22737. if (sipdebug) {
  22738. if (!req->ignore)
  22739. ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
  22740. else
  22741. ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
  22742. }
  22743. if (!req->ignore)
  22744. reinvite = 1;
  22745. if (handle_request_invite_st(p, req, required, reinvite)) {
  22746. p->invitestate = INV_COMPLETED;
  22747. if (!p->lastinvite) {
  22748. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22749. }
  22750. res = INV_REQ_ERROR;
  22751. goto request_invite_cleanup;
  22752. }
  22753. c = p->owner;
  22754. change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE); /*Will return immediately if no Diversion header is present */
  22755. if (c) {
  22756. ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
  22757. }
  22758. ast_party_redirecting_free(&redirecting);
  22759. }
  22760. /* Check if OLI/ANI-II is present in From: */
  22761. parse_oli(req, p->owner);
  22762. if (reinvite && p->stimer->st_active == TRUE) {
  22763. restart_session_timer(p);
  22764. }
  22765. if (!req->ignore && p)
  22766. p->lastinvite = seqno;
  22767. if (c && replace_id) { /* Attended transfer or call pickup - we're the target */
  22768. if (!ast_strlen_zero(pickup.exten)) {
  22769. append_history(p, "Xfer", "INVITE/Replace received");
  22770. /* Let the caller know we're giving it a shot */
  22771. transmit_response(p, "100 Trying", req);
  22772. p->invitestate = INV_PROCEEDING;
  22773. ast_setstate(c, AST_STATE_RING);
  22774. /* Do the pickup itself */
  22775. ast_channel_unlock(c);
  22776. *nounlock = 1;
  22777. /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
  22778. * magic pickup and ast_hangup. Both of these functions will attempt to lock
  22779. * p->owner again, which can cause a deadlock if we already hold a lock on p.
  22780. * Locking order is, channel then pvt. Dead lock avoidance must be used if
  22781. * called the other way around. */
  22782. sip_pvt_unlock(p);
  22783. do_magic_pickup(c, pickup.exten, pickup.context);
  22784. /* Now we're either masqueraded or we failed to pickup, in either case we... */
  22785. ast_hangup(c);
  22786. sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
  22787. res = INV_REQ_FAILED;
  22788. goto request_invite_cleanup;
  22789. } else {
  22790. /* Go and take over the target call */
  22791. if (sipdebug)
  22792. ast_debug(4, "Sending this call to the invite/replaces handler %s\n", p->callid);
  22793. res = handle_invite_replaces(p, req, nounlock, replaces_pvt, replaces_chan);
  22794. goto request_invite_cleanup;
  22795. }
  22796. }
  22797. if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
  22798. enum ast_channel_state c_state = ast_channel_state(c);
  22799. RAII_VAR(struct ast_features_pickup_config *, pickup_cfg, ast_get_chan_features_pickup_config(c), ao2_cleanup);
  22800. const char *pickupexten;
  22801. if (!pickup_cfg) {
  22802. ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
  22803. pickupexten = "";
  22804. } else {
  22805. pickupexten = ast_strdupa(pickup_cfg->pickupexten);
  22806. }
  22807. if (c_state != AST_STATE_UP && reinvite &&
  22808. (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
  22809. /* If these conditions are true, and the channel is still in the 'ringing'
  22810. * state, then this likely means that we have a situation where the initial
  22811. * INVITE transaction has completed *but* the channel's state has not yet been
  22812. * changed to UP. The reason this could happen is if the reinvite is received
  22813. * on the SIP socket prior to an application calling ast_read on this channel
  22814. * to read the answer frame we earlier queued on it. In this case, the reinvite
  22815. * is completely legitimate so we need to handle this the same as if the channel
  22816. * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
  22817. */
  22818. c_state = AST_STATE_UP;
  22819. }
  22820. switch(c_state) {
  22821. case AST_STATE_DOWN:
  22822. ast_debug(2, "%s: New call is still down.... Trying... \n", ast_channel_name(c));
  22823. transmit_provisional_response(p, "100 Trying", req, 0);
  22824. p->invitestate = INV_PROCEEDING;
  22825. ast_setstate(c, AST_STATE_RING);
  22826. if (strcmp(p->exten, pickupexten)) { /* Call to extension -start pbx on this call */
  22827. enum ast_pbx_result result;
  22828. result = ast_pbx_start(c);
  22829. switch(result) {
  22830. case AST_PBX_FAILED:
  22831. sip_alreadygone(p);
  22832. ast_log(LOG_WARNING, "Failed to start PBX :(\n");
  22833. p->invitestate = INV_COMPLETED;
  22834. transmit_response_reliable(p, "503 Unavailable", req);
  22835. break;
  22836. case AST_PBX_CALL_LIMIT:
  22837. sip_alreadygone(p);
  22838. ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
  22839. p->invitestate = INV_COMPLETED;
  22840. transmit_response_reliable(p, "480 Temporarily Unavailable", req);
  22841. res = AUTH_SESSION_LIMIT;
  22842. break;
  22843. case AST_PBX_SUCCESS:
  22844. /* nothing to do */
  22845. break;
  22846. }
  22847. if (result) {
  22848. /* Unlock locks so ast_hangup can do its magic */
  22849. ast_channel_unlock(c);
  22850. *nounlock = 1;
  22851. sip_pvt_unlock(p);
  22852. ast_hangup(c);
  22853. sip_pvt_lock(p);
  22854. c = NULL;
  22855. }
  22856. } else { /* Pickup call in call group */
  22857. if (sip_pickup(c)) {
  22858. ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", ast_channel_name(c));
  22859. transmit_response_reliable(p, "480 Temporarily Unavailable", req);
  22860. sip_alreadygone(p);
  22861. ast_channel_hangupcause_set(c, AST_CAUSE_FAILURE);
  22862. /* Unlock locks so ast_hangup can do its magic */
  22863. ast_channel_unlock(c);
  22864. *nounlock = 1;
  22865. p->invitestate = INV_COMPLETED;
  22866. sip_pvt_unlock(p);
  22867. ast_hangup(c);
  22868. sip_pvt_lock(p);
  22869. c = NULL;
  22870. }
  22871. }
  22872. break;
  22873. case AST_STATE_RING:
  22874. transmit_provisional_response(p, "100 Trying", req, 0);
  22875. p->invitestate = INV_PROCEEDING;
  22876. break;
  22877. case AST_STATE_RINGING:
  22878. transmit_provisional_response(p, "180 Ringing", req, 0);
  22879. p->invitestate = INV_PROCEEDING;
  22880. break;
  22881. case AST_STATE_UP:
  22882. ast_debug(2, "%s: This call is UP.... \n", ast_channel_name(c));
  22883. transmit_response(p, "100 Trying", req);
  22884. if (p->t38.state == T38_PEER_REINVITE) {
  22885. if (p->t38id > -1) {
  22886. /* reset t38 abort timer */
  22887. AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
  22888. }
  22889. p->t38id = ast_sched_add(sched, 5000, sip_t38_abort, dialog_ref(p, "passing dialog ptr into sched structure based on t38id for sip_t38_abort."));
  22890. } else if (p->t38.state == T38_ENABLED) {
  22891. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  22892. transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
  22893. } else if ((p->t38.state == T38_DISABLED) || (p->t38.state == T38_REJECTED)) {
  22894. /* If this is not a re-invite or something to ignore - it's critical */
  22895. if (p->srtp && !ast_test_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK)) {
  22896. ast_log(LOG_WARNING, "Target does not support required crypto\n");
  22897. transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
  22898. } else {
  22899. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  22900. transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
  22901. ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
  22902. }
  22903. }
  22904. p->invitestate = INV_TERMINATED;
  22905. break;
  22906. default:
  22907. ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %u\n", ast_channel_state(c));
  22908. transmit_response(p, "100 Trying", req);
  22909. break;
  22910. }
  22911. } else {
  22912. if (!req->ignore && p && (p->autokillid == -1)) {
  22913. const char *msg;
  22914. if ((!ast_format_cap_count(p->jointcaps)))
  22915. msg = "488 Not Acceptable Here (codec error)";
  22916. else {
  22917. ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
  22918. msg = "503 Unavailable";
  22919. }
  22920. transmit_response_reliable(p, msg, req);
  22921. p->invitestate = INV_COMPLETED;
  22922. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22923. }
  22924. }
  22925. request_invite_cleanup:
  22926. if (authpeer) {
  22927. authpeer = sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_invite authpeer");
  22928. }
  22929. return res;
  22930. }
  22931. /*! \brief Check for the presence of OLI tag(s) in the From header and set on the channel
  22932. */
  22933. static void parse_oli(struct sip_request *req, struct ast_channel *chan)
  22934. {
  22935. const char *from = NULL;
  22936. const char *s = NULL;
  22937. int ani2 = 0;
  22938. if (!chan || !req) {
  22939. /* null pointers are not helpful */
  22940. return;
  22941. }
  22942. from = sip_get_header(req, "From");
  22943. if (ast_strlen_zero(from)) {
  22944. /* no From header */
  22945. return;
  22946. }
  22947. /* Look for the possible OLI tags. */
  22948. if ((s = strcasestr(from, ";isup-oli="))) {
  22949. s += 10;
  22950. } else if ((s = strcasestr(from, ";ss7-oli="))) {
  22951. s += 9;
  22952. } else if ((s = strcasestr(from, ";oli="))) {
  22953. s += 5;
  22954. }
  22955. if (ast_strlen_zero(s)) {
  22956. /* OLI tag is missing, or present with nothing following the '=' sign */
  22957. return;
  22958. }
  22959. /* just in case OLI is quoted */
  22960. if (*s == '\"') {
  22961. s++;
  22962. }
  22963. if (sscanf(s, "%d", &ani2)) {
  22964. ast_channel_caller(chan)->ani2 = ani2;
  22965. }
  22966. return;
  22967. }
  22968. /*! \brief Find all call legs and bridge transferee with target
  22969. * called from handle_request_refer
  22970. *
  22971. * \note this function assumes two locks to begin with, sip_pvt transferer and current.chan1 (the pvt's owner)...
  22972. * 2 additional locks are held at the beginning of the function, targetcall_pvt, and targetcall_pvt's owner
  22973. * channel (which is stored in target.chan1). These 2 locks _MUST_ be let go by the end of the function. Do
  22974. * not be confused into thinking a pvt's owner is the same thing as the channels locked at the beginning of
  22975. * this function, after the masquerade this may not be true. Be consistent and unlock only the exact same
  22976. * pointers that were locked to begin with.
  22977. *
  22978. * If this function is successful, only the transferer pvt lock will remain on return. Setting nounlock indicates
  22979. * to handle_request_do() that the pvt's owner it locked does not require an unlock.
  22980. */
  22981. static int local_attended_transfer(struct sip_pvt *transferer, struct ast_channel *transferer_chan, uint32_t seqno, int *nounlock)
  22982. {
  22983. RAII_VAR(struct sip_pvt *, targetcall_pvt, NULL, ao2_cleanup);
  22984. RAII_VAR(struct ast_channel *, targetcall_chan, NULL, ao2_cleanup);
  22985. enum ast_transfer_result transfer_res;
  22986. /* Check if the call ID of the replaces header does exist locally */
  22987. if (get_sip_pvt_from_replaces(transferer->refer->replaces_callid,
  22988. transferer->refer->replaces_callid_totag,
  22989. transferer->refer->replaces_callid_fromtag,
  22990. &targetcall_pvt, &targetcall_chan)) {
  22991. if (transferer->refer->localtransfer) {
  22992. /* We did not find the refered call. Sorry, can't accept then */
  22993. /* Let's fake a response from someone else in order
  22994. to follow the standard */
  22995. transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
  22996. append_history(transferer, "Xfer", "Refer failed");
  22997. ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
  22998. transferer->refer->status = REFER_FAILED;
  22999. return -1;
  23000. }
  23001. /* Fall through for remote transfers that we did not find locally */
  23002. ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
  23003. return 0;
  23004. }
  23005. if (!targetcall_chan) { /* No active channel */
  23006. ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
  23007. /* Cancel transfer */
  23008. transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
  23009. append_history(transferer, "Xfer", "Refer failed");
  23010. ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
  23011. transferer->refer->status = REFER_FAILED;
  23012. return -1;
  23013. }
  23014. ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
  23015. sip_pvt_unlock(transferer);
  23016. ast_channel_unlock(transferer_chan);
  23017. *nounlock = 1;
  23018. transfer_res = ast_bridge_transfer_attended(transferer_chan, targetcall_chan);
  23019. sip_pvt_lock(transferer);
  23020. switch (transfer_res) {
  23021. case AST_BRIDGE_TRANSFER_SUCCESS:
  23022. transferer->refer->status = REFER_200OK;
  23023. transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
  23024. append_history(transferer, "Xfer", "Refer succeeded");
  23025. return 1;
  23026. case AST_BRIDGE_TRANSFER_FAIL:
  23027. transferer->refer->status = REFER_FAILED;
  23028. transmit_notify_with_sipfrag(transferer, seqno, "500 Internal Server Error", TRUE);
  23029. append_history(transferer, "Xfer", "Refer failed (internal error)");
  23030. ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23031. return -1;
  23032. case AST_BRIDGE_TRANSFER_INVALID:
  23033. transferer->refer->status = REFER_FAILED;
  23034. transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
  23035. append_history(transferer, "Xfer", "Refer failed (invalid bridge state)");
  23036. ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23037. return -1;
  23038. case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
  23039. transferer->refer->status = REFER_FAILED;
  23040. transmit_notify_with_sipfrag(transferer, seqno, "403 Forbidden", TRUE);
  23041. append_history(transferer, "Xfer", "Refer failed (operation not permitted)");
  23042. ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23043. return -1;
  23044. default:
  23045. break;
  23046. }
  23047. return 1;
  23048. }
  23049. /*!
  23050. * Data to set on a channel that runs dialplan
  23051. * at the completion of a blind transfer
  23052. */
  23053. struct blind_transfer_cb_data {
  23054. /*! Contents of the REFER's Referred-by header */
  23055. const char *referred_by;
  23056. /*! Domain of the URI in the REFER's Refer-To header */
  23057. const char *domain;
  23058. /*! Contents of what to place in a Replaces header of an INVITE */
  23059. const char *replaces;
  23060. /*! Redirecting information to set on the channel */
  23061. struct ast_party_redirecting redirecting;
  23062. /*! Parts of the redirecting structure that are to be updated */
  23063. struct ast_set_party_redirecting update_redirecting;
  23064. };
  23065. /*!
  23066. * \internal
  23067. * \brief Callback called on new outbound channel during blind transfer
  23068. *
  23069. * We use this opportunity to populate the channel with data from the REFER
  23070. * so that, if necessary, we can include proper information on any new INVITE
  23071. * we may send out.
  23072. *
  23073. * \param chan The new outbound channel
  23074. * \param user_data A blind_transfer_cb_data struct
  23075. * \param transfer_type Unused
  23076. */
  23077. static void blind_transfer_cb(struct ast_channel *chan, struct transfer_channel_data *user_data_wrapper,
  23078. enum ast_transfer_type transfer_type)
  23079. {
  23080. struct blind_transfer_cb_data *cb_data = user_data_wrapper->data;
  23081. pbx_builtin_setvar_helper(chan, "SIPTRANSFER", "yes");
  23082. pbx_builtin_setvar_helper(chan, "SIPTRANSFER_REFERER", cb_data->referred_by);
  23083. pbx_builtin_setvar_helper(chan, "SIPTRANSFER_REPLACES", cb_data->replaces);
  23084. pbx_builtin_setvar_helper(chan, "SIPDOMAIN", cb_data->domain);
  23085. ast_channel_update_redirecting(chan, &cb_data->redirecting, &cb_data->update_redirecting);
  23086. }
  23087. /*! \brief Handle incoming REFER request */
  23088. /*! \page SIP_REFER SIP transfer Support (REFER)
  23089. REFER is used for call transfer in SIP. We get a REFER
  23090. to place a new call with an INVITE somwhere and then
  23091. keep the transferor up-to-date of the transfer. If the
  23092. transfer fails, get back on line with the orginal call.
  23093. - REFER can be sent outside or inside of a dialog.
  23094. Asterisk only accepts REFER inside of a dialog.
  23095. - If we get a replaces header, it is an attended transfer
  23096. \par Blind transfers
  23097. The transferor provides the transferee
  23098. with the transfer targets contact. The signalling between
  23099. transferer or transferee should not be cancelled, so the
  23100. call is recoverable if the transfer target can not be reached
  23101. by the transferee.
  23102. In this case, Asterisk receives a TRANSFER from
  23103. the transferor, thus is the transferee. We should
  23104. try to set up a call to the contact provided
  23105. and if that fails, re-connect the current session.
  23106. If the new call is set up, we issue a hangup.
  23107. In this scenario, we are following section 5.2
  23108. in the SIP CC Transfer draft. (Transfer without
  23109. a GRUU)
  23110. \par Transfer with consultation hold
  23111. In this case, the transferor
  23112. talks to the transfer target before the transfer takes place.
  23113. This is implemented with SIP hold and transfer.
  23114. Note: The invite From: string could indicate a transfer.
  23115. (Section 6. Transfer with consultation hold)
  23116. The transferor places the transferee on hold, starts a call
  23117. with the transfer target to alert them to the impending
  23118. transfer, terminates the connection with the target, then
  23119. proceeds with the transfer (as in Blind transfer above)
  23120. \par Attended transfer
  23121. The transferor places the transferee
  23122. on hold, calls the transfer target to alert them,
  23123. places the target on hold, then proceeds with the transfer
  23124. using a Replaces header field in the Refer-to header. This
  23125. will force the transfee to send an Invite to the target,
  23126. with a replaces header that instructs the target to
  23127. hangup the call between the transferor and the target.
  23128. In this case, the Refer/to: uses the AOR address. (The same
  23129. URI that the transferee used to establish the session with
  23130. the transfer target (To: ). The Require: replaces header should
  23131. be in the INVITE to avoid the wrong UA in a forked SIP proxy
  23132. scenario to answer and have no call to replace with.
  23133. The referred-by header is *NOT* required, but if we get it,
  23134. can be copied into the INVITE to the transfer target to
  23135. inform the target about the transferor
  23136. "Any REFER request has to be appropriately authenticated.".
  23137. We can't destroy dialogs, since we want the call to continue.
  23138. */
  23139. static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock)
  23140. {
  23141. char *refer_to = NULL;
  23142. char *refer_to_context = NULL;
  23143. int res = 0;
  23144. struct blind_transfer_cb_data cb_data;
  23145. enum ast_transfer_result transfer_res;
  23146. RAII_VAR(struct ast_channel *, transferer, NULL, ast_channel_cleanup);
  23147. RAII_VAR(struct ast_str *, replaces_str, NULL, ast_free_ptr);
  23148. if (req->debug) {
  23149. ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
  23150. p->callid,
  23151. ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
  23152. }
  23153. if (!p->owner) {
  23154. /* This is a REFER outside of an existing SIP dialog */
  23155. /* We can't handle that, so decline it */
  23156. ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
  23157. transmit_response(p, "603 Declined (No dialog)", req);
  23158. if (!req->ignore) {
  23159. append_history(p, "Xfer", "Refer failed. Outside of dialog.");
  23160. sip_alreadygone(p);
  23161. pvt_set_needdestroy(p, "outside of dialog");
  23162. }
  23163. return 0;
  23164. }
  23165. /* Check if transfer is allowed from this device */
  23166. if (p->allowtransfer == TRANSFER_CLOSED ) {
  23167. /* Transfer not allowed, decline */
  23168. transmit_response(p, "603 Declined (policy)", req);
  23169. append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
  23170. /* Do not destroy SIP session */
  23171. return 0;
  23172. }
  23173. if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
  23174. /* Already have a pending REFER */
  23175. transmit_response(p, "491 Request pending", req);
  23176. append_history(p, "Xfer", "Refer failed. Request pending.");
  23177. return 0;
  23178. }
  23179. /* Allocate memory for call transfer data */
  23180. if (!sip_refer_alloc(p)) {
  23181. transmit_response(p, "500 Internal Server Error", req);
  23182. append_history(p, "Xfer", "Refer failed. Memory allocation error.");
  23183. return -3;
  23184. }
  23185. res = get_refer_info(p, req); /* Extract headers */
  23186. p->refer->status = REFER_SENT;
  23187. if (res != 0) {
  23188. switch (res) {
  23189. case -2: /* Syntax error */
  23190. transmit_response(p, "400 Bad Request (Refer-to missing)", req);
  23191. append_history(p, "Xfer", "Refer failed. Refer-to missing.");
  23192. if (req->debug) {
  23193. ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
  23194. }
  23195. break;
  23196. case -3:
  23197. transmit_response(p, "603 Declined (Non sip: uri)", req);
  23198. append_history(p, "Xfer", "Refer failed. Non SIP uri");
  23199. if (req->debug) {
  23200. ast_debug(1, "SIP transfer to non-SIP uri denied\n");
  23201. }
  23202. break;
  23203. default:
  23204. /* Refer-to extension not found, fake a failed transfer */
  23205. transmit_response(p, "202 Accepted", req);
  23206. append_history(p, "Xfer", "Refer failed. Bad extension.");
  23207. transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
  23208. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  23209. if (req->debug) {
  23210. ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
  23211. }
  23212. break;
  23213. }
  23214. return 0;
  23215. }
  23216. if (ast_strlen_zero(p->context)) {
  23217. ast_string_field_set(p, context, sip_cfg.default_context);
  23218. }
  23219. /* If we do not support SIP domains, all transfers are local */
  23220. if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
  23221. p->refer->localtransfer = 1;
  23222. if (sipdebug) {
  23223. ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
  23224. }
  23225. } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
  23226. /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
  23227. p->refer->localtransfer = 1;
  23228. } else if (sipdebug) {
  23229. ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
  23230. }
  23231. /* Is this a repeat of a current request? Ignore it */
  23232. /* Don't know what else to do right now. */
  23233. if (req->ignore) {
  23234. return 0;
  23235. }
  23236. /* Get the transferer's channel */
  23237. transferer = ast_channel_ref(p->owner);
  23238. if (sipdebug) {
  23239. ast_debug(3, "SIP %s transfer: Transferer channel %s\n",
  23240. p->refer->attendedtransfer ? "attended" : "blind",
  23241. ast_channel_name(transferer));
  23242. }
  23243. ast_set_flag(&p->flags[0], SIP_GOTREFER);
  23244. /* From here on failures will be indicated with NOTIFY requests */
  23245. transmit_response(p, "202 Accepted", req);
  23246. /* Attended transfer: Find all call legs and bridge transferee with target*/
  23247. if (p->refer->attendedtransfer) {
  23248. /* both p and p->owner _MUST_ be locked while calling local_attended_transfer */
  23249. if ((res = local_attended_transfer(p, transferer, seqno, nounlock))) {
  23250. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  23251. return res;
  23252. }
  23253. /* Fall through for remote transfers that we did not find locally */
  23254. if (sipdebug) {
  23255. ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
  23256. }
  23257. /* Fallthrough if we can't find the call leg internally */
  23258. }
  23259. /* Copy data we can not safely access after letting the pvt lock go. */
  23260. refer_to = ast_strdupa(p->refer->refer_to);
  23261. refer_to_context = ast_strdupa(p->refer->refer_to_context);
  23262. ast_party_redirecting_init(&cb_data.redirecting);
  23263. memset(&cb_data.update_redirecting, 0, sizeof(cb_data.update_redirecting));
  23264. change_redirecting_information(p, req, &cb_data.redirecting, &cb_data.update_redirecting, 0);
  23265. cb_data.domain = ast_strdupa(p->refer->refer_to_domain);
  23266. cb_data.referred_by = ast_strdupa(p->refer->referred_by);
  23267. if (!ast_strlen_zero(p->refer->replaces_callid)) {
  23268. replaces_str = ast_str_create(128);
  23269. if (!replaces_str) {
  23270. ast_log(LOG_NOTICE, "Unable to create Replaces string for remote attended transfer. Transfer failed\n");
  23271. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  23272. ast_party_redirecting_free(&cb_data.redirecting);
  23273. return -1;
  23274. }
  23275. ast_str_append(&replaces_str, 0, "%s%s%s%s%s", p->refer->replaces_callid,
  23276. !ast_strlen_zero(p->refer->replaces_callid_totag) ? ";to-tag=" : "",
  23277. S_OR(p->refer->replaces_callid_totag, ""),
  23278. !ast_strlen_zero(p->refer->replaces_callid_fromtag) ? ";from-tag=" : "",
  23279. S_OR(p->refer->replaces_callid_fromtag, ""));
  23280. cb_data.replaces = ast_str_buffer(replaces_str);
  23281. } else {
  23282. cb_data.replaces = NULL;
  23283. }
  23284. if (!*nounlock) {
  23285. ast_channel_unlock(p->owner);
  23286. *nounlock = 1;
  23287. }
  23288. ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23289. sip_pvt_unlock(p);
  23290. transfer_res = ast_bridge_transfer_blind(1, transferer, refer_to, refer_to_context, blind_transfer_cb, &cb_data);
  23291. sip_pvt_lock(p);
  23292. switch (transfer_res) {
  23293. case AST_BRIDGE_TRANSFER_INVALID:
  23294. res = -1;
  23295. p->refer->status = REFER_FAILED;
  23296. transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
  23297. append_history(p, "Xfer", "Refer failed (only bridged calls).");
  23298. ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23299. break;
  23300. case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
  23301. res = -1;
  23302. p->refer->status = REFER_FAILED;
  23303. transmit_notify_with_sipfrag(p, seqno, "403 Forbidden", TRUE);
  23304. append_history(p, "Xfer", "Refer failed (bridge does not permit transfers)");
  23305. ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23306. break;
  23307. case AST_BRIDGE_TRANSFER_FAIL:
  23308. res = -1;
  23309. p->refer->status = REFER_FAILED;
  23310. transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
  23311. append_history(p, "Xfer", "Refer failed (internal error)");
  23312. ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23313. break;
  23314. case AST_BRIDGE_TRANSFER_SUCCESS:
  23315. res = 0;
  23316. p->refer->status = REFER_200OK;
  23317. transmit_notify_with_sipfrag(p, seqno, "200 OK", TRUE);
  23318. append_history(p, "Xfer", "Refer succeeded.");
  23319. break;
  23320. default:
  23321. break;
  23322. }
  23323. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  23324. ast_party_redirecting_free(&cb_data.redirecting);
  23325. return res;
  23326. }
  23327. /*! \brief Handle incoming CANCEL request */
  23328. static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
  23329. {
  23330. check_via(p, req);
  23331. sip_alreadygone(p);
  23332. if (p->owner && ast_channel_state(p->owner) == AST_STATE_UP) {
  23333. /* This call is up, cancel is ignored, we need a bye */
  23334. transmit_response(p, "200 OK", req);
  23335. ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
  23336. return 0;
  23337. }
  23338. /* At this point, we could have cancelled the invite at the same time
  23339. as the other side sends a CANCEL. Our final reply with error code
  23340. might not have been received by the other side before the CANCEL
  23341. was sent, so let's just give up retransmissions and waiting for
  23342. ACK on our error code. The call is hanging up any way. */
  23343. if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
  23344. __sip_pretend_ack(p);
  23345. }
  23346. if (p->invitestate != INV_TERMINATED)
  23347. p->invitestate = INV_CANCELLED;
  23348. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
  23349. update_call_counter(p, DEC_CALL_LIMIT);
  23350. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  23351. if (p->owner) {
  23352. sip_queue_hangup_cause(p, 0);
  23353. } else {
  23354. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  23355. }
  23356. if (ast_str_strlen(p->initreq.data) > 0) {
  23357. struct sip_pkt *pkt, *prev_pkt;
  23358. /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
  23359. * a reliable 487, then we don't want to schedule another one on top of the previous
  23360. * one.
  23361. *
  23362. * As odd as this may sound, we can't rely on the previously-transmitted "reliable"
  23363. * response in this situation. What if we've sent all of our reliable responses
  23364. * already and now all of a sudden, we get this second CANCEL?
  23365. *
  23366. * The only way to do this correctly is to cancel our previously-scheduled reliably-
  23367. * transmitted response and send a new one in its place.
  23368. */
  23369. for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
  23370. if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
  23371. AST_SCHED_DEL(sched, pkt->retransid);
  23372. UNLINK(pkt, p->packets, prev_pkt);
  23373. dialog_unref(pkt->owner, "unref packet->owner from dialog");
  23374. if (pkt->data) {
  23375. ast_free(pkt->data);
  23376. }
  23377. ast_free(pkt);
  23378. break;
  23379. }
  23380. }
  23381. transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
  23382. transmit_response(p, "200 OK", req);
  23383. return 1;
  23384. } else {
  23385. transmit_response(p, "481 Call Leg Does Not Exist", req);
  23386. return 0;
  23387. }
  23388. }
  23389. /*! \brief Handle incoming BYE request */
  23390. static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
  23391. {
  23392. struct ast_channel *c=NULL;
  23393. int res;
  23394. const char *required;
  23395. RAII_VAR(struct ast_channel *, peer_channel, NULL, ast_channel_cleanup);
  23396. char quality_buf[AST_MAX_USER_FIELD], *quality;
  23397. /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
  23398. if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
  23399. transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
  23400. }
  23401. __sip_pretend_ack(p);
  23402. p->invitestate = INV_TERMINATED;
  23403. copy_request(&p->initreq, req);
  23404. if (sipdebug)
  23405. ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  23406. check_via(p, req);
  23407. sip_alreadygone(p);
  23408. if (p->owner) {
  23409. RAII_VAR(struct ast_channel *, owner_relock, NULL, ast_channel_cleanup);
  23410. RAII_VAR(struct ast_channel *, owner_ref, NULL, ast_channel_cleanup);
  23411. /* Grab a reference to p->owner to prevent it from going away */
  23412. owner_ref = ast_channel_ref(p->owner);
  23413. /* Established locking order here is bridge, channel, pvt
  23414. * and the bridge will be locked during ast_channel_bridge_peer */
  23415. ast_channel_unlock(owner_ref);
  23416. sip_pvt_unlock(p);
  23417. peer_channel = ast_channel_bridge_peer(owner_ref);
  23418. owner_relock = sip_pvt_lock_full(p);
  23419. if (!owner_relock) {
  23420. ast_debug(3, "Unable to reacquire owner channel lock, channel is gone\n");
  23421. return 0;
  23422. }
  23423. }
  23424. /* Get RTCP quality before end of call */
  23425. if (p->rtp) {
  23426. if (p->do_history) {
  23427. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  23428. append_history(p, "RTCPaudio", "Quality:%s", quality);
  23429. }
  23430. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
  23431. append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
  23432. }
  23433. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
  23434. append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
  23435. }
  23436. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
  23437. append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
  23438. }
  23439. }
  23440. if (p->owner) {
  23441. RAII_VAR(struct ast_channel *, owner_relock, NULL, ast_channel_cleanup);
  23442. RAII_VAR(struct ast_channel *, owner_ref, NULL, ast_channel_cleanup);
  23443. struct ast_rtp_instance *p_rtp;
  23444. /* Grab a reference to p->owner to prevent it from going away */
  23445. owner_ref = ast_channel_ref(p->owner);
  23446. p_rtp = p->rtp;
  23447. ao2_ref(p_rtp, +1);
  23448. /* Established locking order here is bridge, channel, pvt
  23449. * and the bridge and channel will be locked during
  23450. * ast_rtp_instance_set_stats_vars */
  23451. ast_channel_unlock(owner_ref);
  23452. sip_pvt_unlock(p);
  23453. ast_rtp_instance_set_stats_vars(owner_ref, p_rtp);
  23454. ao2_ref(p_rtp, -1);
  23455. if (peer_channel) {
  23456. ast_channel_lock(peer_channel);
  23457. if (IS_SIP_TECH(ast_channel_tech(peer_channel))) {
  23458. struct sip_pvt *peer_pvt;
  23459. peer_pvt = ast_channel_tech_pvt(peer_channel);
  23460. if (peer_pvt) {
  23461. ao2_ref(peer_pvt, +1);
  23462. sip_pvt_lock(peer_pvt);
  23463. if (peer_pvt->rtp) {
  23464. struct ast_rtp_instance *peer_rtp;
  23465. peer_rtp = peer_pvt->rtp;
  23466. ao2_ref(peer_rtp, +1);
  23467. ast_channel_unlock(peer_channel);
  23468. sip_pvt_unlock(peer_pvt);
  23469. ast_rtp_instance_set_stats_vars(peer_channel, peer_rtp);
  23470. ao2_ref(peer_rtp, -1);
  23471. ast_channel_lock(peer_channel);
  23472. sip_pvt_lock(peer_pvt);
  23473. }
  23474. sip_pvt_unlock(peer_pvt);
  23475. ao2_ref(peer_pvt, -1);
  23476. }
  23477. }
  23478. ast_channel_unlock(peer_channel);
  23479. }
  23480. owner_relock = sip_pvt_lock_full(p);
  23481. if (!owner_relock) {
  23482. ast_debug(3, "Unable to reacquire owner channel lock, channel is gone\n");
  23483. return 0;
  23484. }
  23485. }
  23486. }
  23487. if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  23488. if (p->do_history) {
  23489. append_history(p, "RTCPvideo", "Quality:%s", quality);
  23490. }
  23491. if (p->owner) {
  23492. pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
  23493. }
  23494. }
  23495. if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  23496. if (p->do_history) {
  23497. append_history(p, "RTCPtext", "Quality:%s", quality);
  23498. }
  23499. if (p->owner) {
  23500. pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
  23501. }
  23502. }
  23503. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  23504. if (p->stimer) {
  23505. stop_session_timer(p); /* Stop Session-Timer */
  23506. }
  23507. if (!ast_strlen_zero(sip_get_header(req, "Also"))) {
  23508. ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
  23509. ast_sockaddr_stringify(&p->recv));
  23510. if (ast_strlen_zero(p->context))
  23511. ast_string_field_set(p, context, sip_cfg.default_context);
  23512. res = get_also_info(p, req);
  23513. if (!res) {
  23514. c = p->owner;
  23515. if (c) {
  23516. if (peer_channel) {
  23517. RAII_VAR(struct ast_channel *, owner_relock, NULL, ast_channel_cleanup);
  23518. char *local_context = ast_strdupa(p->context);
  23519. char *local_refer_to = ast_strdupa(p->refer->refer_to);
  23520. /* Grab a reference to p->owner to prevent it from going away */
  23521. ast_channel_ref(c);
  23522. /* Don't actually hangup here... */
  23523. ast_queue_unhold(c);
  23524. ast_channel_unlock(c); /* async_goto can do a masquerade, no locks can be held during a masq */
  23525. sip_pvt_unlock(p);
  23526. ast_async_goto(peer_channel, local_context, local_refer_to, 1);
  23527. owner_relock = sip_pvt_lock_full(p);
  23528. ast_channel_cleanup(c);
  23529. if (!owner_relock) {
  23530. ast_debug(3, "Unable to reacquire owner channel lock, channel is gone\n");
  23531. return 0;
  23532. }
  23533. } else {
  23534. ast_queue_hangup(p->owner);
  23535. }
  23536. }
  23537. } else {
  23538. ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
  23539. if (p->owner)
  23540. ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
  23541. }
  23542. } else if (p->owner) {
  23543. sip_queue_hangup_cause(p, 0);
  23544. sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
  23545. ast_debug(3, "Received bye, issuing owner hangup\n");
  23546. } else {
  23547. sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
  23548. ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
  23549. }
  23550. ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  23551. /* Find out what they require */
  23552. required = sip_get_header(req, "Require");
  23553. if (!ast_strlen_zero(required)) {
  23554. char unsupported[256] = { 0, };
  23555. parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
  23556. /* If there are any options required that we do not support,
  23557. * then send a 420 with only those unsupported options listed */
  23558. if (!ast_strlen_zero(unsupported)) {
  23559. transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
  23560. ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
  23561. } else {
  23562. transmit_response(p, "200 OK", req);
  23563. }
  23564. } else {
  23565. transmit_response(p, "200 OK", req);
  23566. }
  23567. /* Destroy any pending invites so we won't try to do another
  23568. * scheduled reINVITE. */
  23569. AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "decrement refcount from sip_destroy because waitid won't be scheduled"));
  23570. return 1;
  23571. }
  23572. /*! \brief Handle incoming MESSAGE request */
  23573. static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
  23574. {
  23575. if (!req->ignore) {
  23576. if (req->debug)
  23577. ast_verbose("Receiving message!\n");
  23578. receive_message(p, req, addr, e);
  23579. } else
  23580. transmit_response(p, "202 Accepted", req);
  23581. return 1;
  23582. }
  23583. static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from);
  23584. static const struct ast_msg_tech sip_msg_tech = {
  23585. .name = "sip",
  23586. .msg_send = sip_msg_send,
  23587. };
  23588. /*!
  23589. * \internal
  23590. * \brief Check if the given header name is blocked.
  23591. *
  23592. * \details Determine if the given header name from the user is
  23593. * blocked for outgoing MESSAGE packets.
  23594. *
  23595. * \param header_name Name of header to see if it is blocked.
  23596. *
  23597. * \retval TRUE if the given header is blocked.
  23598. */
  23599. static int block_msg_header(const char *header_name)
  23600. {
  23601. int idx;
  23602. /*
  23603. * Don't block Content-Type or Max-Forwards headers because the
  23604. * user can override them.
  23605. */
  23606. static const char *hdr[] = {
  23607. "To",
  23608. "From",
  23609. "Via",
  23610. "Route",
  23611. "Contact",
  23612. "Call-ID",
  23613. "CSeq",
  23614. "Allow",
  23615. "Content-Length",
  23616. "Request-URI",
  23617. };
  23618. for (idx = 0; idx < ARRAY_LEN(hdr); ++idx) {
  23619. if (!strcasecmp(header_name, hdr[idx])) {
  23620. /* Block addition of this header. */
  23621. return 1;
  23622. }
  23623. }
  23624. return 0;
  23625. }
  23626. static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from)
  23627. {
  23628. struct sip_pvt *pvt;
  23629. int res;
  23630. char *to_uri;
  23631. char *to_host;
  23632. char *to_user;
  23633. const char *var;
  23634. const char *val;
  23635. struct ast_msg_var_iterator *iter;
  23636. struct sip_peer *peer_ptr;
  23637. if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_MESSAGE, NULL, 0))) {
  23638. return -1;
  23639. }
  23640. for (iter = ast_msg_var_iterator_init(msg);
  23641. ast_msg_var_iterator_next(msg, iter, &var, &val);
  23642. ast_msg_var_unref_current(iter)) {
  23643. if (!strcasecmp(var, "Request-URI")) {
  23644. ast_string_field_set(pvt, fullcontact, val);
  23645. break;
  23646. }
  23647. }
  23648. ast_msg_var_iterator_destroy(iter);
  23649. to_uri = ast_strdupa(to);
  23650. to_uri = get_in_brackets(to_uri);
  23651. parse_uri(to_uri, "sip:,sips:", &to_user, NULL, &to_host, NULL);
  23652. if (ast_strlen_zero(to_host)) {
  23653. ast_log(LOG_WARNING, "MESSAGE(to) is invalid for SIP - '%s'\n", to);
  23654. dialog_unlink_all(pvt);
  23655. dialog_unref(pvt, "MESSAGE(to) is invalid for SIP");
  23656. return -1;
  23657. }
  23658. if (!ast_strlen_zero(from)) {
  23659. if ((peer_ptr = sip_find_peer(from, NULL, 0, 1, 0, 0))) {
  23660. ast_string_field_set(pvt, fromname, S_OR(peer_ptr->cid_name, peer_ptr->name));
  23661. ast_string_field_set(pvt, fromuser, S_OR(peer_ptr->cid_num, peer_ptr->name));
  23662. sip_unref_peer(peer_ptr, "sip_unref_peer, from sip_msg_send, sip_find_peer");
  23663. } else if (strchr(from, '<')) { /* from is callerid-style */
  23664. char *sender;
  23665. char *name = NULL, *location = NULL, *user = NULL, *domain = NULL;
  23666. sender = ast_strdupa(from);
  23667. ast_callerid_parse(sender, &name, &location);
  23668. if (ast_strlen_zero(location)) {
  23669. /* This can occur if either
  23670. * 1) A name-addr style From header does not close the angle brackets
  23671. * properly.
  23672. * 2) The From header is not in name-addr style and the content of the
  23673. * From contains characters other than 0-9, *, #, or +.
  23674. *
  23675. * In both cases, ast_callerid_parse() should have parsed the From header
  23676. * as a name rather than a number. So we just need to set the location
  23677. * to what was parsed as a name, and set the name NULL since there was
  23678. * no name present.
  23679. */
  23680. location = name;
  23681. name = NULL;
  23682. }
  23683. ast_string_field_set(pvt, fromname, name);
  23684. if (strchr(location, ':')) { /* Must be a URI */
  23685. parse_uri(location, "sip:,sips:", &user, NULL, &domain, NULL);
  23686. SIP_PEDANTIC_DECODE(user);
  23687. SIP_PEDANTIC_DECODE(domain);
  23688. extract_host_from_hostport(&domain);
  23689. ast_string_field_set(pvt, fromuser, user);
  23690. ast_string_field_set(pvt, fromdomain, domain);
  23691. } else { /* Treat it as an exten/user */
  23692. ast_string_field_set(pvt, fromuser, location);
  23693. }
  23694. } else { /* assume we just have the name, use defaults for the rest */
  23695. ast_string_field_set(pvt, fromname, from);
  23696. }
  23697. }
  23698. sip_pvt_lock(pvt);
  23699. /* Look up the host to contact */
  23700. if (create_addr(pvt, to_host, NULL, TRUE)) {
  23701. sip_pvt_unlock(pvt);
  23702. dialog_unlink_all(pvt);
  23703. dialog_unref(pvt, "create_addr failed sending a MESSAGE");
  23704. return -1;
  23705. }
  23706. if (!ast_strlen_zero(to_user)) {
  23707. ast_string_field_set(pvt, username, to_user);
  23708. }
  23709. ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
  23710. build_via(pvt);
  23711. ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
  23712. /* XXX Does pvt->expiry need to be set? */
  23713. /* Save additional MESSAGE headers in case of authentication request. */
  23714. for (iter = ast_msg_var_iterator_init(msg);
  23715. ast_msg_var_iterator_next(msg, iter, &var, &val);
  23716. ast_msg_var_unref_current(iter)) {
  23717. if (!strcasecmp(var, "Max-Forwards")) {
  23718. /* Decrement Max-Forwards for SIP loop prevention. */
  23719. if (sscanf(val, "%30d", &pvt->maxforwards) != 1 || pvt->maxforwards < 1) {
  23720. ast_msg_var_iterator_destroy(iter);
  23721. sip_pvt_unlock(pvt);
  23722. dialog_unlink_all(pvt);
  23723. dialog_unref(pvt, "MESSAGE(Max-Forwards) reached zero.");
  23724. ast_log(LOG_NOTICE,
  23725. "MESSAGE(Max-Forwards) reached zero. MESSAGE not sent.\n");
  23726. return -1;
  23727. }
  23728. --pvt->maxforwards;
  23729. continue;
  23730. }
  23731. if (block_msg_header(var)) {
  23732. /* Block addition of this header. */
  23733. continue;
  23734. }
  23735. add_msg_header(pvt, var, val);
  23736. }
  23737. ast_msg_var_iterator_destroy(iter);
  23738. ast_string_field_set(pvt, msg_body, ast_msg_get_body(msg));
  23739. res = transmit_message(pvt, 1, 0);
  23740. sip_pvt_unlock(pvt);
  23741. sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
  23742. dialog_unref(pvt, "sent a MESSAGE");
  23743. return res;
  23744. }
  23745. static enum sip_publish_type determine_sip_publish_type(struct sip_request *req, const char * const event, const char * const etag, const char * const expires, int *expires_int)
  23746. {
  23747. int etag_present = !ast_strlen_zero(etag);
  23748. int body_present = req->lines > 0;
  23749. ast_assert(expires_int != NULL);
  23750. if (ast_strlen_zero(expires)) {
  23751. /* Section 6, item 4, second bullet point of RFC 3903 says to
  23752. * use a locally-configured default expiration if none is provided
  23753. * in the request
  23754. */
  23755. *expires_int = DEFAULT_PUBLISH_EXPIRES;
  23756. } else if (sscanf(expires, "%30d", expires_int) != 1) {
  23757. return SIP_PUBLISH_UNKNOWN;
  23758. }
  23759. if (*expires_int == 0) {
  23760. return SIP_PUBLISH_REMOVE;
  23761. } else if (!etag_present && body_present) {
  23762. return SIP_PUBLISH_INITIAL;
  23763. } else if (etag_present && !body_present) {
  23764. return SIP_PUBLISH_REFRESH;
  23765. } else if (etag_present && body_present) {
  23766. return SIP_PUBLISH_MODIFY;
  23767. }
  23768. return SIP_PUBLISH_UNKNOWN;
  23769. }
  23770. #ifdef HAVE_LIBXML2
  23771. static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
  23772. {
  23773. const char *id;
  23774. int status_found = FALSE;
  23775. struct ast_xml_node *tuple_children;
  23776. struct ast_xml_node *tuple_children_iterator;
  23777. /* Tuples have to have an id attribute or they're invalid */
  23778. if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
  23779. ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
  23780. return FALSE;
  23781. }
  23782. /* We don't care what it actually is, just that it's there */
  23783. ast_xml_free_attr(id);
  23784. /* This is a tuple. It must have a status element */
  23785. if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
  23786. /* The tuple has no children. It sucks */
  23787. ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
  23788. return FALSE;
  23789. }
  23790. for (tuple_children_iterator = tuple_children; tuple_children_iterator;
  23791. tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
  23792. /* Similar to the wording used regarding tuples, the status element should appear
  23793. * first. However, we will once again relax things and accept the status at any
  23794. * position. We will enforce that only a single status element can be present.
  23795. */
  23796. if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
  23797. /* Not the status, we don't care */
  23798. continue;
  23799. }
  23800. if (status_found == TRUE) {
  23801. /* THERE CAN BE ONLY ONE!!! */
  23802. ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
  23803. return FALSE;
  23804. }
  23805. status_found = TRUE;
  23806. }
  23807. return status_found;
  23808. }
  23809. static int pidf_validate_presence(struct ast_xml_doc *doc)
  23810. {
  23811. struct ast_xml_node *presence_node = ast_xml_get_root(doc);
  23812. struct ast_xml_node *child_nodes;
  23813. struct ast_xml_node *node_iterator;
  23814. struct ast_xml_ns *ns;
  23815. const char *entity;
  23816. const char *namespace;
  23817. const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
  23818. if (!presence_node) {
  23819. ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
  23820. return FALSE;
  23821. }
  23822. /* Okay, we managed to open the document! YAY! Now, let's start making sure it's all PIDF-ified
  23823. * correctly.
  23824. */
  23825. if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
  23826. ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
  23827. return FALSE;
  23828. }
  23829. /* The presence element must have an entity attribute and an xmlns attribute. Furthermore
  23830. * the xmlns attribute must be "urn:ietf:params:xml:ns:pidf"
  23831. */
  23832. if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
  23833. ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
  23834. return FALSE;
  23835. }
  23836. /* We're not interested in what the entity is, just that it exists */
  23837. ast_xml_free_attr(entity);
  23838. if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
  23839. ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
  23840. return FALSE;
  23841. }
  23842. namespace = ast_xml_get_ns_href(ns);
  23843. if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
  23844. ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
  23845. return FALSE;
  23846. }
  23847. if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
  23848. ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
  23849. return FALSE;
  23850. }
  23851. /* Check for tuple elements. RFC 3863 says that PIDF documents can have any number of
  23852. * tuples, including 0. The big thing here is that if there are tuple elements present,
  23853. * they have to have a single status element within.
  23854. *
  23855. * The RFC is worded such that tuples should appear as the first elements as children of
  23856. * the presence element. However, we'll be accepting of documents which may place other elements
  23857. * before the tuple(s).
  23858. */
  23859. for (node_iterator = child_nodes; node_iterator;
  23860. node_iterator = ast_xml_node_get_next(node_iterator)) {
  23861. if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
  23862. /* Not a tuple. We don't give a rat's hind quarters */
  23863. continue;
  23864. }
  23865. if (pidf_validate_tuple(node_iterator) == FALSE) {
  23866. ast_log(LOG_WARNING, "Unable to validate tuple\n");
  23867. return FALSE;
  23868. }
  23869. }
  23870. return TRUE;
  23871. }
  23872. /*!
  23873. * \brief Makes sure that body is properly formatted PIDF
  23874. *
  23875. * Specifically, we check that the document has a "presence" element
  23876. * at the root and that within that, there is at least one "tuple" element
  23877. * that contains a "status" element.
  23878. *
  23879. * XXX This function currently assumes a default namespace is used. Of course
  23880. * if you're not using a default namespace, you're probably a stupid jerk anyway.
  23881. *
  23882. * \param req The SIP request to check
  23883. * \param[out] pidf_doc The validated PIDF doc.
  23884. * \retval FALSE The XML was malformed or the basic PIDF structure was marred
  23885. * \retval TRUE The PIDF document is of a valid format
  23886. */
  23887. static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
  23888. {
  23889. struct ast_xml_doc *doc;
  23890. const char *content_type = sip_get_header(req, "Content-Type");
  23891. char *pidf_body;
  23892. int res;
  23893. if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
  23894. ast_log(LOG_WARNING, "Content type is not PIDF\n");
  23895. return FALSE;
  23896. }
  23897. if (!(pidf_body = get_content(req))) {
  23898. ast_log(LOG_WARNING, "Unable to get PIDF body\n");
  23899. return FALSE;
  23900. }
  23901. if (!(doc = ast_xml_read_memory(pidf_body, strlen(pidf_body)))) {
  23902. ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
  23903. return FALSE;
  23904. }
  23905. res = pidf_validate_presence(doc);
  23906. if (res == TRUE) {
  23907. *pidf_doc = doc;
  23908. } else {
  23909. ast_xml_close(doc);
  23910. }
  23911. return res;
  23912. }
  23913. static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry)
  23914. {
  23915. const char *uri = REQ_OFFSET_TO_STR(req, rlpart2);
  23916. struct ast_cc_agent *agent;
  23917. struct sip_cc_agent_pvt *agent_pvt;
  23918. struct ast_xml_doc *pidf_doc = NULL;
  23919. const char *basic_status = NULL;
  23920. struct ast_xml_node *presence_node;
  23921. struct ast_xml_node *presence_children;
  23922. struct ast_xml_node *tuple_node;
  23923. struct ast_xml_node *tuple_children;
  23924. struct ast_xml_node *status_node;
  23925. struct ast_xml_node *status_children;
  23926. struct ast_xml_node *basic_node;
  23927. int res = 0;
  23928. if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
  23929. ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
  23930. transmit_response(pvt, "412 Conditional Request Failed", req);
  23931. return -1;
  23932. }
  23933. agent_pvt = agent->private_data;
  23934. if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
  23935. res = -1;
  23936. goto cc_publish_cleanup;
  23937. }
  23938. /* It's important to note that the PIDF validation routine has no knowledge
  23939. * of what we specifically want in this instance. A valid PIDF document could
  23940. * have no tuples, or it could have tuples whose status element has no basic
  23941. * element contained within. While not violating the PIDF spec, these are
  23942. * insufficient for our needs in this situation
  23943. */
  23944. presence_node = ast_xml_get_root(pidf_doc);
  23945. if (!(presence_children = ast_xml_node_get_children(presence_node))) {
  23946. ast_log(LOG_WARNING, "No tuples within presence element.\n");
  23947. res = -1;
  23948. goto cc_publish_cleanup;
  23949. }
  23950. if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
  23951. ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
  23952. res = -1;
  23953. goto cc_publish_cleanup;
  23954. }
  23955. /* We already made sure that the tuple has a status node when we validated the PIDF
  23956. * document earlier. So there's no need to enclose this operation in an if statement.
  23957. */
  23958. tuple_children = ast_xml_node_get_children(tuple_node);
  23959. /* coverity[null_returns: FALSE] */
  23960. status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
  23961. if (!(status_children = ast_xml_node_get_children(status_node))) {
  23962. ast_log(LOG_WARNING, "No basic elements within status element.\n");
  23963. res = -1;
  23964. goto cc_publish_cleanup;
  23965. }
  23966. if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
  23967. ast_log(LOG_WARNING, "Couldn't find basic node?\n");
  23968. res = -1;
  23969. goto cc_publish_cleanup;
  23970. }
  23971. basic_status = ast_xml_get_text(basic_node);
  23972. if (ast_strlen_zero(basic_status)) {
  23973. ast_log(LOG_NOTICE, "NOthing in basic node?\n");
  23974. res = -1;
  23975. goto cc_publish_cleanup;
  23976. }
  23977. if (!strcmp(basic_status, "open")) {
  23978. agent_pvt->is_available = TRUE;
  23979. ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
  23980. agent->device_name);
  23981. } else if (!strcmp(basic_status, "closed")) {
  23982. agent_pvt->is_available = FALSE;
  23983. ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
  23984. agent->device_name);
  23985. } else {
  23986. ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
  23987. }
  23988. cc_publish_cleanup:
  23989. if (basic_status) {
  23990. ast_xml_free_text(basic_status);
  23991. }
  23992. if (pidf_doc) {
  23993. ast_xml_close(pidf_doc);
  23994. }
  23995. ao2_ref(agent, -1);
  23996. if (res) {
  23997. transmit_response(pvt, "400 Bad Request", req);
  23998. }
  23999. return res;
  24000. }
  24001. #endif /* HAVE_LIBXML2 */
  24002. static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
  24003. {
  24004. struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
  24005. int res = 0;
  24006. if (!esc_entry) {
  24007. transmit_response(p, "503 Internal Server Failure", req);
  24008. return -1;
  24009. }
  24010. if (esc->callbacks->initial_handler) {
  24011. res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
  24012. }
  24013. if (!res) {
  24014. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
  24015. }
  24016. ao2_ref(esc_entry, -1);
  24017. return res;
  24018. }
  24019. static int handle_sip_publish_refresh(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag, const int expires)
  24020. {
  24021. struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
  24022. int expires_ms = expires * 1000;
  24023. int res = 0;
  24024. if (!esc_entry) {
  24025. transmit_response(p, "412 Conditional Request Failed", req);
  24026. return -1;
  24027. }
  24028. AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
  24029. ao2_ref(_data, -1),
  24030. ao2_ref(esc_entry, -1),
  24031. ao2_ref(esc_entry, +1));
  24032. if (esc->callbacks->refresh_handler) {
  24033. res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
  24034. }
  24035. if (!res) {
  24036. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
  24037. }
  24038. ao2_ref(esc_entry, -1);
  24039. return res;
  24040. }
  24041. static int handle_sip_publish_modify(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag, const int expires)
  24042. {
  24043. struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
  24044. int expires_ms = expires * 1000;
  24045. int res = 0;
  24046. if (!esc_entry) {
  24047. transmit_response(p, "412 Conditional Request Failed", req);
  24048. return -1;
  24049. }
  24050. AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
  24051. ao2_ref(_data, -1),
  24052. ao2_ref(esc_entry, -1),
  24053. ao2_ref(esc_entry, +1));
  24054. if (esc->callbacks->modify_handler) {
  24055. res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
  24056. }
  24057. if (!res) {
  24058. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
  24059. }
  24060. ao2_ref(esc_entry, -1);
  24061. return res;
  24062. }
  24063. static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
  24064. {
  24065. struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
  24066. int res = 0;
  24067. if (!esc_entry) {
  24068. transmit_response(p, "412 Conditional Request Failed", req);
  24069. return -1;
  24070. }
  24071. AST_SCHED_DEL(sched, esc_entry->sched_id);
  24072. /* Scheduler's ref of the esc_entry */
  24073. ao2_ref(esc_entry, -1);
  24074. if (esc->callbacks->remove_handler) {
  24075. res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
  24076. }
  24077. if (!res) {
  24078. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
  24079. }
  24080. /* Ref from finding the esc_entry earlier in function */
  24081. ao2_unlink(esc->compositor, esc_entry);
  24082. ao2_ref(esc_entry, -1);
  24083. return res;
  24084. }
  24085. static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
  24086. {
  24087. const char *etag = sip_get_header(req, "SIP-If-Match");
  24088. const char *event = sip_get_header(req, "Event");
  24089. struct event_state_compositor *esc;
  24090. enum sip_publish_type publish_type;
  24091. const char *expires_str = sip_get_header(req, "Expires");
  24092. int expires_int;
  24093. int auth_result;
  24094. int handler_result = -1;
  24095. if (ast_strlen_zero(event)) {
  24096. transmit_response(p, "489 Bad Event", req);
  24097. pvt_set_needdestroy(p, "missing Event: header");
  24098. return -1;
  24099. }
  24100. if (!(esc = get_esc(event))) {
  24101. transmit_response(p, "489 Bad Event", req);
  24102. pvt_set_needdestroy(p, "unknown event package in publish");
  24103. return -1;
  24104. }
  24105. auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_UNRELIABLE, addr);
  24106. if (auth_result == AUTH_CHALLENGE_SENT) {
  24107. p->lastinvite = seqno;
  24108. return 0;
  24109. } else if (auth_result < 0) {
  24110. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
  24111. transmit_response(p, "403 Forbidden", req);
  24112. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  24113. ast_string_field_set(p, theirtag, NULL);
  24114. return 0;
  24115. } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
  24116. /* We need to stop retransmitting the 401 */
  24117. __sip_ack(p, p->lastinvite, 1, 0);
  24118. }
  24119. publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
  24120. if (expires_int > max_expiry) {
  24121. expires_int = max_expiry;
  24122. } else if (expires_int < min_expiry && expires_int > 0) {
  24123. transmit_response_with_minexpires(p, "423 Interval too small", req, min_expiry);
  24124. pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
  24125. return 0;
  24126. }
  24127. p->expiry = expires_int;
  24128. /* It is the responsibility of these handlers to formulate any response
  24129. * sent for a PUBLISH
  24130. */
  24131. switch (publish_type) {
  24132. case SIP_PUBLISH_UNKNOWN:
  24133. transmit_response(p, "400 Bad Request", req);
  24134. break;
  24135. case SIP_PUBLISH_INITIAL:
  24136. handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
  24137. break;
  24138. case SIP_PUBLISH_REFRESH:
  24139. handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
  24140. break;
  24141. case SIP_PUBLISH_MODIFY:
  24142. handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
  24143. break;
  24144. case SIP_PUBLISH_REMOVE:
  24145. handler_result = handle_sip_publish_remove(p, req, esc, etag);
  24146. break;
  24147. default:
  24148. transmit_response(p, "400 Impossible Condition", req);
  24149. break;
  24150. }
  24151. if (!handler_result && p->expiry > 0) {
  24152. sip_scheddestroy(p, (p->expiry + 10) * 1000);
  24153. } else {
  24154. pvt_set_needdestroy(p, "forcing expiration");
  24155. }
  24156. return handler_result;
  24157. }
  24158. /*!
  24159. * \internal
  24160. * \brief Subscribe to MWI events for the specified peer
  24161. *
  24162. * \note The peer cannot be locked during this method. sip_send_mwi_peer will
  24163. * attempt to lock the peer after the event subscription lock is held; if the peer is locked during
  24164. * this method then we will attempt to lock the event subscription lock but after the peer, creating
  24165. * a locking inversion.
  24166. */
  24167. static void add_peer_mwi_subs(struct sip_peer *peer)
  24168. {
  24169. struct sip_mailbox *mailbox;
  24170. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  24171. struct stasis_topic *mailbox_specific_topic;
  24172. mailbox->event_sub = stasis_unsubscribe(mailbox->event_sub);
  24173. mailbox_specific_topic = ast_mwi_topic(mailbox->id);
  24174. if (mailbox_specific_topic) {
  24175. char *peer_name = ast_strdup(peer->name);
  24176. if (!peer_name) {
  24177. return;
  24178. }
  24179. mailbox->event_sub = stasis_subscribe_pool(mailbox_specific_topic, mwi_event_cb, peer_name);
  24180. }
  24181. }
  24182. }
  24183. static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
  24184. {
  24185. const char *uri = REQ_OFFSET_TO_STR(req, rlpart2);
  24186. char *param_separator;
  24187. struct ast_cc_agent *agent;
  24188. struct sip_cc_agent_pvt *agent_pvt;
  24189. const char *expires_str = sip_get_header(req, "Expires");
  24190. int expires = -1; /* Just need it to be non-zero */
  24191. if (!ast_strlen_zero(expires_str)) {
  24192. sscanf(expires_str, "%30d", &expires);
  24193. }
  24194. if ((param_separator = strchr(uri, ';'))) {
  24195. *param_separator = '\0';
  24196. }
  24197. p->subscribed = CALL_COMPLETION;
  24198. if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
  24199. if (!expires) {
  24200. /* Typically, if a 0 Expires reaches us and we can't find
  24201. * the corresponding agent, it means that the CC transaction
  24202. * has completed and so the calling side is just trying to
  24203. * clean up its subscription. We'll just respond with a
  24204. * 200 OK and be done with it
  24205. */
  24206. transmit_response(p, "200 OK", req);
  24207. return 0;
  24208. }
  24209. ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
  24210. transmit_response(p, "404 Not Found", req);
  24211. return -1;
  24212. }
  24213. agent_pvt = agent->private_data;
  24214. if (!expires) {
  24215. /* We got sent a SUBSCRIBE and found an agent. This means that CC
  24216. * is being canceled.
  24217. */
  24218. ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
  24219. transmit_response(p, "200 OK", req);
  24220. ao2_ref(agent, -1);
  24221. return 0;
  24222. }
  24223. agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
  24224. ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
  24225. agent->device_name);
  24226. /* We don't send a response here. That is done in the agent's ack callback or in the
  24227. * agent destructor, should a failure occur before we have responded
  24228. */
  24229. ao2_ref(agent, -1);
  24230. return 0;
  24231. }
  24232. /*! \brief Handle incoming SUBSCRIBE request */
  24233. static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
  24234. {
  24235. int res = 0;
  24236. struct sip_peer *authpeer = NULL;
  24237. char *event = ast_strdupa(sip_get_header(req, "Event")); /* Get Event package name */
  24238. int resubscribe = (p->subscribed != NONE) && !req->ignore;
  24239. char *options;
  24240. if (p->initreq.headers) {
  24241. /* We already have a dialog */
  24242. if (p->initreq.method != SIP_SUBSCRIBE) {
  24243. /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
  24244. /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
  24245. transmit_response(p, "403 Forbidden (within dialog)", req);
  24246. /* Do not destroy session, since we will break the call if we do */
  24247. ast_debug(1, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
  24248. return 0;
  24249. } else if (req->debug) {
  24250. if (resubscribe)
  24251. ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
  24252. else
  24253. ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
  24254. }
  24255. }
  24256. /* Check if we have a global disallow setting on subscriptions.
  24257. if so, we don't have to check peer settings after auth, which saves a lot of processing
  24258. */
  24259. if (!sip_cfg.allowsubscribe) {
  24260. transmit_response(p, "403 Forbidden (policy)", req);
  24261. pvt_set_needdestroy(p, "forbidden");
  24262. return 0;
  24263. }
  24264. if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
  24265. const char *to = sip_get_header(req, "To");
  24266. char totag[128];
  24267. set_pvt_allowed_methods(p, req);
  24268. /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
  24269. if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
  24270. if (req->debug)
  24271. ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
  24272. transmit_response(p, "481 Subscription does not exist", req);
  24273. pvt_set_needdestroy(p, "subscription does not exist");
  24274. return 0;
  24275. }
  24276. /* Use this as the basis */
  24277. if (req->debug)
  24278. ast_verbose("Creating new subscription\n");
  24279. copy_request(&p->initreq, req);
  24280. if (sipdebug)
  24281. ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  24282. check_via(p, req);
  24283. build_route(p, req, 0, 0);
  24284. } else if (req->debug && req->ignore)
  24285. ast_verbose("Ignoring this SUBSCRIBE request\n");
  24286. /* Find parameters to Event: header value and remove them for now */
  24287. if (ast_strlen_zero(event)) {
  24288. transmit_response(p, "489 Bad Event", req);
  24289. ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
  24290. pvt_set_needdestroy(p, "unknown event package in subscribe");
  24291. return 0;
  24292. }
  24293. if ((options = strchr(event, ';')) != NULL) {
  24294. *options++ = '\0';
  24295. }
  24296. /* Handle authentication if we're new and not a retransmission. We can't just
  24297. * use if !req->ignore, because then we'll end up sending
  24298. * a 200 OK if someone retransmits without sending auth */
  24299. if (p->subscribed == NONE || resubscribe) {
  24300. res = check_user_full(p, req, SIP_SUBSCRIBE, e, XMIT_UNRELIABLE, addr, &authpeer);
  24301. /* if an authentication response was sent, we are done here */
  24302. if (res == AUTH_CHALLENGE_SENT) /* authpeer = NULL here */
  24303. return 0;
  24304. if (res != AUTH_SUCCESSFUL) {
  24305. ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", sip_get_header(req, "From"));
  24306. transmit_response(p, "403 Forbidden", req);
  24307. pvt_set_needdestroy(p, "authentication failed");
  24308. return 0;
  24309. }
  24310. }
  24311. /* At this point, we hold a reference to authpeer (if not NULL). It
  24312. * must be released when done.
  24313. */
  24314. /* Check if this device is allowed to subscribe at all */
  24315. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
  24316. transmit_response(p, "403 Forbidden (policy)", req);
  24317. pvt_set_needdestroy(p, "subscription not allowed");
  24318. if (authpeer) {
  24319. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 1)");
  24320. }
  24321. return 0;
  24322. }
  24323. /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
  24324. parse_ok_contact(p, req);
  24325. build_contact(p, req, 1);
  24326. /* Initialize tag for new subscriptions */
  24327. if (ast_strlen_zero(p->tag)) {
  24328. make_our_tag(p);
  24329. }
  24330. if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
  24331. int gotdest;
  24332. const char *accept;
  24333. int start = 0;
  24334. enum subscriptiontype subscribed = NONE;
  24335. const char *unknown_accept = NULL;
  24336. /* Get destination right away */
  24337. gotdest = get_destination(p, NULL, NULL);
  24338. if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
  24339. if (gotdest == SIP_GET_DEST_INVALID_URI) {
  24340. transmit_response(p, "416 Unsupported URI scheme", req);
  24341. } else {
  24342. transmit_response(p, "404 Not Found", req);
  24343. }
  24344. pvt_set_needdestroy(p, "subscription target not found");
  24345. if (authpeer) {
  24346. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
  24347. }
  24348. return 0;
  24349. }
  24350. /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
  24351. accept = __get_header(req, "Accept", &start);
  24352. while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
  24353. if (strstr(accept, "application/pidf+xml")) {
  24354. if (strstr(p->useragent, "Polycom")) {
  24355. subscribed = XPIDF_XML; /* Older versions of Polycom firmware will claim pidf+xml, but really they only support xpidf+xml */
  24356. } else {
  24357. subscribed = PIDF_XML; /* RFC 3863 format */
  24358. }
  24359. } else if (strstr(accept, "application/dialog-info+xml")) {
  24360. subscribed = DIALOG_INFO_XML;
  24361. /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
  24362. } else if (strstr(accept, "application/cpim-pidf+xml")) {
  24363. subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
  24364. } else if (strstr(accept, "application/xpidf+xml")) {
  24365. subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
  24366. } else {
  24367. unknown_accept = accept;
  24368. }
  24369. /* check to see if there is another Accept header present */
  24370. accept = __get_header(req, "Accept", &start);
  24371. }
  24372. if (!start) {
  24373. if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
  24374. transmit_response(p, "489 Bad Event", req);
  24375. ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
  24376. "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
  24377. "'%s', subscribeuri: '%s'\n",
  24378. p->stateid,
  24379. p->laststate,
  24380. p->dialogver,
  24381. p->subscribecontext,
  24382. p->subscribeuri);
  24383. pvt_set_needdestroy(p, "no Accept header");
  24384. if (authpeer) {
  24385. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
  24386. }
  24387. return 0;
  24388. }
  24389. /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
  24390. so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
  24391. } else if (subscribed == NONE) {
  24392. /* Can't find a format for events that we know about */
  24393. char buf[200];
  24394. if (!ast_strlen_zero(unknown_accept)) {
  24395. snprintf(buf, sizeof(buf), "489 Bad Event (format %s)", unknown_accept);
  24396. } else {
  24397. snprintf(buf, sizeof(buf), "489 Bad Event");
  24398. }
  24399. transmit_response(p, buf, req);
  24400. ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
  24401. "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
  24402. "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
  24403. unknown_accept,
  24404. (int)p->subscribed,
  24405. p->stateid,
  24406. p->laststate,
  24407. p->dialogver,
  24408. p->subscribecontext,
  24409. p->subscribeuri);
  24410. pvt_set_needdestroy(p, "unrecognized format");
  24411. if (authpeer) {
  24412. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
  24413. }
  24414. return 0;
  24415. } else {
  24416. p->subscribed = subscribed;
  24417. }
  24418. } else if (!strcmp(event, "message-summary")) {
  24419. int start = 0;
  24420. int found_supported = 0;
  24421. const char *accept;
  24422. accept = __get_header(req, "Accept", &start);
  24423. while (!found_supported && !ast_strlen_zero(accept)) {
  24424. found_supported = strcmp(accept, "application/simple-message-summary") ? 0 : 1;
  24425. if (!found_supported) {
  24426. ast_debug(3, "Received SIP mailbox subscription for unknown format: %s\n", accept);
  24427. }
  24428. accept = __get_header(req, "Accept", &start);
  24429. }
  24430. /* If !start, there is no Accept header at all */
  24431. if (start && !found_supported) {
  24432. /* Format requested that we do not support */
  24433. transmit_response(p, "406 Not Acceptable", req);
  24434. ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", accept);
  24435. pvt_set_needdestroy(p, "unknown format");
  24436. if (authpeer) {
  24437. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 3)");
  24438. }
  24439. return 0;
  24440. }
  24441. /* Looks like they actually want a mailbox status
  24442. This version of Asterisk supports mailbox subscriptions
  24443. The subscribed URI needs to exist in the dial plan
  24444. In most devices, this is configurable to the voicemailmain extension you use
  24445. */
  24446. if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
  24447. if (!authpeer) {
  24448. transmit_response(p, "404 Not found", req);
  24449. } else {
  24450. transmit_response(p, "404 Not found (no mailbox)", req);
  24451. ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
  24452. }
  24453. pvt_set_needdestroy(p, "received 404 response");
  24454. if (authpeer) {
  24455. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 3)");
  24456. }
  24457. return 0;
  24458. }
  24459. p->subscribed = MWI_NOTIFICATION;
  24460. if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
  24461. ao2_unlock(p);
  24462. add_peer_mwi_subs(authpeer);
  24463. ao2_lock(p);
  24464. }
  24465. if (authpeer->mwipvt != p) { /* Destroy old PVT if this is a new one */
  24466. /* We only allow one subscription per peer */
  24467. if (authpeer->mwipvt) {
  24468. dialog_unlink_all(authpeer->mwipvt);
  24469. authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
  24470. }
  24471. authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
  24472. }
  24473. if (p->relatedpeer != authpeer) {
  24474. if (p->relatedpeer) {
  24475. sip_unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
  24476. }
  24477. p->relatedpeer = sip_ref_peer(authpeer, "setting dialog's relatedpeer pointer");
  24478. }
  24479. /* Do not release authpeer here */
  24480. } else if (!strcmp(event, "call-completion")) {
  24481. handle_cc_subscribe(p, req);
  24482. } else { /* At this point, Asterisk does not understand the specified event */
  24483. transmit_response(p, "489 Bad Event", req);
  24484. ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
  24485. pvt_set_needdestroy(p, "unknown event package");
  24486. if (authpeer) {
  24487. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 5)");
  24488. }
  24489. return 0;
  24490. }
  24491. if (!req->ignore) {
  24492. p->lastinvite = seqno;
  24493. }
  24494. if (!p->needdestroy) {
  24495. p->expiry = atoi(sip_get_header(req, "Expires"));
  24496. /* check if the requested expiry-time is within the approved limits from sip.conf */
  24497. if (p->expiry > max_subexpiry) {
  24498. p->expiry = max_subexpiry;
  24499. } else if (p->expiry < min_subexpiry && p->expiry > 0) {
  24500. transmit_response_with_minexpires(p, "423 Interval too small", req, min_subexpiry);
  24501. ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
  24502. "with Expire header less than 'subminexpire' limit. Received \"Expire: %d\" min is %d\n",
  24503. p->exten, p->context, p->expiry, min_subexpiry);
  24504. pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
  24505. if (authpeer) {
  24506. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 6)");
  24507. }
  24508. return 0;
  24509. }
  24510. if (sipdebug) {
  24511. const char *action = p->expiry > 0 ? "Adding" : "Removing";
  24512. if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
  24513. ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
  24514. action, p->relatedpeer->name);
  24515. } else if (p->subscribed == CALL_COMPLETION) {
  24516. ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
  24517. } else {
  24518. ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
  24519. action, p->exten, p->context, p->username);
  24520. }
  24521. }
  24522. if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
  24523. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  24524. if (p->expiry > 0)
  24525. sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
  24526. if (p->subscribed == MWI_NOTIFICATION) {
  24527. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  24528. transmit_response(p, "200 OK", req);
  24529. if (p->relatedpeer) { /* Send first notification */
  24530. struct sip_peer *peer = p->relatedpeer;
  24531. sip_ref_peer(peer, "ensure a peer ref is held during MWI sending");
  24532. ao2_unlock(p);
  24533. sip_send_mwi_to_peer(peer, 0);
  24534. ao2_lock(p);
  24535. sip_unref_peer(peer, "release a peer ref now that MWI is sent");
  24536. }
  24537. } else if (p->subscribed != CALL_COMPLETION) {
  24538. struct state_notify_data data = { 0, };
  24539. char *subtype = NULL;
  24540. char *message = NULL;
  24541. struct ao2_container *device_state_info = NULL;
  24542. if (p->expiry > 0 && !resubscribe) {
  24543. /* Add subscription for extension state from the PBX core */
  24544. if (p->stateid != -1) {
  24545. ast_extension_state_del(p->stateid, cb_extensionstate);
  24546. }
  24547. dialog_ref(p, "copying dialog ptr into extension state struct");
  24548. p->stateid = ast_extension_state_add_destroy_extended(p->context, p->exten, cb_extensionstate, cb_extensionstate_destroy, p);
  24549. if (p->stateid == -1) {
  24550. dialog_unref(p, "copying dialog ptr into extension state struct failed");
  24551. }
  24552. }
  24553. sip_pvt_unlock(p);
  24554. data.state = ast_extension_state_extended(NULL, p->context, p->exten, &device_state_info);
  24555. sip_pvt_lock(p);
  24556. if (data.state < 0) {
  24557. ao2_cleanup(device_state_info);
  24558. if (p->expiry > 0) {
  24559. ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p->exten, p->context, ast_sockaddr_stringify(&p->sa));
  24560. }
  24561. transmit_response(p, "404 Not found", req);
  24562. pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
  24563. if (authpeer) {
  24564. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 6)");
  24565. }
  24566. return 0;
  24567. }
  24568. if (allow_notify_user_presence(p)) {
  24569. data.presence_state = ast_hint_presence_state(NULL, p->context, p->exten, &subtype, &message);
  24570. data.presence_subtype = subtype;
  24571. data.presence_message = message;
  24572. }
  24573. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  24574. transmit_response(p, "200 OK", req);
  24575. /* RFC 3265: A notification must be sent on every subscribe, so force it */
  24576. data.device_state_info = device_state_info;
  24577. if (data.state & AST_EXTENSION_RINGING) {
  24578. /* save last_ringing_channel_time if this state really contains a ringing channel
  24579. * because extensionstate_update() doesn't do it if forced
  24580. */
  24581. struct ast_channel *ringing = find_ringing_channel(data.device_state_info, p);
  24582. if (ringing) {
  24583. p->last_ringing_channel_time = ast_channel_creationtime(ringing);
  24584. ao2_ref(ringing, -1);
  24585. }
  24586. /* If there is no channel, this likely indicates that the ringing indication
  24587. * is due to a custom device state. These do not have associated channels.
  24588. */
  24589. }
  24590. extensionstate_update(p->context, p->exten, &data, p, TRUE);
  24591. append_history(p, "Subscribestatus", "%s", ast_extension_state2str(data.state));
  24592. /* hide the 'complete' exten/context in the refer_to field for later display */
  24593. ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
  24594. /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
  24595. ao2_cleanup(device_state_info);
  24596. ast_free(subtype);
  24597. ast_free(message);
  24598. }
  24599. if (!p->expiry) {
  24600. pvt_set_needdestroy(p, "forcing expiration");
  24601. }
  24602. }
  24603. if (authpeer) {
  24604. sip_unref_peer(authpeer, "unref pointer into (*authpeer)");
  24605. }
  24606. return 1;
  24607. }
  24608. /*! \brief Handle incoming REGISTER request */
  24609. static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
  24610. {
  24611. enum check_auth_result res;
  24612. /* If this is not the intial request, and the initial request isn't
  24613. * a register, something screwy happened, so bail */
  24614. if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
  24615. ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
  24616. return -1;
  24617. }
  24618. /* Use this as the basis */
  24619. copy_request(&p->initreq, req);
  24620. if (sipdebug)
  24621. ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  24622. check_via(p, req);
  24623. if ((res = register_verify(p, addr, req, e)) < 0) {
  24624. const char *reason;
  24625. switch (res) {
  24626. case AUTH_SECRET_FAILED:
  24627. reason = "Wrong password";
  24628. break;
  24629. case AUTH_USERNAME_MISMATCH:
  24630. reason = "Username/auth name mismatch";
  24631. break;
  24632. case AUTH_NOT_FOUND:
  24633. reason = "No matching peer found";
  24634. break;
  24635. case AUTH_UNKNOWN_DOMAIN:
  24636. reason = "Not a local domain";
  24637. break;
  24638. case AUTH_PEER_NOT_DYNAMIC:
  24639. reason = "Peer is not supposed to register";
  24640. break;
  24641. case AUTH_ACL_FAILED:
  24642. reason = "Device does not match ACL";
  24643. break;
  24644. case AUTH_BAD_TRANSPORT:
  24645. reason = "Device not configured to use this transport type";
  24646. break;
  24647. case AUTH_RTP_FAILED:
  24648. reason = "RTP initialization failed";
  24649. break;
  24650. default:
  24651. reason = "Unknown failure";
  24652. break;
  24653. }
  24654. ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
  24655. sip_get_header(req, "To"), ast_sockaddr_stringify(addr),
  24656. reason);
  24657. append_history(p, "RegRequest", "Failed : Account %s : %s", sip_get_header(req, "To"), reason);
  24658. } else {
  24659. req->authenticated = 1;
  24660. append_history(p, "RegRequest", "Succeeded : Account %s", sip_get_header(req, "To"));
  24661. }
  24662. if (res != AUTH_CHALLENGE_SENT) {
  24663. /* Destroy the session, but keep us around for just a bit in case they don't
  24664. get our 200 OK */
  24665. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  24666. }
  24667. return res;
  24668. }
  24669. /*!
  24670. * \brief Handle incoming SIP requests (methods)
  24671. * \note
  24672. * This is where all incoming requests go first.
  24673. * \note
  24674. * called with p and p->owner locked
  24675. */
  24676. static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
  24677. {
  24678. /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
  24679. relatively static */
  24680. const char *cmd;
  24681. const char *cseq;
  24682. const char *useragent;
  24683. const char *via;
  24684. const char *callid;
  24685. int via_pos = 0;
  24686. uint32_t seqno;
  24687. int len;
  24688. int respid;
  24689. int res = 0;
  24690. const char *e;
  24691. int error = 0;
  24692. int oldmethod = p->method;
  24693. int acked = 0;
  24694. /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
  24695. * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
  24696. * so we can check to make sure these fields exist for all requests and responses */
  24697. cseq = sip_get_header(req, "Cseq");
  24698. cmd = REQ_OFFSET_TO_STR(req, header[0]);
  24699. /* Save the via_pos so we can check later that responses only have 1 Via header */
  24700. via = __get_header(req, "Via", &via_pos);
  24701. /* This must exist already because we've called find_call by now */
  24702. callid = sip_get_header(req, "Call-ID");
  24703. /* Must have Cseq */
  24704. if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
  24705. ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
  24706. error = 1;
  24707. }
  24708. if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
  24709. ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
  24710. error = 1;
  24711. }
  24712. if (error) {
  24713. if (!p->initreq.headers) { /* New call */
  24714. pvt_set_needdestroy(p, "no headers");
  24715. }
  24716. return -1;
  24717. }
  24718. /* Get the command XXX */
  24719. cmd = REQ_OFFSET_TO_STR(req, rlpart1);
  24720. e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
  24721. /* Save useragent of the client */
  24722. useragent = sip_get_header(req, "User-Agent");
  24723. if (!ast_strlen_zero(useragent))
  24724. ast_string_field_set(p, useragent, useragent);
  24725. /* Find out SIP method for incoming request */
  24726. if (req->method == SIP_RESPONSE) { /* Response to our request */
  24727. /* ignore means "don't do anything with it" but still have to
  24728. * respond appropriately.
  24729. * But in this case this is a response already, so we really
  24730. * have nothing to do with this message, and even setting the
  24731. * ignore flag is pointless.
  24732. */
  24733. if (ast_strlen_zero(e)) {
  24734. return 0;
  24735. }
  24736. if (sscanf(e, "%30d %n", &respid, &len) != 1) {
  24737. ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
  24738. return 0;
  24739. }
  24740. if (respid <= 0) {
  24741. ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
  24742. return 0;
  24743. }
  24744. /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
  24745. * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
  24746. * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
  24747. if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
  24748. ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
  24749. return 0;
  24750. }
  24751. if (p->ocseq && (p->ocseq < seqno)) {
  24752. ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
  24753. return -1;
  24754. } else {
  24755. if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
  24756. extract_uri(p, req);
  24757. }
  24758. if (p->owner) {
  24759. struct ast_control_pvt_cause_code *cause_code;
  24760. int data_size = sizeof(*cause_code);
  24761. /* size of the string making up the cause code is "SIP " + cause length */
  24762. data_size += 4 + strlen(REQ_OFFSET_TO_STR(req, rlpart2));
  24763. cause_code = ast_alloca(data_size);
  24764. memset(cause_code, 0, data_size);
  24765. ast_copy_string(cause_code->chan_name, ast_channel_name(p->owner), AST_CHANNEL_NAME);
  24766. snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %s", REQ_OFFSET_TO_STR(req, rlpart2));
  24767. cause_code->ast_cause = hangup_sip2cause(respid);
  24768. if (global_store_sip_cause) {
  24769. cause_code->emulate_sip_cause = 1;
  24770. }
  24771. ast_queue_control_data(p->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
  24772. ast_channel_hangupcause_hash_set(p->owner, cause_code, data_size);
  24773. }
  24774. handle_response(p, respid, e + len, req, seqno);
  24775. }
  24776. return 0;
  24777. }
  24778. /* New SIP request coming in
  24779. (could be new request in existing SIP dialog as well...)
  24780. */
  24781. p->method = req->method; /* Find out which SIP method they are using */
  24782. ast_debug(4, "**** Received %s (%u) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
  24783. if (p->icseq && (p->icseq > seqno) ) {
  24784. if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
  24785. ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
  24786. } else {
  24787. ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
  24788. if (req->method == SIP_INVITE) {
  24789. unsigned int ran = (ast_random() % 10) + 1;
  24790. char seconds[4];
  24791. snprintf(seconds, sizeof(seconds), "%u", ran);
  24792. transmit_response_with_retry_after(p, "500 Server error", req, seconds); /* respond according to RFC 3261 14.2 with Retry-After betwewn 0 and 10 */
  24793. } else if (req->method != SIP_ACK) {
  24794. transmit_response(p, "500 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
  24795. }
  24796. return -1;
  24797. }
  24798. } else if (p->icseq &&
  24799. p->icseq == seqno &&
  24800. req->method != SIP_ACK &&
  24801. (p->method != SIP_CANCEL || p->alreadygone)) {
  24802. /* ignore means "don't do anything with it" but still have to
  24803. respond appropriately. We do this if we receive a repeat of
  24804. the last sequence number */
  24805. req->ignore = 1;
  24806. ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
  24807. }
  24808. /* RFC 3261 section 9. "CANCEL has no effect on a request to which a UAS has
  24809. * already given a final response." */
  24810. if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
  24811. transmit_response(p, "481 Call/Transaction Does Not Exist", req);
  24812. return res;
  24813. }
  24814. if (seqno >= p->icseq)
  24815. /* Next should follow monotonically (but not necessarily
  24816. incrementally -- thanks again to the genius authors of SIP --
  24817. increasing */
  24818. p->icseq = seqno;
  24819. /* Find their tag if we haven't got it */
  24820. if (ast_strlen_zero(p->theirtag)) {
  24821. char tag[128];
  24822. gettag(req, "From", tag, sizeof(tag));
  24823. ast_string_field_set(p, theirtag, tag);
  24824. }
  24825. snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
  24826. if (sip_cfg.pedanticsipchecking) {
  24827. /* If this is a request packet without a from tag, it's not
  24828. correct according to RFC 3261 */
  24829. /* Check if this a new request in a new dialog with a totag already attached to it,
  24830. RFC 3261 - section 12.2 - and we don't want to mess with recovery */
  24831. if (!p->initreq.headers && req->has_to_tag) {
  24832. /* If this is a first request and it got a to-tag, it is not for us */
  24833. if (!req->ignore && req->method == SIP_INVITE) {
  24834. /* Just because we think this is a dialog-starting INVITE with a to-tag
  24835. * doesn't mean it actually is. It could be a reinvite for an established, but
  24836. * unknown dialog. In such a case, we need to change our tag to the
  24837. * incoming INVITE's to-tag so that they will recognize the 481 we send and
  24838. * so that we will properly match their incoming ACK.
  24839. */
  24840. char totag[128];
  24841. gettag(req, "To", totag, sizeof(totag));
  24842. ast_string_field_set(p, tag, totag);
  24843. p->pendinginvite = p->icseq;
  24844. transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
  24845. /* Will cease to exist after ACK */
  24846. return res;
  24847. } else if (req->method != SIP_ACK) {
  24848. transmit_response(p, "481 Call/Transaction Does Not Exist", req);
  24849. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  24850. return res;
  24851. }
  24852. /* Otherwise, this is an ACK. It will always have a to-tag */
  24853. }
  24854. }
  24855. if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
  24856. transmit_response(p, "400 Bad request", req);
  24857. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  24858. return -1;
  24859. }
  24860. /* Handle various incoming SIP methods in requests */
  24861. switch (p->method) {
  24862. case SIP_OPTIONS:
  24863. res = handle_request_options(p, req, addr, e);
  24864. break;
  24865. case SIP_INVITE:
  24866. res = handle_request_invite(p, req, addr, seqno, recount, e, nounlock);
  24867. if (res < 9) {
  24868. sip_report_security_event(p, req, res);
  24869. }
  24870. switch (res) {
  24871. case INV_REQ_SUCCESS:
  24872. res = 1;
  24873. break;
  24874. case INV_REQ_FAILED:
  24875. res = 0;
  24876. break;
  24877. case INV_REQ_ERROR:
  24878. res = -1;
  24879. break;
  24880. default:
  24881. res = 0;
  24882. break;
  24883. }
  24884. break;
  24885. case SIP_REFER:
  24886. res = handle_request_refer(p, req, seqno, nounlock);
  24887. break;
  24888. case SIP_CANCEL:
  24889. res = handle_request_cancel(p, req);
  24890. break;
  24891. case SIP_BYE:
  24892. res = handle_request_bye(p, req);
  24893. break;
  24894. case SIP_MESSAGE:
  24895. res = handle_request_message(p, req, addr, e);
  24896. break;
  24897. case SIP_PUBLISH:
  24898. res = handle_request_publish(p, req, addr, seqno, e);
  24899. break;
  24900. case SIP_SUBSCRIBE:
  24901. res = handle_request_subscribe(p, req, addr, seqno, e);
  24902. break;
  24903. case SIP_REGISTER:
  24904. res = handle_request_register(p, req, addr, e);
  24905. sip_report_security_event(p, req, res);
  24906. break;
  24907. case SIP_INFO:
  24908. if (req->debug)
  24909. ast_verbose("Receiving INFO!\n");
  24910. if (!req->ignore)
  24911. handle_request_info(p, req);
  24912. else /* if ignoring, transmit response */
  24913. transmit_response(p, "200 OK", req);
  24914. break;
  24915. case SIP_NOTIFY:
  24916. res = handle_request_notify(p, req, addr, seqno, e);
  24917. break;
  24918. case SIP_UPDATE:
  24919. res = handle_request_update(p, req);
  24920. break;
  24921. case SIP_ACK:
  24922. /* Make sure we don't ignore this */
  24923. if (seqno == p->pendinginvite) {
  24924. p->invitestate = INV_TERMINATED;
  24925. p->pendinginvite = 0;
  24926. acked = __sip_ack(p, seqno, 1 /* response */, 0);
  24927. if (p->owner && find_sdp(req)) {
  24928. if (process_sdp(p, req, SDP_T38_NONE)) {
  24929. return -1;
  24930. }
  24931. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  24932. ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
  24933. }
  24934. }
  24935. check_pendings(p);
  24936. } else if (p->glareinvite == seqno) {
  24937. /* handle ack for the 491 pending sent for glareinvite */
  24938. p->glareinvite = 0;
  24939. acked = __sip_ack(p, seqno, 1, 0);
  24940. }
  24941. if (!acked) {
  24942. /* Got an ACK that did not match anything. Ignore
  24943. * silently and restore previous method */
  24944. p->method = oldmethod;
  24945. }
  24946. if (!p->lastinvite && ast_strlen_zero(p->nonce)) {
  24947. pvt_set_needdestroy(p, "unmatched ACK");
  24948. }
  24949. break;
  24950. default:
  24951. transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
  24952. ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
  24953. cmd, ast_sockaddr_stringify(&p->sa));
  24954. /* If this is some new method, and we don't have a call, destroy it now */
  24955. if (!p->initreq.headers) {
  24956. pvt_set_needdestroy(p, "unimplemented method");
  24957. }
  24958. break;
  24959. }
  24960. return res;
  24961. }
  24962. /*! \brief Read data from SIP UDP socket
  24963. \note sipsock_read locks the owner channel while we are processing the SIP message
  24964. \return 1 on error, 0 on success
  24965. \note Successful messages is connected to SIP call and forwarded to handle_incoming()
  24966. */
  24967. static int sipsock_read(int *id, int fd, short events, void *ignore)
  24968. {
  24969. struct sip_request req;
  24970. struct ast_sockaddr addr;
  24971. int res;
  24972. static char readbuf[65535];
  24973. memset(&req, 0, sizeof(req));
  24974. res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
  24975. if (res < 0) {
  24976. #if !defined(__FreeBSD__)
  24977. if (errno == EAGAIN)
  24978. ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
  24979. else
  24980. #endif
  24981. if (errno != ECONNREFUSED)
  24982. ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
  24983. return 1;
  24984. }
  24985. readbuf[res] = '\0';
  24986. if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
  24987. return 1;
  24988. }
  24989. if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
  24990. return -1;
  24991. }
  24992. req.socket.fd = sipsock;
  24993. set_socket_transport(&req.socket, AST_TRANSPORT_UDP);
  24994. req.socket.tcptls_session = NULL;
  24995. req.socket.port = htons(ast_sockaddr_port(&bindaddr));
  24996. handle_request_do(&req, &addr);
  24997. deinit_req(&req);
  24998. return 1;
  24999. }
  25000. /*! \brief Handle incoming SIP message - request or response
  25001. This is used for all transports (udp, tcp and tcp/tls)
  25002. */
  25003. static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
  25004. {
  25005. struct sip_pvt *p;
  25006. struct ast_channel *owner_chan_ref = NULL;
  25007. int recount = 0;
  25008. int nounlock = 0;
  25009. if (sip_debug_test_addr(addr)) /* Set the debug flag early on packet level */
  25010. req->debug = 1;
  25011. if (sip_cfg.pedanticsipchecking)
  25012. lws2sws(req->data); /* Fix multiline headers */
  25013. if (req->debug) {
  25014. ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
  25015. sip_get_transport(req->socket.type), ast_sockaddr_stringify(addr), ast_str_buffer(req->data));
  25016. }
  25017. if (parse_request(req) == -1) { /* Bad packet, can't parse */
  25018. ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
  25019. return 1;
  25020. }
  25021. req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlpart1));
  25022. if (req->debug)
  25023. ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
  25024. if (req->headers < 2) { /* Must have at least two headers */
  25025. ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
  25026. return 1;
  25027. }
  25028. ast_mutex_lock(&netlock);
  25029. /* Find the active SIP dialog or create a new one */
  25030. p = find_call(req, addr, req->method); /* returns p with a reference only. _NOT_ locked*/
  25031. if (p == NULL) {
  25032. ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
  25033. ast_mutex_unlock(&netlock);
  25034. return 1;
  25035. }
  25036. if (p->logger_callid) {
  25037. ast_callid_threadassoc_add(p->logger_callid);
  25038. }
  25039. /* Lock both the pvt and the owner if owner is present. This will
  25040. * not fail. */
  25041. owner_chan_ref = sip_pvt_lock_full(p);
  25042. copy_socket_data(&p->socket, &req->socket);
  25043. ast_sockaddr_copy(&p->recv, addr);
  25044. /* if we have an owner, then this request has been authenticated */
  25045. if (p->owner) {
  25046. req->authenticated = 1;
  25047. }
  25048. if (p->do_history) /* This is a request or response, note what it was for */
  25049. append_history(p, "Rx", "%s / %s / %s", ast_str_buffer(req->data), sip_get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlpart2));
  25050. if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
  25051. /* Request failed */
  25052. ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
  25053. }
  25054. if (recount) {
  25055. ast_update_use_count();
  25056. }
  25057. if (p->owner && !nounlock) {
  25058. ast_channel_unlock(p->owner);
  25059. }
  25060. if (owner_chan_ref) {
  25061. ast_channel_unref(owner_chan_ref);
  25062. }
  25063. sip_pvt_unlock(p);
  25064. ast_mutex_unlock(&netlock);
  25065. if (p->logger_callid) {
  25066. ast_callid_threadassoc_remove();
  25067. }
  25068. ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
  25069. return 1;
  25070. }
  25071. /*! \brief Returns the port to use for this socket
  25072. *
  25073. * \param type The type of transport used
  25074. * \param port Port we are checking to see if it's the standard port.
  25075. * \note port is expected in host byte order
  25076. */
  25077. static int sip_standard_port(enum ast_transport type, int port)
  25078. {
  25079. if (type & AST_TRANSPORT_TLS)
  25080. return port == STANDARD_TLS_PORT;
  25081. else
  25082. return port == STANDARD_SIP_PORT;
  25083. }
  25084. static int threadinfo_locate_cb(void *obj, void *arg, int flags)
  25085. {
  25086. struct sip_threadinfo *th = obj;
  25087. struct ast_sockaddr *s = arg;
  25088. if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
  25089. return CMP_MATCH | CMP_STOP;
  25090. }
  25091. return 0;
  25092. }
  25093. /*!
  25094. * \brief Find thread for TCP/TLS session (based on IP/Port
  25095. *
  25096. * \note This function returns an astobj2 reference
  25097. */
  25098. static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
  25099. {
  25100. struct sip_threadinfo *th;
  25101. struct ast_tcptls_session_instance *tcptls_instance = NULL;
  25102. if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
  25103. tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
  25104. ao2_t_ref(th, -1, "decrement ref from callback");
  25105. }
  25106. return tcptls_instance;
  25107. }
  25108. /*!
  25109. * \brief Helper for dns resolution to filter by address family.
  25110. *
  25111. * \note return 0 if addr is [::] else it returns addr's family.
  25112. */
  25113. int get_address_family_filter(unsigned int transport)
  25114. {
  25115. const struct ast_sockaddr *addr = NULL;
  25116. if ((transport == AST_TRANSPORT_UDP) || !transport) {
  25117. addr = &bindaddr;
  25118. } else if (transport == AST_TRANSPORT_TCP || transport == AST_TRANSPORT_WS) {
  25119. addr = &sip_tcp_desc.local_address;
  25120. } else if (transport == AST_TRANSPORT_TLS || transport == AST_TRANSPORT_WSS) {
  25121. addr = &sip_tls_desc.local_address;
  25122. }
  25123. if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
  25124. return 0;
  25125. }
  25126. return addr->ss.ss_family;
  25127. }
  25128. /*! \todo Get socket for dialog, prepare if needed, and return file handle */
  25129. static int sip_prepare_socket(struct sip_pvt *p)
  25130. {
  25131. struct sip_socket *s = &p->socket;
  25132. static const char name[] = "SIP socket";
  25133. struct sip_threadinfo *th = NULL;
  25134. struct ast_tcptls_session_instance *tcptls_session;
  25135. struct ast_tcptls_session_args *ca;
  25136. struct ast_sockaddr sa_tmp;
  25137. pthread_t launched;
  25138. /* check to see if a socket is already active */
  25139. if ((s->fd != -1) && (s->type == AST_TRANSPORT_UDP)) {
  25140. return s->fd;
  25141. }
  25142. if ((s->type & (AST_TRANSPORT_TCP | AST_TRANSPORT_TLS)) &&
  25143. (s->tcptls_session) &&
  25144. (s->tcptls_session->fd != -1)) {
  25145. return s->tcptls_session->fd;
  25146. }
  25147. if ((s->type & (AST_TRANSPORT_WS | AST_TRANSPORT_WSS))) {
  25148. return s->ws_session ? ast_websocket_fd(s->ws_session) : -1;
  25149. }
  25150. /*! \todo Check this... This might be wrong, depending on the proxy configuration
  25151. If proxy is in "force" mode its correct.
  25152. */
  25153. if (p->outboundproxy && p->outboundproxy->transport) {
  25154. s->type = p->outboundproxy->transport;
  25155. }
  25156. if (s->type == AST_TRANSPORT_UDP) {
  25157. s->fd = sipsock;
  25158. return s->fd;
  25159. }
  25160. /* At this point we are dealing with a TCP/TLS connection
  25161. * 1. We need to check to see if a connection thread exists
  25162. * for this address, if so use that.
  25163. * 2. If a thread does not exist for this address, but the tcptls_session
  25164. * exists on the socket, the connection was closed.
  25165. * 3. If no tcptls_session thread exists for the address, and no tcptls_session
  25166. * already exists on the socket, create a new one and launch a new thread.
  25167. */
  25168. /* 1. check for existing threads */
  25169. ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
  25170. if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
  25171. s->fd = tcptls_session->fd;
  25172. if (s->tcptls_session) {
  25173. ao2_ref(s->tcptls_session, -1);
  25174. s->tcptls_session = NULL;
  25175. }
  25176. s->tcptls_session = tcptls_session;
  25177. return s->fd;
  25178. /* 2. Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
  25179. } else if (s->tcptls_session) {
  25180. return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
  25181. }
  25182. /* 3. Create a new TCP/TLS client connection */
  25183. /* create new session arguments for the client connection */
  25184. if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
  25185. !(ca->name = ast_strdup(name))) {
  25186. goto create_tcptls_session_fail;
  25187. }
  25188. ca->accept_fd = -1;
  25189. ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
  25190. /* if type is TLS, we need to create a tls cfg for this session arg */
  25191. if (s->type == AST_TRANSPORT_TLS) {
  25192. if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
  25193. goto create_tcptls_session_fail;
  25194. }
  25195. memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
  25196. if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
  25197. !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
  25198. !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
  25199. !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
  25200. !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
  25201. goto create_tcptls_session_fail;
  25202. }
  25203. /* this host is used as the common name in ssl/tls */
  25204. if (!ast_strlen_zero(p->tohost)) {
  25205. ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
  25206. }
  25207. }
  25208. /* Create a client connection for address, this does not start the connection, just sets it up. */
  25209. if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
  25210. goto create_tcptls_session_fail;
  25211. }
  25212. s->fd = s->tcptls_session->fd;
  25213. /* client connections need to have the sip_threadinfo object created before
  25214. * the thread is detached. This ensures the alert_pipe is up before it will
  25215. * be used. Note that this function links the new threadinfo object into the
  25216. * threadt container. */
  25217. if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
  25218. goto create_tcptls_session_fail;
  25219. }
  25220. /* Give the new thread a reference to the tcptls_session */
  25221. ao2_ref(s->tcptls_session, +1);
  25222. if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
  25223. ast_debug(1, "Unable to launch '%s'.", ca->name);
  25224. ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
  25225. goto create_tcptls_session_fail;
  25226. }
  25227. return s->fd;
  25228. create_tcptls_session_fail:
  25229. if (ca) {
  25230. ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
  25231. }
  25232. if (s->tcptls_session) {
  25233. ast_tcptls_close_session_file(s->tcptls_session);
  25234. s->fd = -1;
  25235. ao2_ref(s->tcptls_session, -1);
  25236. s->tcptls_session = NULL;
  25237. }
  25238. if (th) {
  25239. ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
  25240. }
  25241. return -1;
  25242. }
  25243. /*!
  25244. * \brief Get cached MWI info
  25245. * \return TRUE if found MWI in cache
  25246. */
  25247. static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
  25248. {
  25249. struct sip_mailbox *mailbox;
  25250. int in_cache;
  25251. in_cache = 0;
  25252. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  25253. RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
  25254. struct ast_mwi_state *mwi_state;
  25255. msg = stasis_cache_get(ast_mwi_state_cache(), ast_mwi_state_type(), mailbox->id);
  25256. if (!msg) {
  25257. continue;
  25258. }
  25259. mwi_state = stasis_message_data(msg);
  25260. *new += mwi_state->new_msgs;
  25261. *old += mwi_state->old_msgs;
  25262. in_cache = 1;
  25263. }
  25264. return in_cache;
  25265. }
  25266. /*! \brief Send message waiting indication to alert peer that they've got voicemail
  25267. * \note Both peer and associated sip_pvt must be unlocked prior to calling this function
  25268. * \returns -1 on failure, 0 on success
  25269. */
  25270. static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
  25271. {
  25272. /* Called with peer lock, but releases it */
  25273. struct sip_pvt *p;
  25274. int newmsgs = 0, oldmsgs = 0;
  25275. const char *vmexten = NULL;
  25276. ao2_lock(peer);
  25277. if (peer->vmexten) {
  25278. vmexten = ast_strdupa(peer->vmexten);
  25279. }
  25280. if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
  25281. update_peer_lastmsgssent(peer, -1, 1);
  25282. ao2_unlock(peer);
  25283. return -1;
  25284. }
  25285. /* Do we have an IP address? If not, skip this peer */
  25286. if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
  25287. update_peer_lastmsgssent(peer, -1, 1);
  25288. ao2_unlock(peer);
  25289. return -1;
  25290. }
  25291. /* Attempt to use cached mwi to get message counts. */
  25292. if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
  25293. /* Fall back to manually checking the mailbox if not cache_only and get_cached_mwi failed */
  25294. struct ast_str *mailbox_str = ast_str_alloca(512);
  25295. peer_mailboxes_to_str(&mailbox_str, peer);
  25296. /* if there is no mailbox do nothing */
  25297. if (!ast_str_strlen(mailbox_str)) {
  25298. ao2_unlock(peer);
  25299. return -1;
  25300. }
  25301. ao2_unlock(peer);
  25302. /* If there is no mailbox do nothing */
  25303. if (!ast_str_strlen(mailbox_str)) {
  25304. update_peer_lastmsgssent(peer, -1, 0);
  25305. return 0;
  25306. }
  25307. ast_app_inboxcount(ast_str_buffer(mailbox_str), &newmsgs, &oldmsgs);
  25308. ao2_lock(peer);
  25309. }
  25310. if (peer->mwipvt) {
  25311. /* Base message on subscription */
  25312. p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
  25313. ao2_unlock(peer);
  25314. } else {
  25315. ao2_unlock(peer);
  25316. /* Build temporary dialog for this message */
  25317. if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, 0))) {
  25318. update_peer_lastmsgssent(peer, -1, 0);
  25319. return -1;
  25320. }
  25321. /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
  25322. * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy
  25323. * the peer's socket information to the sip_pvt we just allocated
  25324. */
  25325. set_socket_transport(&p->socket, 0);
  25326. if (create_addr_from_peer(p, peer)) {
  25327. /* Maybe they're not registered, etc. */
  25328. dialog_unlink_all(p);
  25329. dialog_unref(p, "unref dialog p just created via sip_alloc");
  25330. update_peer_lastmsgssent(peer, -1, 0);
  25331. return -1;
  25332. }
  25333. /* Recalculate our side, and recalculate Call ID */
  25334. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  25335. build_via(p);
  25336. ao2_lock(peer);
  25337. if (!ast_strlen_zero(peer->mwi_from)) {
  25338. ast_string_field_set(p, mwi_from, peer->mwi_from);
  25339. } else if (!ast_strlen_zero(default_mwi_from)) {
  25340. ast_string_field_set(p, mwi_from, default_mwi_from);
  25341. }
  25342. ao2_unlock(peer);
  25343. /* Change the dialog callid. */
  25344. change_callid_pvt(p, NULL);
  25345. /* Destroy this session after 32 secs */
  25346. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  25347. }
  25348. /* We have multiple threads (mwi events and monitor retransmits) working with this PVT and as we modify the sip history if that's turned on,
  25349. we really need to have a lock on it */
  25350. sip_pvt_lock(p);
  25351. /* Send MWI */
  25352. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  25353. /* the following will decrement the refcount on p as it finishes */
  25354. transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
  25355. sip_pvt_unlock(p);
  25356. dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
  25357. update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
  25358. return 0;
  25359. }
  25360. static struct ast_manager_event_blob *session_timeout_to_ami(struct stasis_message *msg)
  25361. {
  25362. RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
  25363. struct ast_channel_blob *obj = stasis_message_data(msg);
  25364. const char *source = ast_json_string_get(ast_json_object_get(obj->blob, "source"));
  25365. channel_string = ast_manager_build_channel_state_string(obj->snapshot);
  25366. if (!channel_string) {
  25367. return NULL;
  25368. }
  25369. return ast_manager_event_blob_create(EVENT_FLAG_CALL, "SessionTimeout",
  25370. "%s"
  25371. "Source: %s\r\n",
  25372. ast_str_buffer(channel_string), source);
  25373. }
  25374. /*! \brief Sends a session timeout channel blob used to produce SessionTimeout AMI messages */
  25375. static void send_session_timeout(struct ast_channel *chan, const char *source)
  25376. {
  25377. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  25378. ast_assert(chan != NULL);
  25379. ast_assert(source != NULL);
  25380. blob = ast_json_pack("{s: s}", "source", source);
  25381. if (!blob) {
  25382. return;
  25383. }
  25384. ast_channel_publish_blob(chan, session_timeout_type(), blob);
  25385. }
  25386. /*!
  25387. * \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked
  25388. *
  25389. * \return CMP_MATCH for items to be unlinked from dialogs_rtpcheck.
  25390. */
  25391. static int check_rtp_timeout(struct sip_pvt *dialog, time_t t)
  25392. {
  25393. int timeout;
  25394. int hold_timeout;
  25395. int keepalive;
  25396. if (!dialog->rtp) {
  25397. /*
  25398. * We have no RTP. Since we don't do much with video RTP for
  25399. * now, stop checking this dialog.
  25400. */
  25401. return CMP_MATCH;
  25402. }
  25403. /* If we have no active owner, no need to check timers */
  25404. if (!dialog->owner) {
  25405. return CMP_MATCH;
  25406. }
  25407. /* If the call is redirected outside Asterisk, no need to check timers */
  25408. if (!ast_sockaddr_isnull(&dialog->redirip)) {
  25409. return CMP_MATCH;
  25410. }
  25411. /* If the call is involved in a T38 fax session do not check RTP timeout */
  25412. if (dialog->t38.state == T38_ENABLED) {
  25413. return CMP_MATCH;
  25414. }
  25415. /* If the call is not in UP state return for later check. */
  25416. if (ast_channel_state(dialog->owner) != AST_STATE_UP) {
  25417. return 0;
  25418. }
  25419. /* Store these values locally to avoid multiple function calls */
  25420. timeout = ast_rtp_instance_get_timeout(dialog->rtp);
  25421. hold_timeout = ast_rtp_instance_get_hold_timeout(dialog->rtp);
  25422. keepalive = ast_rtp_instance_get_keepalive(dialog->rtp);
  25423. /* If we have no timers set, return now */
  25424. if (!keepalive && !timeout && !hold_timeout) {
  25425. return CMP_MATCH;
  25426. }
  25427. /* Check AUDIO RTP keepalives */
  25428. if (dialog->lastrtptx && keepalive && (t > dialog->lastrtptx + keepalive)) {
  25429. /* Need to send an empty RTP packet */
  25430. dialog->lastrtptx = time(NULL);
  25431. ast_rtp_instance_sendcng(dialog->rtp, 0);
  25432. }
  25433. /*! \todo Check video RTP keepalives
  25434. Do we need to move the lastrtptx to the RTP structure to have one for audio and one
  25435. for video? It really does belong to the RTP structure.
  25436. */
  25437. /* Check AUDIO RTP timers */
  25438. if (dialog->lastrtprx && (timeout || hold_timeout) && (t > dialog->lastrtprx + timeout)) {
  25439. if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (hold_timeout && (t > dialog->lastrtprx + hold_timeout))) {
  25440. /* Needs a hangup */
  25441. if (timeout) {
  25442. if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
  25443. /*
  25444. * Don't block, just try again later.
  25445. * If there was no owner, the call is dead already.
  25446. */
  25447. return 0;
  25448. }
  25449. ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
  25450. ast_channel_name(dialog->owner), (long) (t - dialog->lastrtprx));
  25451. send_session_timeout(dialog->owner, "RTPTimeout");
  25452. /* Issue a softhangup */
  25453. ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
  25454. ast_channel_unlock(dialog->owner);
  25455. /* forget the timeouts for this call, since a hangup
  25456. has already been requested and we don't want to
  25457. repeatedly request hangups
  25458. */
  25459. ast_rtp_instance_set_timeout(dialog->rtp, 0);
  25460. ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
  25461. if (dialog->vrtp) {
  25462. ast_rtp_instance_set_timeout(dialog->vrtp, 0);
  25463. ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
  25464. }
  25465. /* finally unlink the dialog from dialogs_rtpcheck. */
  25466. return CMP_MATCH;
  25467. }
  25468. }
  25469. }
  25470. return 0;
  25471. }
  25472. /*! \brief The SIP monitoring thread
  25473. \note This thread monitors all the SIP sessions and peers that needs notification of mwi
  25474. (and thus do not have a separate thread) indefinitely
  25475. */
  25476. static void *do_monitor(void *data)
  25477. {
  25478. int res;
  25479. time_t t;
  25480. int reloading;
  25481. /* Add an I/O event to our SIP UDP socket */
  25482. if (sipsock > -1) {
  25483. sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
  25484. }
  25485. /* From here on out, we die whenever asked */
  25486. for(;;) {
  25487. /* Check for a reload request */
  25488. ast_mutex_lock(&sip_reload_lock);
  25489. reloading = sip_reloading;
  25490. sip_reloading = FALSE;
  25491. ast_mutex_unlock(&sip_reload_lock);
  25492. if (reloading) {
  25493. ast_verb(1, "Reloading SIP\n");
  25494. sip_do_reload(sip_reloadreason);
  25495. /* Change the I/O fd of our UDP socket */
  25496. if (sipsock > -1) {
  25497. if (sipsock_read_id) {
  25498. sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
  25499. } else {
  25500. sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
  25501. }
  25502. } else if (sipsock_read_id) {
  25503. ast_io_remove(io, sipsock_read_id);
  25504. sipsock_read_id = NULL;
  25505. }
  25506. }
  25507. /* Check for dialogs needing to be killed */
  25508. t = time(NULL);
  25509. /*
  25510. * Check dialogs with rtp and rtptimeout.
  25511. * All dialogs which have rtp are in dialogs_rtpcheck.
  25512. */
  25513. ao2_t_callback(dialogs_rtpcheck, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
  25514. dialog_checkrtp_cb, &t,
  25515. "callback to check rtptimeout and hangup calls if necessary");
  25516. /*
  25517. * Check dialogs marked to be destroyed.
  25518. * All dialogs with needdestroy set are in dialogs_needdestroy.
  25519. */
  25520. ao2_t_callback(dialogs_needdestroy, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy,
  25521. NULL, "callback to check dialogs which need to be destroyed");
  25522. /* XXX TODO The scheduler usage in this module does not have sufficient
  25523. * synchronization being done between running the scheduler and places
  25524. * scheduling tasks. As it is written, any scheduled item may not run
  25525. * any sooner than about 1 second, regardless of whether a sooner time
  25526. * was asked for. */
  25527. pthread_testcancel();
  25528. /* Wait for sched or io */
  25529. res = ast_sched_wait(sched);
  25530. if ((res < 0) || (res > 1000)) {
  25531. res = 1000;
  25532. }
  25533. res = ast_io_wait(io, res);
  25534. if (res > 20) {
  25535. ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
  25536. }
  25537. ast_mutex_lock(&monlock);
  25538. res = ast_sched_runq(sched);
  25539. if (res >= 20) {
  25540. ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
  25541. }
  25542. ast_mutex_unlock(&monlock);
  25543. }
  25544. /* Never reached */
  25545. return NULL;
  25546. }
  25547. /*! \brief Start the channel monitor thread */
  25548. static int restart_monitor(void)
  25549. {
  25550. /* If we're supposed to be stopped -- stay stopped */
  25551. if (monitor_thread == AST_PTHREADT_STOP)
  25552. return 0;
  25553. ast_mutex_lock(&monlock);
  25554. if (monitor_thread == pthread_self()) {
  25555. ast_mutex_unlock(&monlock);
  25556. ast_log(LOG_WARNING, "Cannot kill myself\n");
  25557. return -1;
  25558. }
  25559. if (monitor_thread != AST_PTHREADT_NULL && monitor_thread != AST_PTHREADT_STOP) {
  25560. /* Wake up the thread */
  25561. pthread_kill(monitor_thread, SIGURG);
  25562. } else {
  25563. /* Start a new monitor */
  25564. if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
  25565. ast_mutex_unlock(&monlock);
  25566. ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
  25567. return -1;
  25568. }
  25569. }
  25570. ast_mutex_unlock(&monlock);
  25571. return 0;
  25572. }
  25573. static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
  25574. struct stasis_message *message)
  25575. {
  25576. if (stasis_message_type(message) != ast_named_acl_change_type()) {
  25577. return;
  25578. }
  25579. ast_log(LOG_NOTICE, "Reloading chan_sip in response to ACL change event.\n");
  25580. ast_mutex_lock(&sip_reload_lock);
  25581. if (sip_reloading) {
  25582. ast_verbose("Previous SIP reload not yet done\n");
  25583. } else {
  25584. sip_reloading = TRUE;
  25585. sip_reloadreason = CHANNEL_ACL_RELOAD;
  25586. }
  25587. ast_mutex_unlock(&sip_reload_lock);
  25588. restart_monitor();
  25589. }
  25590. /*! \brief Session-Timers: Restart session timer */
  25591. static void restart_session_timer(struct sip_pvt *p)
  25592. {
  25593. if (p->stimer->st_active == TRUE) {
  25594. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  25595. AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
  25596. dialog_unref(p, "Removing session timer ref"));
  25597. start_session_timer(p);
  25598. }
  25599. }
  25600. /*! \brief Session-Timers: Stop session timer */
  25601. static void stop_session_timer(struct sip_pvt *p)
  25602. {
  25603. if (p->stimer->st_active == TRUE) {
  25604. p->stimer->st_active = FALSE;
  25605. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  25606. AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
  25607. dialog_unref(p, "removing session timer ref"));
  25608. }
  25609. }
  25610. /*! \brief Session-Timers: Start session timer */
  25611. static void start_session_timer(struct sip_pvt *p)
  25612. {
  25613. unsigned int timeout_ms;
  25614. if (p->stimer->st_schedid > -1) {
  25615. /* in the event a timer is already going, stop it */
  25616. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  25617. AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
  25618. dialog_unref(p, "unref stimer->st_schedid from dialog"));
  25619. }
  25620. /*
  25621. * RFC 4028 Section 10
  25622. * If the side not performing refreshes does not receive a
  25623. * session refresh request before the session expiration, it SHOULD send
  25624. * a BYE to terminate the session, slightly before the session
  25625. * expiration. The minimum of 32 seconds and one third of the session
  25626. * interval is RECOMMENDED.
  25627. */
  25628. timeout_ms = (1000 * p->stimer->st_interval);
  25629. if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
  25630. timeout_ms /= 2;
  25631. } else {
  25632. timeout_ms -= MIN(timeout_ms / 3, 32000);
  25633. }
  25634. p->stimer->st_schedid = ast_sched_add(sched, timeout_ms, proc_session_timer,
  25635. dialog_ref(p, "adding session timer ref"));
  25636. if (p->stimer->st_schedid < 0) {
  25637. dialog_unref(p, "removing session timer ref");
  25638. ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
  25639. } else {
  25640. p->stimer->st_active = TRUE;
  25641. ast_debug(2, "Session timer started: %d - %s %ums\n", p->stimer->st_schedid, p->callid, timeout_ms);
  25642. }
  25643. }
  25644. /*! \brief Session-Timers: Process session refresh timeout event */
  25645. static int proc_session_timer(const void *vp)
  25646. {
  25647. struct sip_pvt *p = (struct sip_pvt *) vp;
  25648. int res = 0;
  25649. if (!p->stimer) {
  25650. ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
  25651. goto return_unref;
  25652. }
  25653. ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
  25654. if (!p->owner) {
  25655. goto return_unref;
  25656. }
  25657. if ((p->stimer->st_active != TRUE) || (ast_channel_state(p->owner) != AST_STATE_UP)) {
  25658. goto return_unref;
  25659. }
  25660. if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
  25661. res = 1;
  25662. if (T38_ENABLED == p->t38.state) {
  25663. transmit_reinvite_with_sdp(p, TRUE, TRUE);
  25664. } else {
  25665. transmit_reinvite_with_sdp(p, FALSE, TRUE);
  25666. }
  25667. } else {
  25668. if (p->stimer->quit_flag) {
  25669. goto return_unref;
  25670. }
  25671. ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
  25672. sip_pvt_lock(p);
  25673. while (p->owner && ast_channel_trylock(p->owner)) {
  25674. sip_pvt_unlock(p);
  25675. usleep(1);
  25676. if (p->stimer && p->stimer->quit_flag) {
  25677. goto return_unref;
  25678. }
  25679. sip_pvt_lock(p);
  25680. }
  25681. send_session_timeout(p->owner, "SIPSessionTimer");
  25682. ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
  25683. ast_channel_unlock(p->owner);
  25684. sip_pvt_unlock(p);
  25685. }
  25686. return_unref:
  25687. if (!res) {
  25688. /* An error occurred. Stop session timer processing */
  25689. if (p->stimer) {
  25690. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  25691. /* Don't pass go, don't collect $200.. we are the scheduled
  25692. * callback. We can rip ourself out here. */
  25693. p->stimer->st_schedid = -1;
  25694. /* Calling stop_session_timer is nice for consistent debug
  25695. * logs. */
  25696. stop_session_timer(p);
  25697. }
  25698. /* If we are not asking to be rescheduled, then we need to release our
  25699. * reference to the dialog. */
  25700. dialog_unref(p, "removing session timer ref");
  25701. }
  25702. return res;
  25703. }
  25704. /*! \brief Session-Timers: Function for parsing Min-SE header */
  25705. int parse_minse (const char *p_hdrval, int *const p_interval)
  25706. {
  25707. if (ast_strlen_zero(p_hdrval)) {
  25708. ast_log(LOG_WARNING, "Null Min-SE header\n");
  25709. return -1;
  25710. }
  25711. *p_interval = 0;
  25712. p_hdrval = ast_skip_blanks(p_hdrval);
  25713. if (!sscanf(p_hdrval, "%30d", p_interval)) {
  25714. ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
  25715. return -1;
  25716. }
  25717. ast_debug(2, "Received Min-SE: %d\n", *p_interval);
  25718. return 0;
  25719. }
  25720. /*! \brief Session-Timers: Function for parsing Session-Expires header */
  25721. int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
  25722. {
  25723. char *p_token;
  25724. int ref_idx;
  25725. char *p_se_hdr;
  25726. if (ast_strlen_zero(p_hdrval)) {
  25727. ast_log(LOG_WARNING, "Null Session-Expires header\n");
  25728. return -1;
  25729. }
  25730. *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
  25731. *p_interval = 0;
  25732. p_se_hdr = ast_strdupa(p_hdrval);
  25733. p_se_hdr = ast_skip_blanks(p_se_hdr);
  25734. while ((p_token = strsep(&p_se_hdr, ";"))) {
  25735. p_token = ast_skip_blanks(p_token);
  25736. if (!sscanf(p_token, "%30d", p_interval)) {
  25737. ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
  25738. return -1;
  25739. }
  25740. ast_debug(2, "Session-Expires: %d\n", *p_interval);
  25741. if (!p_se_hdr)
  25742. continue;
  25743. p_se_hdr = ast_skip_blanks(p_se_hdr);
  25744. ref_idx = strlen("refresher=");
  25745. if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
  25746. p_se_hdr += ref_idx;
  25747. p_se_hdr = ast_skip_blanks(p_se_hdr);
  25748. if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
  25749. *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
  25750. ast_debug(2, "Refresher: UAC\n");
  25751. } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
  25752. *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
  25753. ast_debug(2, "Refresher: UAS\n");
  25754. } else {
  25755. ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
  25756. return -1;
  25757. }
  25758. break;
  25759. }
  25760. }
  25761. return 0;
  25762. }
  25763. /*! \brief Handle 422 response to INVITE with session-timer requested
  25764. Session-Timers: An INVITE originated by Asterisk that asks for session-timers support
  25765. from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
  25766. server tells Asterisk that the session refresh interval offered by Asterisk is too low
  25767. for them. The proc_422_rsp() function handles a 422 response. It extracts the Min-SE
  25768. header that comes back in 422 and sends a new INVITE accordingly. */
  25769. static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
  25770. {
  25771. int rtn;
  25772. const char *p_hdrval;
  25773. int minse;
  25774. p_hdrval = sip_get_header(rsp, "Min-SE");
  25775. if (ast_strlen_zero(p_hdrval)) {
  25776. ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
  25777. return;
  25778. }
  25779. rtn = parse_minse(p_hdrval, &minse);
  25780. if (rtn != 0) {
  25781. ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
  25782. return;
  25783. }
  25784. p->stimer->st_cached_min_se = minse;
  25785. if (p->stimer->st_interval < minse) {
  25786. p->stimer->st_interval = minse;
  25787. }
  25788. transmit_invite(p, SIP_INVITE, 1, 2, NULL);
  25789. }
  25790. /*! \brief Get Max or Min SE (session timer expiry)
  25791. * \param p pointer to the SIP dialog
  25792. * \param max if true, get max se, otherwise min se
  25793. */
  25794. int st_get_se(struct sip_pvt *p, int max)
  25795. {
  25796. if (max == TRUE) {
  25797. if (p->stimer->st_cached_max_se) {
  25798. return p->stimer->st_cached_max_se;
  25799. }
  25800. if (p->relatedpeer) {
  25801. p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
  25802. return (p->stimer->st_cached_max_se);
  25803. }
  25804. p->stimer->st_cached_max_se = global_max_se;
  25805. return (p->stimer->st_cached_max_se);
  25806. }
  25807. /* Find Min SE timer */
  25808. if (p->stimer->st_cached_min_se) {
  25809. return p->stimer->st_cached_min_se;
  25810. }
  25811. if (p->relatedpeer) {
  25812. p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
  25813. return (p->stimer->st_cached_min_se);
  25814. }
  25815. p->stimer->st_cached_min_se = global_min_se;
  25816. return (p->stimer->st_cached_min_se);
  25817. }
  25818. /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
  25819. * \note This is only called when processing an INVITE, so in that case Asterisk is
  25820. * always currently the UAS. If this is ever used to process responses, the
  25821. * function will have to be changed.
  25822. * \param p pointer to the SIP dialog
  25823. */
  25824. enum st_refresher st_get_refresher(struct sip_pvt *p)
  25825. {
  25826. if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
  25827. return p->stimer->st_cached_ref;
  25828. }
  25829. if (p->relatedpeer) {
  25830. p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
  25831. return p->stimer->st_cached_ref;
  25832. }
  25833. p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
  25834. return p->stimer->st_cached_ref;
  25835. }
  25836. /*!
  25837. * \brief Get the session-timer mode
  25838. * \param p pointer to the SIP dialog
  25839. * \param no_cached Set this to true in order to force a peername lookup on
  25840. * the session timer mode.
  25841. */
  25842. enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
  25843. {
  25844. if (!p->stimer) {
  25845. sip_st_alloc(p);
  25846. if (!p->stimer) {
  25847. return SESSION_TIMER_MODE_INVALID;
  25848. }
  25849. }
  25850. if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
  25851. return p->stimer->st_cached_mode;
  25852. if (p->relatedpeer) {
  25853. p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
  25854. return p->stimer->st_cached_mode;
  25855. }
  25856. p->stimer->st_cached_mode = global_st_mode;
  25857. return global_st_mode;
  25858. }
  25859. /*! \brief Send keep alive packet to peer */
  25860. static int sip_send_keepalive(const void *data)
  25861. {
  25862. struct sip_peer *peer = (struct sip_peer*) data;
  25863. int res = 0;
  25864. const char keepalive[] = "\r\n";
  25865. peer->keepalivesend = -1;
  25866. if (!peer->keepalive || ast_sockaddr_isnull(&peer->addr)) {
  25867. sip_unref_peer(peer, "release keepalive peer ref");
  25868. return 0;
  25869. }
  25870. /* Send the packet out using the proper method for this peer */
  25871. if ((peer->socket.fd != -1) && (peer->socket.type == AST_TRANSPORT_UDP)) {
  25872. res = ast_sendto(peer->socket.fd, keepalive, sizeof(keepalive), 0, &peer->addr);
  25873. } else if ((peer->socket.type & (AST_TRANSPORT_TCP | AST_TRANSPORT_TLS)) &&
  25874. (peer->socket.tcptls_session) &&
  25875. (peer->socket.tcptls_session->fd != -1)) {
  25876. res = sip_tcptls_write(peer->socket.tcptls_session, keepalive, sizeof(keepalive));
  25877. } else if (peer->socket.type == AST_TRANSPORT_UDP) {
  25878. res = ast_sendto(sipsock, keepalive, sizeof(keepalive), 0, &peer->addr);
  25879. }
  25880. if (res == -1) {
  25881. switch (errno) {
  25882. case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
  25883. case EHOSTUNREACH: /* Host can't be reached */
  25884. case ENETDOWN: /* Interface down */
  25885. case ENETUNREACH: /* Network failure */
  25886. case ECONNREFUSED: /* ICMP port unreachable */
  25887. res = XMIT_ERROR; /* Don't bother with trying to transmit again */
  25888. }
  25889. }
  25890. if (res != sizeof(keepalive)) {
  25891. ast_log(LOG_WARNING, "sip_send_keepalive to %s returned %d: %s\n", ast_sockaddr_stringify(&peer->addr), res, strerror(errno));
  25892. }
  25893. AST_SCHED_REPLACE_UNREF(peer->keepalivesend, sched,
  25894. peer->keepalive * 1000, sip_send_keepalive, peer,
  25895. sip_unref_peer(_data, "removing keepalive peer ref"),
  25896. sip_unref_peer(peer, "removing keepalive peer ref"),
  25897. sip_ref_peer(peer, "adding keepalive peer ref"));
  25898. sip_unref_peer(peer, "release keepalive peer ref");
  25899. return 0;
  25900. }
  25901. /*! \brief React to lack of answer to Qualify poke */
  25902. static int sip_poke_noanswer(const void *data)
  25903. {
  25904. struct sip_peer *peer = (struct sip_peer *)data;
  25905. peer->pokeexpire = -1;
  25906. if (peer->lastms > -1) {
  25907. ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
  25908. if (sip_cfg.peer_rtupdate) {
  25909. ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
  25910. }
  25911. if (peer->endpoint) {
  25912. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  25913. ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_OFFLINE);
  25914. blob = ast_json_pack("{s: s, s: s}",
  25915. "peer_status", "Unreachable",
  25916. "time", "-1");
  25917. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  25918. }
  25919. if (sip_cfg.regextenonqualify) {
  25920. register_peer_exten(peer, FALSE);
  25921. }
  25922. }
  25923. if (peer->call) {
  25924. dialog_unlink_all(peer->call);
  25925. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  25926. /* peer->call = sip_destroy(peer->call);*/
  25927. }
  25928. /* Don't send a devstate change if nothing changed. */
  25929. if (peer->lastms > -1) {
  25930. peer->lastms = -1;
  25931. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  25932. }
  25933. /* Try again quickly */
  25934. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
  25935. DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
  25936. sip_unref_peer(_data, "removing poke peer ref"),
  25937. sip_unref_peer(peer, "removing poke peer ref"),
  25938. sip_ref_peer(peer, "adding poke peer ref"));
  25939. /* Release the ref held by the running scheduler entry */
  25940. sip_unref_peer(peer, "release peer poke noanswer ref");
  25941. return 0;
  25942. }
  25943. /*! \brief Check availability of peer, also keep NAT open
  25944. \note This is done with 60 seconds between each ping,
  25945. unless forced by cli or manager. If peer is unreachable,
  25946. we check every 10th second by default.
  25947. \note Do *not* hold a pvt lock while calling this function.
  25948. This function calls sip_alloc, which can cause a deadlock
  25949. if another sip_pvt is held.
  25950. */
  25951. static int sip_poke_peer(struct sip_peer *peer, int force)
  25952. {
  25953. struct sip_pvt *p;
  25954. int xmitres = 0;
  25955. if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
  25956. /* IF we have no IP, or this isn't to be monitored, return
  25957. immediately after clearing things out */
  25958. AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
  25959. sip_unref_peer(peer, "removing poke peer ref"));
  25960. peer->lastms = 0;
  25961. if (peer->call) {
  25962. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  25963. }
  25964. return 0;
  25965. }
  25966. if (peer->call) {
  25967. if (sipdebug) {
  25968. ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
  25969. }
  25970. dialog_unlink_all(peer->call);
  25971. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  25972. /* peer->call = sip_destroy(peer->call); */
  25973. }
  25974. if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL, 0))) {
  25975. return -1;
  25976. }
  25977. peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
  25978. p->sa = peer->addr;
  25979. p->recv = peer->addr;
  25980. copy_socket_data(&p->socket, &peer->socket);
  25981. ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
  25982. ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  25983. ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  25984. sip_route_copy(&p->route, &peer->path);
  25985. if (!sip_route_empty(&p->route)) {
  25986. /* Parse SIP URI of first route-set hop and use it as target address */
  25987. __set_address_from_contact(sip_route_first_uri(&p->route), &p->sa, p->socket.type == AST_TRANSPORT_TLS ? 1 : 0);
  25988. }
  25989. /* Get the outbound proxy information */
  25990. ref_proxy(p, obproxy_get(p, peer));
  25991. /* Send OPTIONs to peer's fullcontact */
  25992. if (!ast_strlen_zero(peer->fullcontact)) {
  25993. ast_string_field_set(p, fullcontact, peer->fullcontact);
  25994. }
  25995. if (!ast_strlen_zero(peer->fromuser)) {
  25996. ast_string_field_set(p, fromuser, peer->fromuser);
  25997. }
  25998. if (!ast_strlen_zero(peer->tohost)) {
  25999. ast_string_field_set(p, tohost, peer->tohost);
  26000. } else {
  26001. ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
  26002. }
  26003. /* Recalculate our side, and recalculate Call ID */
  26004. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  26005. build_via(p);
  26006. /* Change the dialog callid. */
  26007. change_callid_pvt(p, NULL);
  26008. AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
  26009. sip_unref_peer(peer, "removing poke peer ref"));
  26010. if (p->relatedpeer)
  26011. p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
  26012. p->relatedpeer = sip_ref_peer(peer, "setting the relatedpeer field in the dialog");
  26013. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  26014. #ifdef VOCAL_DATA_HACK
  26015. ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
  26016. xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL); /* sinks the p refcount */
  26017. #else
  26018. xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL); /* sinks the p refcount */
  26019. #endif
  26020. peer->ps = ast_tvnow();
  26021. if (xmitres == XMIT_ERROR) {
  26022. /* Immediately unreachable, network problems */
  26023. sip_poke_noanswer(sip_ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
  26024. } else if (!force) {
  26025. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
  26026. sip_unref_peer(_data, "removing poke peer ref"),
  26027. sip_unref_peer(peer, "removing poke peer ref"),
  26028. sip_ref_peer(peer, "adding poke peer ref"));
  26029. }
  26030. dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
  26031. return 0;
  26032. }
  26033. /*! \brief Part of PBX channel interface
  26034. \note
  26035. \par Return values:---
  26036. If we have qualify on and the device is not reachable, regardless of registration
  26037. state we return AST_DEVICE_UNAVAILABLE
  26038. For peers with call limit:
  26039. - not registered AST_DEVICE_UNAVAILABLE
  26040. - registered, no call AST_DEVICE_NOT_INUSE
  26041. - registered, active calls AST_DEVICE_INUSE
  26042. - registered, call limit reached AST_DEVICE_BUSY
  26043. - registered, onhold AST_DEVICE_ONHOLD
  26044. - registered, ringing AST_DEVICE_RINGING
  26045. For peers without call limit:
  26046. - not registered AST_DEVICE_UNAVAILABLE
  26047. - registered AST_DEVICE_NOT_INUSE
  26048. - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
  26049. Peers that does not have a known call and can't be reached by OPTIONS
  26050. - unreachable AST_DEVICE_UNAVAILABLE
  26051. If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
  26052. out a state by walking the channel list.
  26053. The queue system (\ref app_queue.c) treats a member as "active"
  26054. if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
  26055. When placing a call to the queue member, queue system sets a member to busy if
  26056. != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
  26057. */
  26058. static int sip_devicestate(const char *data)
  26059. {
  26060. char *host;
  26061. char *tmp;
  26062. struct sip_peer *p;
  26063. int res = AST_DEVICE_INVALID;
  26064. /* make sure data is not null. Maybe unnecessary, but better be safe */
  26065. host = ast_strdupa(data ? data : "");
  26066. if ((tmp = strchr(host, '@')))
  26067. host = tmp + 1;
  26068. ast_debug(3, "Checking device state for peer %s\n", host);
  26069. /* If sip_find_peer asks for a realtime peer, then this breaks rtautoclear. This
  26070. * is because when a peer tries to autoexpire, the last thing it does is to
  26071. * queue up an event telling the system that the devicestate has changed
  26072. * (presumably to unavailable). If we ask for a realtime peer here, this would
  26073. * load it BACK into memory, thus defeating the point of trying to clear dead
  26074. * hosts out of memory.
  26075. */
  26076. if ((p = sip_find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
  26077. if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
  26078. /* we have an address for the peer */
  26079. /* Check status in this order
  26080. - Hold
  26081. - Ringing
  26082. - Busy (enforced only by call limit)
  26083. - Inuse (we have a call)
  26084. - Unreachable (qualify)
  26085. If we don't find any of these state, report AST_DEVICE_NOT_INUSE
  26086. for registered devices */
  26087. if (p->onhold)
  26088. /* First check for hold or ring states */
  26089. res = AST_DEVICE_ONHOLD;
  26090. else if (p->ringing) {
  26091. if (p->ringing == p->inuse)
  26092. res = AST_DEVICE_RINGING;
  26093. else
  26094. res = AST_DEVICE_RINGINUSE;
  26095. } else if (p->call_limit && (p->inuse == p->call_limit))
  26096. /* check call limit */
  26097. res = AST_DEVICE_BUSY;
  26098. else if (p->call_limit && p->busy_level && p->inuse >= p->busy_level)
  26099. /* We're forcing busy before we've reached the call limit */
  26100. res = AST_DEVICE_BUSY;
  26101. else if (p->call_limit && p->inuse)
  26102. /* Not busy, but we do have a call */
  26103. res = AST_DEVICE_INUSE;
  26104. else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
  26105. /* We don't have a call. Are we reachable at all? Requires qualify= */
  26106. res = AST_DEVICE_UNAVAILABLE;
  26107. else /* Default reply if we're registered and have no other data */
  26108. res = AST_DEVICE_NOT_INUSE;
  26109. } else {
  26110. /* there is no address, it's unavailable */
  26111. res = AST_DEVICE_UNAVAILABLE;
  26112. }
  26113. sip_unref_peer(p, "sip_unref_peer, from sip_devicestate, release ref from sip_find_peer");
  26114. }
  26115. return res;
  26116. }
  26117. /*! \brief PBX interface function -build SIP pvt structure
  26118. * SIP calls initiated by the PBX arrive here.
  26119. *
  26120. * \verbatim
  26121. * SIP Dial string syntax:
  26122. * SIP/devicename
  26123. * or SIP/username@domain (SIP uri)
  26124. * or SIP/username[:password[:md5secret[:authname[:transport]]]]@host[:port]
  26125. * or SIP/devicename/extension
  26126. * or SIP/devicename/extension/IPorHost
  26127. * or SIP/username@domain//IPorHost
  26128. * and there is an optional [!dnid] argument you can append to alter the
  26129. * To: header.
  26130. * \endverbatim
  26131. */
  26132. static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest, int *cause)
  26133. {
  26134. struct sip_pvt *p;
  26135. struct ast_channel *tmpc = NULL;
  26136. char *ext = NULL, *host;
  26137. char tmp[256];
  26138. struct ast_str *codec_buf = ast_str_alloca(64);
  26139. struct ast_str *cap_buf = ast_str_alloca(64);
  26140. char *dnid;
  26141. char *secret = NULL;
  26142. char *md5secret = NULL;
  26143. char *authname = NULL;
  26144. char *trans = NULL;
  26145. char dialstring[256];
  26146. char *remote_address;
  26147. enum ast_transport transport = 0;
  26148. ast_callid callid;
  26149. AST_DECLARE_APP_ARGS(args,
  26150. AST_APP_ARG(peerorhost);
  26151. AST_APP_ARG(exten);
  26152. AST_APP_ARG(remote_address);
  26153. );
  26154. /* mask request with some set of allowed formats.
  26155. * XXX this needs to be fixed.
  26156. * The original code uses AST_FORMAT_AUDIO_MASK, but it is
  26157. * unclear what to use here. We have global_capabilities, which is
  26158. * configured from sip.conf, and sip_tech.capabilities, which is
  26159. * hardwired to all audio formats.
  26160. */
  26161. if (!(ast_format_cap_has_type(cap, AST_MEDIA_TYPE_AUDIO))) {
  26162. ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n",
  26163. ast_format_cap_get_names(cap, &codec_buf),
  26164. ast_format_cap_get_names(sip_cfg.caps, &cap_buf));
  26165. *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
  26166. return NULL;
  26167. }
  26168. ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_format_cap_get_names(cap, &codec_buf));
  26169. if (ast_strlen_zero(dest)) {
  26170. ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
  26171. *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
  26172. return NULL;
  26173. }
  26174. callid = ast_read_threadstorage_callid();
  26175. if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL, callid))) {
  26176. ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
  26177. *cause = AST_CAUSE_SWITCH_CONGESTION;
  26178. return NULL;
  26179. }
  26180. p->outgoing_call = TRUE;
  26181. snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
  26182. ast_string_field_set(p, dialstring, dialstring);
  26183. if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
  26184. dialog_unlink_all(p);
  26185. dialog_unref(p, "unref dialog p from mem fail");
  26186. /* sip_destroy(p); */
  26187. ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
  26188. *cause = AST_CAUSE_SWITCH_CONGESTION;
  26189. return NULL;
  26190. }
  26191. /* Save the destination, the SIP dial string */
  26192. ast_copy_string(tmp, dest, sizeof(tmp));
  26193. /* Find DNID and take it away */
  26194. dnid = strchr(tmp, '!');
  26195. if (dnid != NULL) {
  26196. *dnid++ = '\0';
  26197. ast_string_field_set(p, todnid, dnid);
  26198. }
  26199. /* Divvy up the items separated by slashes */
  26200. AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
  26201. /* Find at sign - @ */
  26202. host = strchr(args.peerorhost, '@');
  26203. if (host) {
  26204. *host++ = '\0';
  26205. ext = args.peerorhost;
  26206. secret = strchr(ext, ':');
  26207. }
  26208. if (secret) {
  26209. *secret++ = '\0';
  26210. md5secret = strchr(secret, ':');
  26211. }
  26212. if (md5secret) {
  26213. *md5secret++ = '\0';
  26214. authname = strchr(md5secret, ':');
  26215. }
  26216. if (authname) {
  26217. *authname++ = '\0';
  26218. trans = strchr(authname, ':');
  26219. }
  26220. if (trans) {
  26221. *trans++ = '\0';
  26222. if (!strcasecmp(trans, "tcp"))
  26223. transport = AST_TRANSPORT_TCP;
  26224. else if (!strcasecmp(trans, "tls"))
  26225. transport = AST_TRANSPORT_TLS;
  26226. else {
  26227. if (strcasecmp(trans, "udp"))
  26228. ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
  26229. transport = AST_TRANSPORT_UDP;
  26230. }
  26231. } else { /* use default */
  26232. transport = AST_TRANSPORT_UDP;
  26233. }
  26234. if (!host) {
  26235. ext = args.exten;
  26236. host = args.peerorhost;
  26237. remote_address = args.remote_address;
  26238. } else {
  26239. remote_address = args.remote_address;
  26240. if (!ast_strlen_zero(args.exten)) {
  26241. ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
  26242. }
  26243. }
  26244. if (!ast_strlen_zero(remote_address)) {
  26245. p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
  26246. if (!p->options->outboundproxy) {
  26247. ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
  26248. }
  26249. }
  26250. set_socket_transport(&p->socket, transport);
  26251. /* We now have
  26252. host = peer name, DNS host name or DNS domain (for SRV)
  26253. ext = extension (user part of URI)
  26254. dnid = destination of the call (applies to the To: header)
  26255. */
  26256. if (create_addr(p, host, NULL, 1)) {
  26257. *cause = AST_CAUSE_UNREGISTERED;
  26258. ast_debug(3, "Cant create SIP call - target device not registered\n");
  26259. dialog_unlink_all(p);
  26260. dialog_unref(p, "unref dialog p UNREGISTERED");
  26261. /* sip_destroy(p); */
  26262. return NULL;
  26263. }
  26264. if (ast_strlen_zero(p->peername) && ext)
  26265. ast_string_field_set(p, peername, ext);
  26266. /* Recalculate our side, and recalculate Call ID */
  26267. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  26268. /* When chan_sip is first loaded or reloaded, we need to check for NAT and set the appropiate flags
  26269. now that we have the auto_* settings. */
  26270. check_for_nat(&p->sa, p);
  26271. /* If there is a peer related to this outgoing call and it hasn't re-registered after
  26272. a reload, we need to set the peer's NAT flags accordingly. */
  26273. if (p->relatedpeer) {
  26274. if (!ast_strlen_zero(p->relatedpeer->fullcontact) && !p->natdetected &&
  26275. (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) && !ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT))) {
  26276. /* We need to make an attempt to determine if a peer is behind NAT
  26277. if the peer has the auto_force_rport flag set. */
  26278. struct ast_sockaddr tmpaddr;
  26279. __set_address_from_contact(p->relatedpeer->fullcontact, &tmpaddr, 0);
  26280. check_for_nat(&tmpaddr, p);
  26281. }
  26282. set_peer_nat(p, p->relatedpeer);
  26283. }
  26284. do_setnat(p);
  26285. build_via(p);
  26286. /* Change the dialog callid. */
  26287. change_callid_pvt(p, NULL);
  26288. /* We have an extension to call, don't use the full contact here */
  26289. /* This to enable dialing registered peers with extension dialling,
  26290. like SIP/peername/extension
  26291. SIP/peername will still use the full contact
  26292. */
  26293. if (ext) {
  26294. ast_string_field_set(p, username, ext);
  26295. ast_string_field_set(p, fullcontact, NULL);
  26296. }
  26297. if (secret && !ast_strlen_zero(secret))
  26298. ast_string_field_set(p, peersecret, secret);
  26299. if (md5secret && !ast_strlen_zero(md5secret))
  26300. ast_string_field_set(p, peermd5secret, md5secret);
  26301. if (authname && !ast_strlen_zero(authname))
  26302. ast_string_field_set(p, authname, authname);
  26303. #if 0
  26304. printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
  26305. #endif
  26306. ast_format_cap_append_from_cap(p->prefcaps, cap, AST_MEDIA_TYPE_UNKNOWN);
  26307. ast_format_cap_get_compatible(cap, p->caps, p->jointcaps);
  26308. sip_pvt_lock(p);
  26309. tmpc = sip_new(p, AST_STATE_DOWN, host, assignedids, requestor, callid); /* Place the call */
  26310. sip_pvt_unlock(p);
  26311. if (!tmpc) {
  26312. dialog_unlink_all(p);
  26313. /* sip_destroy(p); */
  26314. } else {
  26315. ast_channel_unlock(tmpc);
  26316. }
  26317. dialog_unref(p, "toss pvt ptr at end of sip_request_call");
  26318. ast_update_use_count();
  26319. restart_monitor();
  26320. return tmpc;
  26321. }
  26322. /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
  26323. static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
  26324. {
  26325. if (ast_strlen_zero(value))
  26326. return;
  26327. if (!ast_false(value)) {
  26328. char buf[64];
  26329. char *word, *next;
  26330. ast_copy_string(buf, value, sizeof(buf));
  26331. next = buf;
  26332. while ((word = strsep(&next, ","))) {
  26333. if (!strcasecmp(word, "port"))
  26334. ast_set_flag(&flags[0], SIP_INSECURE_PORT);
  26335. else if (!strcasecmp(word, "invite"))
  26336. ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
  26337. else
  26338. ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
  26339. }
  26340. }
  26341. }
  26342. /*!
  26343. \brief Handle T.38 configuration options common to users and peers
  26344. \returns non-zero if any config options were handled, zero otherwise
  26345. */
  26346. static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
  26347. unsigned int *maxdatagram)
  26348. {
  26349. int res = 1;
  26350. if (!strcasecmp(v->name, "t38pt_udptl")) {
  26351. char *buf = ast_strdupa(v->value);
  26352. char *word, *next = buf;
  26353. ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
  26354. while ((word = strsep(&next, ","))) {
  26355. if (ast_true(word) || !strcasecmp(word, "fec")) {
  26356. ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
  26357. ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
  26358. } else if (!strcasecmp(word, "redundancy")) {
  26359. ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
  26360. ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
  26361. } else if (!strcasecmp(word, "none")) {
  26362. ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
  26363. ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
  26364. } else if (!strncasecmp(word, "maxdatagram=", 12)) {
  26365. if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
  26366. ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
  26367. *maxdatagram = global_t38_maxdatagram;
  26368. }
  26369. }
  26370. }
  26371. } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
  26372. ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
  26373. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
  26374. } else {
  26375. res = 0;
  26376. }
  26377. return res;
  26378. }
  26379. /*!
  26380. \brief Handle flag-type options common to configuration of devices - peers
  26381. \param flags array of three struct ast_flags
  26382. \param mask array of three struct ast_flags
  26383. \param v linked list of config variables to process
  26384. \returns non-zero if any config options were handled, zero otherwise
  26385. */
  26386. static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
  26387. {
  26388. int res = 1;
  26389. if (!strcasecmp(v->name, "trustrpid")) {
  26390. ast_set_flag(&mask[0], SIP_TRUSTRPID);
  26391. ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
  26392. } else if (!strcasecmp(v->name, "supportpath")) {
  26393. ast_set_flag(&mask[0], SIP_USEPATH);
  26394. ast_set2_flag(&flags[0], ast_true(v->value), SIP_USEPATH);
  26395. } else if (!strcasecmp(v->name, "sendrpid")) {
  26396. ast_set_flag(&mask[0], SIP_SENDRPID);
  26397. if (!strcasecmp(v->value, "pai")) {
  26398. ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
  26399. } else if (!strcasecmp(v->value, "rpid")) {
  26400. ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
  26401. } else if (ast_true(v->value)) {
  26402. ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
  26403. }
  26404. } else if (!strcasecmp(v->name, "rpid_update")) {
  26405. ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
  26406. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
  26407. } else if (!strcasecmp(v->name, "rpid_immediate")) {
  26408. ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
  26409. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
  26410. } else if (!strcasecmp(v->name, "trust_id_outbound")) {
  26411. ast_set_flag(&mask[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
  26412. ast_clear_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
  26413. if (!strcasecmp(v->value, "legacy")) {
  26414. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
  26415. } else if (ast_true(v->value)) {
  26416. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_YES);
  26417. } else if (ast_false(v->value)) {
  26418. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_NO);
  26419. } else {
  26420. ast_log(LOG_WARNING, "Unknown trust_id_outbound mode '%s' on line %d, using legacy\n", v->value, v->lineno);
  26421. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
  26422. }
  26423. } else if (!strcasecmp(v->name, "g726nonstandard")) {
  26424. ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
  26425. ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
  26426. } else if (!strcasecmp(v->name, "useclientcode")) {
  26427. ast_set_flag(&mask[0], SIP_USECLIENTCODE);
  26428. ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
  26429. } else if (!strcasecmp(v->name, "dtmfmode")) {
  26430. ast_set_flag(&mask[0], SIP_DTMF);
  26431. ast_clear_flag(&flags[0], SIP_DTMF);
  26432. if (!strcasecmp(v->value, "inband"))
  26433. ast_set_flag(&flags[0], SIP_DTMF_INBAND);
  26434. else if (!strcasecmp(v->value, "rfc2833"))
  26435. ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
  26436. else if (!strcasecmp(v->value, "info"))
  26437. ast_set_flag(&flags[0], SIP_DTMF_INFO);
  26438. else if (!strcasecmp(v->value, "shortinfo"))
  26439. ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
  26440. else if (!strcasecmp(v->value, "auto"))
  26441. ast_set_flag(&flags[0], SIP_DTMF_AUTO);
  26442. else {
  26443. ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
  26444. ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
  26445. }
  26446. } else if (!strcasecmp(v->name, "nat")) {
  26447. sip_parse_nat_option(v->value, mask, flags);
  26448. } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
  26449. ast_set_flag(&mask[0], SIP_REINVITE);
  26450. ast_clear_flag(&flags[0], SIP_REINVITE);
  26451. if (ast_true(v->value)) {
  26452. ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
  26453. } else if (!ast_false(v->value)) {
  26454. char buf[64];
  26455. char *word, *next = buf;
  26456. ast_copy_string(buf, v->value, sizeof(buf));
  26457. while ((word = strsep(&next, ","))) {
  26458. if (!strcasecmp(word, "update")) {
  26459. ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
  26460. } else if (!strcasecmp(word, "nonat")) {
  26461. ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
  26462. ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
  26463. } else if (!strcasecmp(word, "outgoing")) {
  26464. ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
  26465. ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
  26466. ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
  26467. } else {
  26468. ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
  26469. }
  26470. }
  26471. }
  26472. } else if (!strcasecmp(v->name, "insecure")) {
  26473. ast_set_flag(&mask[0], SIP_INSECURE);
  26474. ast_clear_flag(&flags[0], SIP_INSECURE);
  26475. set_insecure_flags(&flags[0], v->value, v->lineno);
  26476. } else if (!strcasecmp(v->name, "progressinband")) {
  26477. ast_set_flag(&mask[0], SIP_PROG_INBAND);
  26478. ast_clear_flag(&flags[0], SIP_PROG_INBAND);
  26479. if (ast_true(v->value))
  26480. ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
  26481. else if (!strcasecmp(v->value, "never"))
  26482. ast_set_flag(&flags[0], SIP_PROG_INBAND_NEVER);
  26483. } else if (!strcasecmp(v->name, "promiscredir")) {
  26484. ast_set_flag(&mask[0], SIP_PROMISCREDIR);
  26485. ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
  26486. } else if (!strcasecmp(v->name, "videosupport")) {
  26487. if (!strcasecmp(v->value, "always")) {
  26488. ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
  26489. ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
  26490. } else {
  26491. ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
  26492. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
  26493. }
  26494. } else if (!strcasecmp(v->name, "textsupport")) {
  26495. ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
  26496. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
  26497. res = 1;
  26498. } else if (!strcasecmp(v->name, "allowoverlap")) {
  26499. ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
  26500. ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
  26501. if (ast_true(v->value)) {
  26502. ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
  26503. } else if (!strcasecmp(v->value, "dtmf")){
  26504. ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
  26505. }
  26506. } else if (!strcasecmp(v->name, "allowsubscribe")) {
  26507. ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
  26508. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
  26509. } else if (!strcasecmp(v->name, "ignoresdpversion")) {
  26510. ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
  26511. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
  26512. } else if (!strcasecmp(v->name, "faxdetect")) {
  26513. ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
  26514. if (ast_true(v->value)) {
  26515. ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
  26516. } else if (ast_false(v->value)) {
  26517. ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
  26518. } else {
  26519. char *buf = ast_strdupa(v->value);
  26520. char *word, *next = buf;
  26521. while ((word = strsep(&next, ","))) {
  26522. if (!strcasecmp(word, "cng")) {
  26523. ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
  26524. } else if (!strcasecmp(word, "t38")) {
  26525. ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
  26526. } else {
  26527. ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
  26528. }
  26529. }
  26530. }
  26531. } else if (!strcasecmp(v->name, "rfc2833compensate")) {
  26532. ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
  26533. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
  26534. } else if (!strcasecmp(v->name, "buggymwi")) {
  26535. ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
  26536. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
  26537. } else
  26538. res = 0;
  26539. return res;
  26540. }
  26541. /*! \brief Add SIP domain to list of domains we are responsible for */
  26542. static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
  26543. {
  26544. struct domain *d;
  26545. if (ast_strlen_zero(domain)) {
  26546. ast_log(LOG_WARNING, "Zero length domain.\n");
  26547. return 1;
  26548. }
  26549. if (!(d = ast_calloc(1, sizeof(*d))))
  26550. return 0;
  26551. ast_copy_string(d->domain, domain, sizeof(d->domain));
  26552. if (!ast_strlen_zero(context))
  26553. ast_copy_string(d->context, context, sizeof(d->context));
  26554. d->mode = mode;
  26555. AST_LIST_LOCK(&domain_list);
  26556. AST_LIST_INSERT_TAIL(&domain_list, d, list);
  26557. AST_LIST_UNLOCK(&domain_list);
  26558. if (sipdebug)
  26559. ast_debug(1, "Added local SIP domain '%s'\n", domain);
  26560. return 1;
  26561. }
  26562. /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
  26563. static int check_sip_domain(const char *domain, char *context, size_t len)
  26564. {
  26565. struct domain *d;
  26566. int result = 0;
  26567. AST_LIST_LOCK(&domain_list);
  26568. AST_LIST_TRAVERSE(&domain_list, d, list) {
  26569. if (strcasecmp(d->domain, domain)) {
  26570. continue;
  26571. }
  26572. if (len && !ast_strlen_zero(d->context))
  26573. ast_copy_string(context, d->context, len);
  26574. result = 1;
  26575. break;
  26576. }
  26577. AST_LIST_UNLOCK(&domain_list);
  26578. return result;
  26579. }
  26580. /*! \brief Clear our domain list (at reload) */
  26581. static void clear_sip_domains(void)
  26582. {
  26583. struct domain *d;
  26584. AST_LIST_LOCK(&domain_list);
  26585. while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
  26586. ast_free(d);
  26587. AST_LIST_UNLOCK(&domain_list);
  26588. }
  26589. /*!
  26590. * \internal
  26591. * \brief Realm authentication container destructor.
  26592. *
  26593. * \param obj Container object to destroy.
  26594. *
  26595. * \return Nothing
  26596. */
  26597. static void destroy_realm_authentication(void *obj)
  26598. {
  26599. struct sip_auth_container *credentials = obj;
  26600. struct sip_auth *auth;
  26601. while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
  26602. ast_free(auth);
  26603. }
  26604. }
  26605. /*!
  26606. * \internal
  26607. * \brief Add realm authentication to credentials.
  26608. *
  26609. * \param credentials Realm authentication container to create/add authentication credentials.
  26610. * \param configuration Credential configuration value.
  26611. * \param lineno Line number in config file.
  26612. *
  26613. * \return Nothing
  26614. */
  26615. static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
  26616. {
  26617. char *authcopy;
  26618. char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
  26619. struct sip_auth *auth;
  26620. if (ast_strlen_zero(configuration)) {
  26621. /* Nothing to add */
  26622. return;
  26623. }
  26624. ast_debug(1, "Auth config :: %s\n", configuration);
  26625. authcopy = ast_strdupa(configuration);
  26626. username = authcopy;
  26627. /* split user[:secret] and relm */
  26628. realm = strrchr(username, '@');
  26629. if (realm)
  26630. *realm++ = '\0';
  26631. if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
  26632. ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
  26633. return;
  26634. }
  26635. /* parse username at ':' for secret, or '#" for md5secret */
  26636. if ((secret = strchr(username, ':'))) {
  26637. *secret++ = '\0';
  26638. } else if ((md5secret = strchr(username, '#'))) {
  26639. *md5secret++ = '\0';
  26640. }
  26641. /* Create the continer if needed. */
  26642. if (!*credentials) {
  26643. *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
  26644. "Create realm auth container.");
  26645. if (!*credentials) {
  26646. /* Failed to create the credentials container. */
  26647. return;
  26648. }
  26649. }
  26650. /* Create the authentication credential entry. */
  26651. auth = ast_calloc(1, sizeof(*auth));
  26652. if (!auth) {
  26653. return;
  26654. }
  26655. ast_copy_string(auth->realm, realm, sizeof(auth->realm));
  26656. ast_copy_string(auth->username, username, sizeof(auth->username));
  26657. if (secret)
  26658. ast_copy_string(auth->secret, secret, sizeof(auth->secret));
  26659. if (md5secret)
  26660. ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
  26661. /* Add credential to container list. */
  26662. AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
  26663. ast_verb(3, "Added authentication for realm %s\n", realm);
  26664. }
  26665. /*!
  26666. * \internal
  26667. * \brief Find authentication for a specific realm.
  26668. *
  26669. * \param credentials Realm authentication container to search.
  26670. * \param realm Authentication realm to find.
  26671. *
  26672. * \return Found authentication credential or NULL.
  26673. */
  26674. static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
  26675. {
  26676. struct sip_auth *auth;
  26677. if (credentials) {
  26678. AST_LIST_TRAVERSE(&credentials->list, auth, node) {
  26679. if (!strcasecmp(auth->realm, realm)) {
  26680. break;
  26681. }
  26682. }
  26683. } else {
  26684. auth = NULL;
  26685. }
  26686. return auth;
  26687. }
  26688. /*! \brief
  26689. * implement the setvar config line
  26690. */
  26691. static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
  26692. {
  26693. struct ast_variable *tmpvar = NULL;
  26694. char *varname = ast_strdupa(buf), *varval = NULL;
  26695. if ((varval = strchr(varname, '='))) {
  26696. *varval++ = '\0';
  26697. if ((tmpvar = ast_variable_new(varname, varval, ""))) {
  26698. tmpvar->next = list;
  26699. list = tmpvar;
  26700. }
  26701. }
  26702. return list;
  26703. }
  26704. /*! \brief Set peer defaults before configuring specific configurations */
  26705. static void set_peer_defaults(struct sip_peer *peer)
  26706. {
  26707. if (peer->expire == 0) {
  26708. /* Don't reset expire or port time during reload
  26709. if we have an active registration
  26710. */
  26711. peer->expire = -1;
  26712. peer->pokeexpire = -1;
  26713. peer->keepalivesend = -1;
  26714. set_socket_transport(&peer->socket, AST_TRANSPORT_UDP);
  26715. }
  26716. peer->type = SIP_TYPE_PEER;
  26717. ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
  26718. ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  26719. ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  26720. ast_string_field_set(peer, context, sip_cfg.default_context);
  26721. ast_string_field_set(peer, record_on_feature, sip_cfg.default_record_on_feature);
  26722. ast_string_field_set(peer, record_off_feature, sip_cfg.default_record_off_feature);
  26723. ast_string_field_set(peer, messagecontext, sip_cfg.messagecontext);
  26724. ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
  26725. ast_string_field_set(peer, language, default_language);
  26726. ast_string_field_set(peer, mohinterpret, default_mohinterpret);
  26727. ast_string_field_set(peer, mohsuggest, default_mohsuggest);
  26728. ast_string_field_set(peer, engine, default_engine);
  26729. ast_sockaddr_setnull(&peer->addr);
  26730. ast_sockaddr_setnull(&peer->defaddr);
  26731. ast_format_cap_append_from_cap(peer->caps, sip_cfg.caps, AST_MEDIA_TYPE_UNKNOWN);
  26732. peer->maxcallbitrate = default_maxcallbitrate;
  26733. peer->rtptimeout = global_rtptimeout;
  26734. peer->rtpholdtimeout = global_rtpholdtimeout;
  26735. peer->rtpkeepalive = global_rtpkeepalive;
  26736. peer->allowtransfer = sip_cfg.allowtransfer;
  26737. peer->autoframing = global_autoframing;
  26738. peer->t38_maxdatagram = global_t38_maxdatagram;
  26739. peer->qualifyfreq = global_qualifyfreq;
  26740. if (global_callcounter)
  26741. peer->call_limit=INT_MAX;
  26742. ast_string_field_set(peer, vmexten, default_vmexten);
  26743. ast_string_field_set(peer, secret, "");
  26744. ast_string_field_set(peer, description, "");
  26745. ast_string_field_set(peer, remotesecret, "");
  26746. ast_string_field_set(peer, md5secret, "");
  26747. ast_string_field_set(peer, cid_num, "");
  26748. ast_string_field_set(peer, cid_name, "");
  26749. ast_string_field_set(peer, cid_tag, "");
  26750. ast_string_field_set(peer, fromdomain, "");
  26751. ast_string_field_set(peer, fromuser, "");
  26752. ast_string_field_set(peer, regexten, "");
  26753. peer->callgroup = 0;
  26754. peer->pickupgroup = 0;
  26755. peer->maxms = default_qualify;
  26756. peer->keepalive = default_keepalive;
  26757. ast_string_field_set(peer, zone, default_zone);
  26758. peer->stimer.st_mode_oper = global_st_mode; /* Session-Timers */
  26759. peer->stimer.st_ref = global_st_refresher;
  26760. peer->stimer.st_min_se = global_min_se;
  26761. peer->stimer.st_max_se = global_max_se;
  26762. peer->timer_t1 = global_t1;
  26763. peer->timer_b = global_timer_b;
  26764. clear_peer_mailboxes(peer);
  26765. peer->disallowed_methods = sip_cfg.disallowed_methods;
  26766. peer->transports = default_transports;
  26767. peer->default_outbound_transport = default_primary_transport;
  26768. if (peer->outboundproxy) {
  26769. ao2_ref(peer->outboundproxy, -1);
  26770. peer->outboundproxy = NULL;
  26771. }
  26772. }
  26773. /*! \brief Create temporary peer (used in autocreatepeer mode) */
  26774. static struct sip_peer *temp_peer(const char *name)
  26775. {
  26776. struct sip_peer *peer;
  26777. if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
  26778. return NULL;
  26779. if (ast_string_field_init(peer, 512)) {
  26780. ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
  26781. return NULL;
  26782. }
  26783. if (!(peer->cc_params = ast_cc_config_params_init())) {
  26784. ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
  26785. return NULL;
  26786. }
  26787. if (!(peer->caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  26788. ao2_t_ref(peer, -1, "failed to allocate format capabilities, drop peer");
  26789. return NULL;
  26790. }
  26791. ast_atomic_fetchadd_int(&apeerobjs, 1);
  26792. set_peer_defaults(peer);
  26793. ast_copy_string(peer->name, name, sizeof(peer->name));
  26794. peer->selfdestruct = TRUE;
  26795. peer->host_dynamic = TRUE;
  26796. reg_source_db(peer);
  26797. return peer;
  26798. }
  26799. /*! \todo document this function */
  26800. static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
  26801. {
  26802. char *next;
  26803. char *mbox;
  26804. next = ast_strdupa(value);
  26805. while ((mbox = strsep(&next, ","))) {
  26806. struct sip_mailbox *mailbox;
  26807. int duplicate = 0;
  26808. /* remove leading/trailing whitespace from mailbox string */
  26809. mbox = ast_strip(mbox);
  26810. if (ast_strlen_zero(mbox)) {
  26811. continue;
  26812. }
  26813. /* Check whether the mailbox is already in the list */
  26814. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  26815. if (!strcmp(mailbox->id, mbox)) {
  26816. duplicate = 1;
  26817. break;
  26818. }
  26819. }
  26820. if (duplicate) {
  26821. continue;
  26822. }
  26823. mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox));
  26824. if (!mailbox) {
  26825. continue;
  26826. }
  26827. strcpy(mailbox->id, mbox); /* SAFE */
  26828. AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
  26829. }
  26830. }
  26831. /*! \brief Build peer from configuration (file or realtime static/dynamic) */
  26832. static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
  26833. {
  26834. struct sip_peer *peer = NULL;
  26835. struct ast_acl_list *oldacl = NULL;
  26836. struct ast_acl_list *olddirectmediaacl = NULL;
  26837. int found = 0;
  26838. int firstpass = 1;
  26839. uint16_t port = 0;
  26840. int format = 0; /* Ama flags */
  26841. int timerb_set = 0, timert1_set = 0;
  26842. time_t regseconds = 0;
  26843. struct ast_flags peerflags[3] = {{(0)}};
  26844. struct ast_flags mask[3] = {{(0)}};
  26845. struct sip_peer tmp_peer;
  26846. const char *srvlookup = NULL;
  26847. static int deprecation_warning = 1;
  26848. int alt_fullcontact = alt ? 1 : 0, headercount = 0;
  26849. struct ast_str *fullcontact = ast_str_alloca(512);
  26850. int acl_change_subscription_needed = 0;
  26851. if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  26852. /* Note we do NOT use sip_find_peer here, to avoid realtime recursion */
  26853. /* We also use a case-sensitive comparison (unlike sip_find_peer) so
  26854. that case changes made to the peer name will be properly handled
  26855. during reload
  26856. */
  26857. ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
  26858. peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
  26859. }
  26860. if (peer) {
  26861. /* Already in the list, remove it and it will be added back (or FREE'd) */
  26862. found++;
  26863. /* we've unlinked the peer from the peers container but not unlinked from the peers_by_ip container yet
  26864. this leads to a wrong refcounter and the peer object is never destroyed */
  26865. if (!ast_sockaddr_isnull(&peer->addr)) {
  26866. ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
  26867. }
  26868. if (!(peer->the_mark))
  26869. firstpass = 0;
  26870. } else {
  26871. if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct"))) {
  26872. return NULL;
  26873. }
  26874. if (!(peer->endpoint = ast_endpoint_create("SIP", name))) {
  26875. return NULL;
  26876. }
  26877. if (!(peer->caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  26878. ao2_t_ref(peer, -1, "failed to allocate format capabilities, drop peer");
  26879. return NULL;
  26880. }
  26881. if (ast_string_field_init(peer, 512)) {
  26882. ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
  26883. return NULL;
  26884. }
  26885. if (!(peer->cc_params = ast_cc_config_params_init())) {
  26886. ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
  26887. return NULL;
  26888. }
  26889. if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  26890. ast_atomic_fetchadd_int(&rpeerobjs, 1);
  26891. ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
  26892. } else
  26893. ast_atomic_fetchadd_int(&speerobjs, 1);
  26894. }
  26895. /* Note that our peer HAS had its reference count increased */
  26896. if (firstpass) {
  26897. oldacl = peer->acl;
  26898. peer->acl = NULL;
  26899. olddirectmediaacl = peer->directmediaacl;
  26900. peer->directmediaacl = NULL;
  26901. set_peer_defaults(peer); /* Set peer defaults */
  26902. peer->type = 0;
  26903. }
  26904. /* in case the case of the peer name has changed, update the name */
  26905. ast_copy_string(peer->name, name, sizeof(peer->name));
  26906. /* If we have channel variables, remove them (reload) */
  26907. if (peer->chanvars) {
  26908. ast_variables_destroy(peer->chanvars);
  26909. peer->chanvars = NULL;
  26910. /* XXX should unregister ? */
  26911. }
  26912. if (found)
  26913. peer->portinuri = 0;
  26914. /* If we have realm authentication information, remove them (reload) */
  26915. ao2_lock(peer);
  26916. if (peer->auth) {
  26917. ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
  26918. peer->auth = NULL;
  26919. }
  26920. ao2_unlock(peer);
  26921. /* clear the transport information. We will detect if a default value is required after parsing the config */
  26922. peer->default_outbound_transport = 0;
  26923. peer->transports = 0;
  26924. if (!devstate_only) {
  26925. struct sip_mailbox *mailbox;
  26926. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  26927. mailbox->delme = 1;
  26928. }
  26929. }
  26930. /* clear named callgroup and named pickup group container */
  26931. peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
  26932. peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
  26933. /* Set the default DTLS settings from default_tls_cfg */
  26934. ast_rtp_dtls_cfg_free(&peer->dtls_cfg);
  26935. ast_rtp_dtls_cfg_copy(&default_dtls_cfg, &peer->dtls_cfg);
  26936. peer->dtls_cfg.enabled = FALSE;
  26937. for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
  26938. if (!devstate_only) {
  26939. if (handle_common_options(&peerflags[0], &mask[0], v)) {
  26940. continue;
  26941. }
  26942. if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
  26943. continue;
  26944. }
  26945. if (!strcasecmp(v->name, "transport")) {
  26946. char *val = ast_strdupa(v->value);
  26947. char *trans;
  26948. peer->transports = peer->default_outbound_transport = 0;
  26949. while ((trans = strsep(&val, ","))) {
  26950. trans = ast_skip_blanks(trans);
  26951. if (!strncasecmp(trans, "udp", 3)) {
  26952. peer->transports |= AST_TRANSPORT_UDP;
  26953. } else if (!strncasecmp(trans, "wss", 3)) {
  26954. peer->transports |= AST_TRANSPORT_WSS;
  26955. } else if (!strncasecmp(trans, "ws", 2)) {
  26956. peer->transports |= AST_TRANSPORT_WS;
  26957. } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
  26958. peer->transports |= AST_TRANSPORT_TCP;
  26959. } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
  26960. peer->transports |= AST_TRANSPORT_TLS;
  26961. } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
  26962. ast_log(LOG_WARNING, "'%.3s' is not a valid transport type when %.3senable=no. If no other is specified, the defaults from general will be used.\n", trans, trans);
  26963. } else {
  26964. ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, the defaults from general will be used.\n", trans);
  26965. }
  26966. if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
  26967. peer->default_outbound_transport = peer->transports;
  26968. }
  26969. }
  26970. } else if (realtime && !strcasecmp(v->name, "regseconds")) {
  26971. ast_get_time_t(v->value, &regseconds, 0, NULL);
  26972. } else if (realtime && !strcasecmp(v->name, "name")) {
  26973. ast_copy_string(peer->name, v->value, sizeof(peer->name));
  26974. } else if (realtime && !strcasecmp(v->name, "useragent")) {
  26975. ast_string_field_set(peer, useragent, v->value);
  26976. } else if (!strcasecmp(v->name, "type")) {
  26977. if (!strcasecmp(v->value, "peer")) {
  26978. peer->type |= SIP_TYPE_PEER;
  26979. } else if (!strcasecmp(v->value, "user")) {
  26980. peer->type |= SIP_TYPE_USER;
  26981. } else if (!strcasecmp(v->value, "friend")) {
  26982. peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
  26983. }
  26984. } else if (!strcasecmp(v->name, "remotesecret")) {
  26985. ast_string_field_set(peer, remotesecret, v->value);
  26986. } else if (!strcasecmp(v->name, "secret")) {
  26987. ast_string_field_set(peer, secret, v->value);
  26988. } else if (!strcasecmp(v->name, "description")) {
  26989. ast_string_field_set(peer, description, v->value);
  26990. } else if (!strcasecmp(v->name, "md5secret")) {
  26991. ast_string_field_set(peer, md5secret, v->value);
  26992. } else if (!strcasecmp(v->name, "auth")) {
  26993. add_realm_authentication(&peer->auth, v->value, v->lineno);
  26994. } else if (!strcasecmp(v->name, "callerid")) {
  26995. char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
  26996. ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
  26997. ast_string_field_set(peer, cid_name, cid_name);
  26998. ast_string_field_set(peer, cid_num, cid_num);
  26999. } else if (!strcasecmp(v->name, "mwi_from")) {
  27000. ast_string_field_set(peer, mwi_from, v->value);
  27001. } else if (!strcasecmp(v->name, "fullname")) {
  27002. ast_string_field_set(peer, cid_name, v->value);
  27003. } else if (!strcasecmp(v->name, "trunkname")) {
  27004. /* This is actually for a trunk, so we don't want to override callerid */
  27005. ast_string_field_set(peer, cid_name, "");
  27006. } else if (!strcasecmp(v->name, "cid_number")) {
  27007. ast_string_field_set(peer, cid_num, v->value);
  27008. } else if (!strcasecmp(v->name, "cid_tag")) {
  27009. ast_string_field_set(peer, cid_tag, v->value);
  27010. } else if (!strcasecmp(v->name, "context")) {
  27011. ast_string_field_set(peer, context, v->value);
  27012. ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
  27013. } else if (!strcasecmp(v->name, "recordonfeature")) {
  27014. ast_string_field_set(peer, record_on_feature, v->value);
  27015. } else if (!strcasecmp(v->name, "recordofffeature")) {
  27016. ast_string_field_set(peer, record_off_feature, v->value);
  27017. } else if (!strcasecmp(v->name, "outofcall_message_context")) {
  27018. ast_string_field_set(peer, messagecontext, v->value);
  27019. } else if (!strcasecmp(v->name, "subscribecontext")) {
  27020. ast_string_field_set(peer, subscribecontext, v->value);
  27021. } else if (!strcasecmp(v->name, "fromdomain")) {
  27022. char *fromdomainport;
  27023. ast_string_field_set(peer, fromdomain, v->value);
  27024. if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
  27025. *fromdomainport++ = '\0';
  27026. if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
  27027. ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
  27028. }
  27029. } else {
  27030. peer->fromdomainport = STANDARD_SIP_PORT;
  27031. }
  27032. } else if (!strcasecmp(v->name, "usereqphone")) {
  27033. ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
  27034. } else if (!strcasecmp(v->name, "fromuser")) {
  27035. ast_string_field_set(peer, fromuser, v->value);
  27036. } else if (!strcasecmp(v->name, "outboundproxy")) {
  27037. struct sip_proxy *proxy;
  27038. if (ast_strlen_zero(v->value)) {
  27039. ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
  27040. continue;
  27041. }
  27042. proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
  27043. if (!proxy) {
  27044. ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
  27045. continue;
  27046. }
  27047. peer->outboundproxy = proxy;
  27048. } else if (!strcasecmp(v->name, "host")) {
  27049. if (!strcasecmp(v->value, "dynamic")) {
  27050. /* They'll register with us */
  27051. if ((!found && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) || !peer->host_dynamic) {
  27052. /* Initialize stuff if this is a new peer, or if it used to
  27053. * not be dynamic before the reload. */
  27054. ast_sockaddr_setnull(&peer->addr);
  27055. }
  27056. peer->host_dynamic = TRUE;
  27057. } else {
  27058. /* Non-dynamic. Make sure we become that way if we're not */
  27059. AST_SCHED_DEL_UNREF(sched, peer->expire,
  27060. sip_unref_peer(peer, "removing register expire ref"));
  27061. peer->host_dynamic = FALSE;
  27062. srvlookup = v->value;
  27063. }
  27064. } else if (!strcasecmp(v->name, "defaultip")) {
  27065. peer->defaddr.ss.ss_family = AST_AF_UNSPEC;
  27066. if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
  27067. sip_unref_peer(peer, "sip_unref_peer: from build_peer defaultip");
  27068. return NULL;
  27069. }
  27070. } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny") || !strcasecmp(v->name, "acl")) {
  27071. int ha_error = 0;
  27072. if (!ast_strlen_zero(v->value)) {
  27073. ast_append_acl(v->name, v->value, &peer->acl, &ha_error, &acl_change_subscription_needed);
  27074. }
  27075. if (ha_error) {
  27076. ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  27077. }
  27078. } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny") || !strcasecmp(v->name, "contactacl")) {
  27079. int ha_error = 0;
  27080. if (!ast_strlen_zero(v->value)) {
  27081. ast_append_acl(v->name + 7, v->value, &peer->contactacl, &ha_error, &acl_change_subscription_needed);
  27082. }
  27083. if (ha_error) {
  27084. ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  27085. }
  27086. } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny") || !strcasecmp(v->name, "directmediaacl")) {
  27087. int ha_error = 0;
  27088. ast_append_acl(v->name + 11, v->value, &peer->directmediaacl, &ha_error, &acl_change_subscription_needed);
  27089. if (ha_error) {
  27090. ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  27091. }
  27092. } else if (!strcasecmp(v->name, "port")) {
  27093. peer->portinuri = 1;
  27094. if (!(port = port_str2int(v->value, 0))) {
  27095. if (realtime) {
  27096. /* If stored as integer, could be 0 for some DBs (notably MySQL) */
  27097. peer->portinuri = 0;
  27098. } else {
  27099. ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
  27100. }
  27101. }
  27102. } else if (!strcasecmp(v->name, "callingpres")) {
  27103. peer->callingpres = ast_parse_caller_presentation(v->value);
  27104. if (peer->callingpres == -1) {
  27105. peer->callingpres = atoi(v->value);
  27106. }
  27107. } else if (!strcasecmp(v->name, "username") || !strcasecmp(v->name, "defaultuser")) { /* "username" is deprecated */
  27108. ast_string_field_set(peer, username, v->value);
  27109. if (!strcasecmp(v->name, "username")) {
  27110. if (deprecation_warning) {
  27111. ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
  27112. deprecation_warning = 0;
  27113. }
  27114. peer->deprecated_username = 1;
  27115. }
  27116. } else if (!strcasecmp(v->name, "tonezone")) {
  27117. struct ast_tone_zone *new_zone;
  27118. if (!(new_zone = ast_get_indication_zone(v->value))) {
  27119. ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone in device [%s] at line %d. Check indications.conf for available country codes.\n", v->value, peer->name, v->lineno);
  27120. } else {
  27121. ast_tone_zone_unref(new_zone);
  27122. ast_string_field_set(peer, zone, v->value);
  27123. }
  27124. } else if (!strcasecmp(v->name, "language")) {
  27125. ast_string_field_set(peer, language, v->value);
  27126. } else if (!strcasecmp(v->name, "regexten")) {
  27127. ast_string_field_set(peer, regexten, v->value);
  27128. } else if (!strcasecmp(v->name, "callbackextension")) {
  27129. ast_string_field_set(peer, callback, v->value);
  27130. } else if (!strcasecmp(v->name, "amaflags")) {
  27131. format = ast_channel_string2amaflag(v->value);
  27132. if (format < 0) {
  27133. ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
  27134. } else {
  27135. peer->amaflags = format;
  27136. }
  27137. } else if (!strcasecmp(v->name, "maxforwards")) {
  27138. if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
  27139. || peer->maxforwards < 1 || 255 < peer->maxforwards) {
  27140. ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
  27141. peer->maxforwards = sip_cfg.default_max_forwards;
  27142. }
  27143. } else if (!strcasecmp(v->name, "accountcode")) {
  27144. ast_string_field_set(peer, accountcode, v->value);
  27145. } else if (!strcasecmp(v->name, "mohinterpret")) {
  27146. ast_string_field_set(peer, mohinterpret, v->value);
  27147. } else if (!strcasecmp(v->name, "mohsuggest")) {
  27148. ast_string_field_set(peer, mohsuggest, v->value);
  27149. } else if (!strcasecmp(v->name, "parkinglot")) {
  27150. ast_string_field_set(peer, parkinglot, v->value);
  27151. } else if (!strcasecmp(v->name, "rtp_engine")) {
  27152. ast_string_field_set(peer, engine, v->value);
  27153. } else if (!strcasecmp(v->name, "mailbox")) {
  27154. add_peer_mailboxes(peer, v->value);
  27155. } else if (!strcasecmp(v->name, "hasvoicemail")) {
  27156. /* People expect that if 'hasvoicemail' is set, that the mailbox will
  27157. * be also set, even if not explicitly specified. */
  27158. if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
  27159. /*
  27160. * hasvoicemail is a users.conf legacy voicemail enable method.
  27161. * hasvoicemail is only going to work for app_voicemail mailboxes.
  27162. */
  27163. if (strchr(name, '@')) {
  27164. add_peer_mailboxes(peer, name);
  27165. } else {
  27166. char mailbox[AST_MAX_MAILBOX_UNIQUEID];
  27167. snprintf(mailbox, sizeof(mailbox), "%s@default", name);
  27168. add_peer_mailboxes(peer, mailbox);
  27169. }
  27170. }
  27171. } else if (!strcasecmp(v->name, "subscribemwi")) {
  27172. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
  27173. } else if (!strcasecmp(v->name, "vmexten")) {
  27174. ast_string_field_set(peer, vmexten, v->value);
  27175. } else if (!strcasecmp(v->name, "callgroup")) {
  27176. peer->callgroup = ast_get_group(v->value);
  27177. } else if (!strcasecmp(v->name, "allowtransfer")) {
  27178. peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
  27179. } else if (!strcasecmp(v->name, "pickupgroup")) {
  27180. peer->pickupgroup = ast_get_group(v->value);
  27181. } else if (!strcasecmp(v->name, "namedcallgroup")) {
  27182. peer->named_callgroups = ast_get_namedgroups(v->value);
  27183. } else if (!strcasecmp(v->name, "namedpickupgroup")) {
  27184. peer->named_pickupgroups = ast_get_namedgroups(v->value);
  27185. } else if (!strcasecmp(v->name, "allow")) {
  27186. int error = ast_format_cap_update_by_allow_disallow(peer->caps, v->value, TRUE);
  27187. if (error) {
  27188. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  27189. }
  27190. } else if (!strcasecmp(v->name, "disallow")) {
  27191. int error = ast_format_cap_update_by_allow_disallow(peer->caps, v->value, FALSE);
  27192. if (error) {
  27193. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  27194. }
  27195. } else if (!strcasecmp(v->name, "preferred_codec_only")) {
  27196. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
  27197. } else if (!strcasecmp(v->name, "autoframing")) {
  27198. peer->autoframing = ast_true(v->value);
  27199. } else if (!strcasecmp(v->name, "rtptimeout")) {
  27200. if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
  27201. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  27202. peer->rtptimeout = global_rtptimeout;
  27203. }
  27204. } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
  27205. if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
  27206. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  27207. peer->rtpholdtimeout = global_rtpholdtimeout;
  27208. }
  27209. } else if (!strcasecmp(v->name, "rtpkeepalive")) {
  27210. if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
  27211. ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
  27212. peer->rtpkeepalive = global_rtpkeepalive;
  27213. }
  27214. } else if (!strcasecmp(v->name, "timert1")) {
  27215. if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
  27216. ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
  27217. peer->timer_t1 = global_t1min;
  27218. }
  27219. timert1_set = 1;
  27220. } else if (!strcasecmp(v->name, "timerb")) {
  27221. if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
  27222. ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
  27223. peer->timer_b = global_timer_b;
  27224. }
  27225. timerb_set = 1;
  27226. } else if (!strcasecmp(v->name, "setvar")) {
  27227. peer->chanvars = add_var(v->value, peer->chanvars);
  27228. } else if (!strcasecmp(v->name, "header")) {
  27229. char tmp[4096];
  27230. snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
  27231. peer->chanvars = add_var(tmp, peer->chanvars);
  27232. } else if (!strcasecmp(v->name, "qualifyfreq")) {
  27233. int i;
  27234. if (sscanf(v->value, "%30d", &i) == 1) {
  27235. peer->qualifyfreq = i * 1000;
  27236. } else {
  27237. ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
  27238. peer->qualifyfreq = global_qualifyfreq;
  27239. }
  27240. } else if (!strcasecmp(v->name, "maxcallbitrate")) {
  27241. peer->maxcallbitrate = atoi(v->value);
  27242. if (peer->maxcallbitrate < 0) {
  27243. peer->maxcallbitrate = default_maxcallbitrate;
  27244. }
  27245. } else if (!strcasecmp(v->name, "session-timers")) {
  27246. int i = (int) str2stmode(v->value);
  27247. if (i < 0) {
  27248. ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
  27249. peer->stimer.st_mode_oper = global_st_mode;
  27250. } else {
  27251. peer->stimer.st_mode_oper = i;
  27252. }
  27253. } else if (!strcasecmp(v->name, "session-expires")) {
  27254. if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
  27255. ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
  27256. peer->stimer.st_max_se = global_max_se;
  27257. }
  27258. } else if (!strcasecmp(v->name, "session-minse")) {
  27259. if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
  27260. ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
  27261. peer->stimer.st_min_se = global_min_se;
  27262. }
  27263. if (peer->stimer.st_min_se < DEFAULT_MIN_SE) {
  27264. ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < %d secs\n", v->value, v->lineno, config, DEFAULT_MIN_SE);
  27265. peer->stimer.st_min_se = global_min_se;
  27266. }
  27267. } else if (!strcasecmp(v->name, "session-refresher")) {
  27268. int i = (int) str2strefresherparam(v->value);
  27269. if (i < 0) {
  27270. ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
  27271. peer->stimer.st_ref = global_st_refresher;
  27272. } else {
  27273. peer->stimer.st_ref = i;
  27274. }
  27275. } else if (!strcasecmp(v->name, "disallowed_methods")) {
  27276. char *disallow = ast_strdupa(v->value);
  27277. mark_parsed_methods(&peer->disallowed_methods, disallow);
  27278. } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
  27279. ast_string_field_set(peer, unsolicited_mailbox, v->value);
  27280. } else if (!strcasecmp(v->name, "use_q850_reason")) {
  27281. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
  27282. } else if (!strcasecmp(v->name, "encryption")) {
  27283. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
  27284. } else if (!strcasecmp(v->name, "encryption_taglen")) {
  27285. ast_set2_flag(&peer->flags[2], !strcasecmp(v->value, "32"), SIP_PAGE3_SRTP_TAG_32);
  27286. } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
  27287. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
  27288. } else if (!strcasecmp(v->name, "avpf")) {
  27289. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_USE_AVPF);
  27290. } else if (!strcasecmp(v->name, "icesupport")) {
  27291. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_ICE_SUPPORT);
  27292. } else if (!strcasecmp(v->name, "ignore_requested_pref")) {
  27293. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_IGNORE_PREFCAPS);
  27294. } else if (!strcasecmp(v->name, "discard_remote_hold_retrieval")) {
  27295. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_DISCARD_REMOTE_HOLD_RETRIEVAL);
  27296. } else if (!strcasecmp(v->name, "force_avp")) {
  27297. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_FORCE_AVP);
  27298. } else {
  27299. ast_rtp_dtls_cfg_parse(&peer->dtls_cfg, v->name, v->value);
  27300. }
  27301. }
  27302. /* Apply the encryption tag length to the DTLS configuration, in case DTLS is in use */
  27303. peer->dtls_cfg.suite = (ast_test_flag(&peer->flags[2], SIP_PAGE3_SRTP_TAG_32) ? AST_AES_CM_128_HMAC_SHA1_32 : AST_AES_CM_128_HMAC_SHA1_80);
  27304. /* These apply to devstate lookups */
  27305. if (realtime && !strcasecmp(v->name, "lastms")) {
  27306. sscanf(v->value, "%30d", &peer->lastms);
  27307. } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
  27308. ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
  27309. } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
  27310. if (alt_fullcontact && !alt) {
  27311. /* Reset, because the alternate also has a fullcontact and we
  27312. * do NOT want the field value to be doubled. It might be
  27313. * tempting to skip this, but the first table might not have
  27314. * fullcontact and since we're here, we know that the alternate
  27315. * absolutely does. */
  27316. alt_fullcontact = 0;
  27317. ast_str_reset(fullcontact);
  27318. }
  27319. /* Reconstruct field, because realtime separates our value at the ';' */
  27320. if (ast_str_strlen(fullcontact) > 0) {
  27321. ast_str_append(&fullcontact, 0, ";%s", v->value);
  27322. } else {
  27323. ast_str_set(&fullcontact, 0, "%s", v->value);
  27324. }
  27325. } else if (!strcasecmp(v->name, "qualify")) {
  27326. if (!strcasecmp(v->value, "no")) {
  27327. peer->maxms = 0;
  27328. } else if (!strcasecmp(v->value, "yes")) {
  27329. peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
  27330. } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
  27331. ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
  27332. peer->maxms = 0;
  27333. }
  27334. if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
  27335. /* This would otherwise cause a network storm, where the
  27336. * qualify response refreshes the peer from the database,
  27337. * which in turn causes another qualify to be sent, ad
  27338. * infinitum. */
  27339. ast_log(LOG_WARNING, "Qualify is incompatible with dynamic uncached realtime. Please either turn rtcachefriends on or turn qualify off on peer '%s'\n", peer->name);
  27340. peer->maxms = 0;
  27341. }
  27342. } else if (!strcasecmp(v->name, "keepalive")) {
  27343. if (!strcasecmp(v->value, "no")) {
  27344. peer->keepalive = 0;
  27345. } else if (!strcasecmp(v->value, "yes")) {
  27346. peer->keepalive = DEFAULT_KEEPALIVE_INTERVAL;
  27347. } else if (sscanf(v->value, "%30d", &peer->keepalive) != 1) {
  27348. ast_log(LOG_WARNING, "Keep alive of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
  27349. peer->keepalive = 0;
  27350. }
  27351. } else if (!strcasecmp(v->name, "callcounter")) {
  27352. peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
  27353. } else if (!strcasecmp(v->name, "call-limit")) {
  27354. peer->call_limit = atoi(v->value);
  27355. if (peer->call_limit < 0) {
  27356. peer->call_limit = 0;
  27357. }
  27358. } else if (!strcasecmp(v->name, "busylevel")) {
  27359. peer->busy_level = atoi(v->value);
  27360. if (peer->busy_level < 0) {
  27361. peer->busy_level = 0;
  27362. }
  27363. } else if (ast_cc_is_config_param(v->name)) {
  27364. ast_cc_set_param(peer->cc_params, v->name, v->value);
  27365. }
  27366. }
  27367. if (!devstate_only) {
  27368. struct sip_mailbox *mailbox;
  27369. AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
  27370. if (mailbox->delme) {
  27371. AST_LIST_REMOVE_CURRENT(entry);
  27372. destroy_mailbox(mailbox);
  27373. }
  27374. }
  27375. AST_LIST_TRAVERSE_SAFE_END;
  27376. }
  27377. if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
  27378. ast_log(LOG_WARNING, "Peer %s has a cc_agent_policy of 'native' but required libxml2 dependency is not installed. Changing policy to 'never'\n", peer->name);
  27379. ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
  27380. }
  27381. /* Note that Timer B is dependent upon T1 and MUST NOT be lower
  27382. * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
  27383. if (peer->timer_b < peer->timer_t1 * 64) {
  27384. if (timerb_set && timert1_set) {
  27385. ast_log(LOG_WARNING, "Timer B has been set lower than recommended for peer %s (%d < 64 * Timer-T1=%d)\n", peer->name, peer->timer_b, peer->timer_t1);
  27386. } else if (timerb_set) {
  27387. if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
  27388. ast_log(LOG_WARNING, "Timer B has been set lower than recommended (%d < 64 * timert1=%d). (RFC 3261, 17.1.1.2)\n", peer->timer_b, peer->timer_t1);
  27389. peer->timer_t1 = global_t1min;
  27390. peer->timer_b = peer->timer_t1 * 64;
  27391. }
  27392. peer->timer_t1 = peer->timer_b / 64;
  27393. } else {
  27394. peer->timer_b = peer->timer_t1 * 64;
  27395. }
  27396. }
  27397. if (!peer->default_outbound_transport) {
  27398. /* Set default set of transports */
  27399. peer->transports = default_transports;
  27400. /* Set default primary transport */
  27401. peer->default_outbound_transport = default_primary_transport;
  27402. }
  27403. /* The default transport type set during build_peer should only replace the socket.type when...
  27404. * 1. Registration is not present and the socket.type and default transport types are different.
  27405. * 2. The socket.type is not an acceptable transport type after rebuilding peer.
  27406. * 3. The socket.type is not set yet. */
  27407. if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
  27408. !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
  27409. set_socket_transport(&peer->socket, peer->default_outbound_transport);
  27410. }
  27411. ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
  27412. ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
  27413. ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
  27414. if (ast_str_strlen(fullcontact)) {
  27415. ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
  27416. peer->rt_fromcontact = TRUE;
  27417. /* We have a hostname in the fullcontact, but if we don't have an
  27418. * address listed on the entry (or if it's 'dynamic'), then we need to
  27419. * parse the entry to obtain the IP address, so a dynamic host can be
  27420. * contacted immediately after reload (as opposed to waiting for it to
  27421. * register once again). But if we have an address for this peer and NAT was
  27422. * specified, use that address instead. */
  27423. /* XXX May need to revisit the final argument; does the realtime DB store whether
  27424. * the original contact was over TLS or not? XXX */
  27425. if ((!ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT))
  27426. || ast_sockaddr_isnull(&peer->addr)) {
  27427. __set_address_from_contact(ast_str_buffer(fullcontact), &peer->addr, 0);
  27428. }
  27429. }
  27430. if (srvlookup && peer->dnsmgr == NULL) {
  27431. char transport[MAXHOSTNAMELEN];
  27432. char _srvlookup[MAXHOSTNAMELEN];
  27433. char *params;
  27434. ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
  27435. if ((params = strchr(_srvlookup, ';'))) {
  27436. *params++ = '\0';
  27437. }
  27438. snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
  27439. peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type); /* Filter address family */
  27440. if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
  27441. on_dns_update_peer, sip_ref_peer(peer, "Store peer on dnsmgr"))) {
  27442. ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
  27443. sip_unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
  27444. sip_unref_peer(peer, "getting rid of a peer pointer");
  27445. return NULL;
  27446. }
  27447. if (!peer->dnsmgr) {
  27448. /* dnsmgr refresh disabeld, release reference */
  27449. sip_unref_peer(peer, "dnsmgr disabled, unref peer");
  27450. }
  27451. ast_string_field_set(peer, tohost, srvlookup);
  27452. if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
  27453. int ha_error = 0;
  27454. ast_append_acl("deny", ast_sockaddr_stringify_addr(&peer->addr), &sip_cfg.contact_acl, &ha_error, NULL);
  27455. if (ha_error) {
  27456. ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
  27457. }
  27458. }
  27459. } else if (peer->dnsmgr && !peer->host_dynamic) {
  27460. /* force a refresh here on reload if dnsmgr already exists and host is set. */
  27461. ast_dnsmgr_refresh(peer->dnsmgr);
  27462. }
  27463. if (port && !realtime && peer->host_dynamic) {
  27464. ast_sockaddr_set_port(&peer->defaddr, port);
  27465. } else if (port) {
  27466. ast_sockaddr_set_port(&peer->addr, port);
  27467. }
  27468. if (ast_sockaddr_port(&peer->addr) == 0) {
  27469. ast_sockaddr_set_port(&peer->addr,
  27470. (peer->socket.type & AST_TRANSPORT_TLS) ?
  27471. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  27472. }
  27473. if (ast_sockaddr_port(&peer->defaddr) == 0) {
  27474. ast_sockaddr_set_port(&peer->defaddr,
  27475. (peer->socket.type & AST_TRANSPORT_TLS) ?
  27476. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  27477. }
  27478. if (!peer->socket.port) {
  27479. peer->socket.port = htons(((peer->socket.type & AST_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
  27480. }
  27481. if (realtime) {
  27482. int enablepoke = 1;
  27483. if (!sip_cfg.ignore_regexpire && peer->host_dynamic) {
  27484. time_t nowtime = time(NULL);
  27485. if ((nowtime - regseconds) > 0) {
  27486. destroy_association(peer);
  27487. memset(&peer->addr, 0, sizeof(peer->addr));
  27488. peer->lastms = -1;
  27489. enablepoke = 0;
  27490. ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
  27491. }
  27492. }
  27493. /* Startup regular pokes */
  27494. if (!devstate_only && enablepoke) {
  27495. /*
  27496. * We cannot poke the peer now in this thread without
  27497. * a lock inversion so pass it off to the scheduler
  27498. * thread.
  27499. */
  27500. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
  27501. 0, /* Poke the peer ASAP */
  27502. sip_poke_peer_now, peer,
  27503. sip_unref_peer(_data, "removing poke peer ref"),
  27504. sip_unref_peer(peer, "removing poke peer ref"),
  27505. sip_ref_peer(peer, "adding poke peer ref"));
  27506. }
  27507. }
  27508. if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
  27509. sip_cfg.allowsubscribe = TRUE; /* No global ban any more */
  27510. }
  27511. /* If read-only RT backend, then refresh from local DB cache */
  27512. if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
  27513. reg_source_db(peer);
  27514. }
  27515. /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
  27516. * subscribe to it now. */
  27517. if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
  27518. !AST_LIST_EMPTY(&peer->mailboxes)) {
  27519. add_peer_mwi_subs(peer);
  27520. /* Send MWI from the event cache only. This is so we can send initial
  27521. * MWI if app_voicemail got loaded before chan_sip. If it is the other
  27522. * way, then we will get events when app_voicemail gets loaded. */
  27523. sip_send_mwi_to_peer(peer, 1);
  27524. }
  27525. peer->the_mark = 0;
  27526. oldacl = ast_free_acl_list(oldacl);
  27527. olddirectmediaacl = ast_free_acl_list(olddirectmediaacl);
  27528. if (!ast_strlen_zero(peer->callback)) { /* build string from peer info */
  27529. char *reg_string;
  27530. if (ast_asprintf(&reg_string, "%s?%s:%s@%s/%s", peer->name, peer->username, !ast_strlen_zero(peer->remotesecret) ? peer->remotesecret : peer->secret, peer->tohost, peer->callback) >= 0) {
  27531. sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
  27532. ast_free(reg_string);
  27533. }
  27534. }
  27535. /* If an ACL change subscription is needed and doesn't exist, we need one. */
  27536. if (acl_change_subscription_needed) {
  27537. acl_change_stasis_subscribe();
  27538. }
  27539. return peer;
  27540. }
  27541. static int peer_markall_func(void *device, void *arg, int flags)
  27542. {
  27543. struct sip_peer *peer = device;
  27544. if (!peer->selfdestruct) {
  27545. peer->the_mark = 1;
  27546. }
  27547. return 0;
  27548. }
  27549. static int peer_markall_autopeers_func(void *device, void *arg, int flags)
  27550. {
  27551. struct sip_peer *peer = device;
  27552. if (peer->selfdestruct) {
  27553. peer->the_mark = 1;
  27554. }
  27555. return 0;
  27556. }
  27557. /*!
  27558. * \internal
  27559. * \brief If no default formats are set in config, these are used
  27560. */
  27561. static void sip_set_default_format_capabilities(struct ast_format_cap *cap)
  27562. {
  27563. ast_format_cap_remove_by_type(cap, AST_MEDIA_TYPE_UNKNOWN);
  27564. ast_format_cap_append(cap, ast_format_ulaw, 0);
  27565. ast_format_cap_append(cap, ast_format_alaw, 0);
  27566. ast_format_cap_append(cap, ast_format_gsm, 0);
  27567. ast_format_cap_append(cap, ast_format_h263, 0);
  27568. }
  27569. static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
  27570. int global_nat, specific_nat;
  27571. if (reason == CHANNEL_MODULE_LOAD && (specific_nat = ast_test_flag(&flags[0], SIP_NAT_FORCE_RPORT)) != (global_nat = ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT))) {
  27572. ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the global setting can make\n");
  27573. ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
  27574. ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
  27575. ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
  27576. ast_log(LOG_WARNING, "!!! (config category='%s' global force_rport='%s' peer/user force_rport='%s')\n", cat, AST_CLI_YESNO(global_nat), AST_CLI_YESNO(specific_nat));
  27577. }
  27578. }
  27579. static int cleanup_registration(void *obj, void *arg, int flags)
  27580. {
  27581. struct sip_registry *reg = obj;
  27582. ao2_lock(reg);
  27583. if (reg->call) {
  27584. ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
  27585. /* This will also remove references to the registry */
  27586. dialog_unlink_all(reg->call);
  27587. reg->call = dialog_unref(reg->call, "remove iterator->call from registry traversal");
  27588. }
  27589. if (reg->expire > -1) {
  27590. AST_SCHED_DEL_UNREF(sched, reg->expire, ao2_t_ref(reg, -1, "reg ptr unref from reload config"));
  27591. }
  27592. if (reg->timeout > -1) {
  27593. AST_SCHED_DEL_UNREF(sched, reg->timeout, ao2_t_ref(reg, -1, "reg ptr unref from reload config"));
  27594. }
  27595. if (reg->dnsmgr) {
  27596. ast_dnsmgr_release(reg->dnsmgr);
  27597. reg->dnsmgr = NULL;
  27598. ao2_t_ref(reg, -1, "reg ptr unref from dnsmgr");
  27599. }
  27600. ao2_unlock(reg);
  27601. return CMP_MATCH;
  27602. }
  27603. static void cleanup_all_regs(void)
  27604. {
  27605. ao2_t_callback(registry_list, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
  27606. cleanup_registration, NULL, "remove all SIP registry items");
  27607. }
  27608. /*! \brief Re-read SIP.conf config file
  27609. \note This function reloads all config data, except for
  27610. active peers (with registrations). They will only
  27611. change configuration data at restart, not at reload.
  27612. SIP debug and recordhistory state will not change
  27613. */
  27614. static int reload_config(enum channelreloadreason reason)
  27615. {
  27616. struct ast_config *cfg, *ucfg;
  27617. struct ast_variable *v;
  27618. struct sip_peer *peer;
  27619. char *cat, *stringp, *context, *oldregcontext;
  27620. char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
  27621. struct ast_flags mask[3] = {{0}};
  27622. struct ast_flags setflags[3] = {{0}};
  27623. struct ast_flags config_flags = { (reason == CHANNEL_MODULE_LOAD || reason == CHANNEL_ACL_RELOAD) ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
  27624. int auto_sip_domains = FALSE;
  27625. struct ast_sockaddr old_bindaddr = bindaddr;
  27626. int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
  27627. int subscribe_network_change = 1;
  27628. time_t run_start, run_end;
  27629. int bindport = 0;
  27630. int acl_change_subscription_needed = 0;
  27631. int min_subexpiry_set = 0, max_subexpiry_set = 0;
  27632. run_start = time(0);
  27633. ast_unload_realtime("sipregs");
  27634. ast_unload_realtime("sippeers");
  27635. cfg = ast_config_load(config, config_flags);
  27636. /* We *must* have a config file otherwise stop immediately */
  27637. if (!cfg) {
  27638. ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
  27639. return -1;
  27640. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  27641. ucfg = ast_config_load("users.conf", config_flags);
  27642. if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
  27643. return 1;
  27644. } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
  27645. ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
  27646. return 1;
  27647. }
  27648. /* Must reread both files, because one changed */
  27649. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  27650. if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
  27651. ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
  27652. ast_config_destroy(ucfg);
  27653. return 1;
  27654. }
  27655. if (!cfg) {
  27656. /* should have been able to reload here */
  27657. ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
  27658. return -1;
  27659. }
  27660. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  27661. ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
  27662. return 1;
  27663. } else {
  27664. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  27665. if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
  27666. ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
  27667. ast_config_destroy(cfg);
  27668. return 1;
  27669. }
  27670. }
  27671. sip_cfg.contact_acl = ast_free_acl_list(sip_cfg.contact_acl);
  27672. default_tls_cfg.enabled = FALSE; /* Default: Disable TLS */
  27673. default_dtls_cfg.enabled = FALSE; /* Default: Disable DTLS too */
  27674. if (reason != CHANNEL_MODULE_LOAD) {
  27675. ast_debug(4, "--------------- SIP reload started\n");
  27676. clear_sip_domains();
  27677. ast_mutex_lock(&authl_lock);
  27678. if (authl) {
  27679. ao2_t_ref(authl, -1, "Removing old global authentication");
  27680. authl = NULL;
  27681. }
  27682. ast_mutex_unlock(&authl_lock);
  27683. /* Then, actually destroy users and registry */
  27684. cleanup_all_regs();
  27685. ast_debug(4, "--------------- Done destroying registry list\n");
  27686. ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
  27687. }
  27688. /* Reset certificate handling for TLS and DTLS sessions */
  27689. if (reason != CHANNEL_MODULE_LOAD) {
  27690. ast_free(default_tls_cfg.certfile);
  27691. ast_free(default_tls_cfg.pvtfile);
  27692. ast_free(default_tls_cfg.cipher);
  27693. ast_free(default_tls_cfg.cafile);
  27694. ast_free(default_tls_cfg.capath);
  27695. ast_rtp_dtls_cfg_free(&default_dtls_cfg);
  27696. }
  27697. default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
  27698. default_tls_cfg.pvtfile = ast_strdup("");
  27699. default_tls_cfg.cipher = ast_strdup("");
  27700. default_tls_cfg.cafile = ast_strdup("");
  27701. default_tls_cfg.capath = ast_strdup("");
  27702. /* Using the same idea fro DTLS as the code block above for TLS */
  27703. default_dtls_cfg.certfile = ast_strdup("");
  27704. default_dtls_cfg.pvtfile = ast_strdup("");
  27705. default_dtls_cfg.cipher = ast_strdup("");
  27706. default_dtls_cfg.cafile = ast_strdup("");
  27707. default_dtls_cfg.capath = ast_strdup("");
  27708. /* Initialize copy of current sip_cfg.regcontext for later use in removing stale contexts */
  27709. ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
  27710. oldregcontext = oldcontexts;
  27711. /* Clear all flags before setting default values */
  27712. /* Preserve debugging settings for console */
  27713. sipdebug &= sip_debug_console;
  27714. ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
  27715. ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
  27716. ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
  27717. /* Reset IP addresses */
  27718. ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
  27719. memset(&internip, 0, sizeof(internip));
  27720. /* Free memory for local network address mask */
  27721. ast_free_ha(localaddr);
  27722. memset(&localaddr, 0, sizeof(localaddr));
  27723. memset(&externaddr, 0, sizeof(externaddr));
  27724. memset(&media_address, 0, sizeof(media_address));
  27725. memset(&rtpbindaddr, 0, sizeof(rtpbindaddr));
  27726. memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
  27727. sip_cfg.outboundproxy.force = FALSE; /*!< Don't force proxy usage, use route: headers */
  27728. default_transports = AST_TRANSPORT_UDP;
  27729. default_primary_transport = AST_TRANSPORT_UDP;
  27730. ourport_tcp = STANDARD_SIP_PORT;
  27731. ourport_tls = STANDARD_TLS_PORT;
  27732. externtcpport = STANDARD_SIP_PORT;
  27733. externtlsport = STANDARD_TLS_PORT;
  27734. sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
  27735. global_tos_sip = DEFAULT_TOS_SIP;
  27736. global_tos_audio = DEFAULT_TOS_AUDIO;
  27737. global_tos_video = DEFAULT_TOS_VIDEO;
  27738. global_tos_text = DEFAULT_TOS_TEXT;
  27739. global_cos_sip = DEFAULT_COS_SIP;
  27740. global_cos_audio = DEFAULT_COS_AUDIO;
  27741. global_cos_video = DEFAULT_COS_VIDEO;
  27742. global_cos_text = DEFAULT_COS_TEXT;
  27743. externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
  27744. externexpire = 0; /* Expiration for DNS re-issuing */
  27745. externrefresh = 10;
  27746. /* Reset channel settings to default before re-configuring */
  27747. sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
  27748. sip_cfg.regcontext[0] = '\0';
  27749. sip_set_default_format_capabilities(sip_cfg.caps);
  27750. sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
  27751. sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
  27752. sip_cfg.send_diversion = DEFAULT_SEND_DIVERSION;
  27753. sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
  27754. sip_cfg.notifycid = DEFAULT_NOTIFYCID;
  27755. sip_cfg.notifyhold = FALSE; /*!< Keep track of hold status for a peer */
  27756. sip_cfg.directrtpsetup = FALSE; /* Experimental feature, disabled by default */
  27757. sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
  27758. sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
  27759. sip_cfg.auth_message_requests = DEFAULT_AUTH_MESSAGE;
  27760. sip_cfg.messagecontext[0] = '\0';
  27761. sip_cfg.accept_outofcall_message = DEFAULT_ACCEPT_OUTOFCALL_MESSAGE;
  27762. sip_cfg.allowsubscribe = FALSE;
  27763. sip_cfg.disallowed_methods = SIP_UNKNOWN;
  27764. sip_cfg.contact_acl = NULL; /* Reset the contact ACL */
  27765. snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
  27766. snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
  27767. snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
  27768. global_prematuremediafilter = TRUE;
  27769. ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
  27770. ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
  27771. sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
  27772. ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
  27773. ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
  27774. sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
  27775. global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
  27776. global_regattempts_max = 0;
  27777. global_reg_retry_403 = 0;
  27778. sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
  27779. sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
  27780. global_autoframing = 0;
  27781. sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
  27782. global_callcounter = DEFAULT_CALLCOUNTER;
  27783. global_match_auth_username = FALSE; /*!< Match auth username if available instead of From: Default off. */
  27784. global_rtptimeout = 0;
  27785. global_rtpholdtimeout = 0;
  27786. global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
  27787. sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
  27788. sip_cfg.rtautoclear = 120;
  27789. ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for all devices: TRUE */
  27790. ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES); /* Default for all devices: Yes */
  27791. sip_cfg.peer_rtupdate = TRUE;
  27792. global_dynamic_exclude_static = 0; /* Exclude static peers */
  27793. sip_cfg.tcp_enabled = FALSE;
  27794. /* Session-Timers */
  27795. global_st_mode = SESSION_TIMER_MODE_ACCEPT;
  27796. global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
  27797. global_min_se = DEFAULT_MIN_SE;
  27798. global_max_se = DEFAULT_MAX_SE;
  27799. /* Peer poking settings */
  27800. global_qualify_gap = DEFAULT_QUALIFY_GAP;
  27801. global_qualify_peers = DEFAULT_QUALIFY_PEERS;
  27802. /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
  27803. ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
  27804. ast_copy_string(sip_cfg.default_record_on_feature, DEFAULT_RECORD_FEATURE, sizeof(sip_cfg.default_record_on_feature));
  27805. ast_copy_string(sip_cfg.default_record_off_feature, DEFAULT_RECORD_FEATURE, sizeof(sip_cfg.default_record_off_feature));
  27806. sip_cfg.default_subscribecontext[0] = '\0';
  27807. sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
  27808. default_language[0] = '\0';
  27809. default_fromdomain[0] = '\0';
  27810. default_fromdomainport = 0;
  27811. default_qualify = DEFAULT_QUALIFY;
  27812. default_keepalive = DEFAULT_KEEPALIVE;
  27813. default_zone[0] = '\0';
  27814. default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
  27815. ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
  27816. ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
  27817. ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
  27818. ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
  27819. ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA); /*!< Allow re-invites */
  27820. ast_set_flag(&global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT); /*!< Default to nat=auto_force_rport */
  27821. ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
  27822. ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
  27823. /* Debugging settings, always default to off */
  27824. dumphistory = FALSE;
  27825. recordhistory = FALSE;
  27826. sipdebug &= ~sip_debug_config;
  27827. /* Misc settings for the channel */
  27828. global_relaxdtmf = FALSE;
  27829. global_authfailureevents = FALSE;
  27830. global_t1 = DEFAULT_TIMER_T1;
  27831. global_timer_b = 64 * DEFAULT_TIMER_T1;
  27832. global_t1min = DEFAULT_T1MIN;
  27833. global_qualifyfreq = DEFAULT_QUALIFYFREQ;
  27834. global_t38_maxdatagram = -1;
  27835. global_shrinkcallerid = 1;
  27836. global_refer_addheaders = TRUE;
  27837. authlimit = DEFAULT_AUTHLIMIT;
  27838. authtimeout = DEFAULT_AUTHTIMEOUT;
  27839. global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
  27840. min_expiry = DEFAULT_MIN_EXPIRY;
  27841. max_expiry = DEFAULT_MAX_EXPIRY;
  27842. default_expiry = DEFAULT_DEFAULT_EXPIRY;
  27843. sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
  27844. /* Copy the default jb config over global_jbconf */
  27845. memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
  27846. ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
  27847. ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
  27848. ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
  27849. ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
  27850. /* Read the [general] config section of sip.conf (or from realtime config) */
  27851. for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
  27852. if (handle_common_options(&setflags[0], &mask[0], v)) {
  27853. continue;
  27854. }
  27855. if (handle_t38_options(&setflags[0], &mask[0], v, &global_t38_maxdatagram)) {
  27856. continue;
  27857. }
  27858. /* handle jb conf */
  27859. if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
  27860. continue;
  27861. }
  27862. /* Load default dtls configuration */
  27863. ast_rtp_dtls_cfg_parse(&default_dtls_cfg, v->name, v->value);
  27864. /* handle tls conf, don't allow setting of tlsverifyclient as it isn't supported by chan_sip */
  27865. if (!strcasecmp(v->name, "tlsverifyclient")) {
  27866. ast_log(LOG_WARNING, "Ignoring unsupported option 'tlsverifyclient'\n");
  27867. continue;
  27868. } else if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
  27869. continue;
  27870. }
  27871. if (!strcasecmp(v->name, "context")) {
  27872. ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
  27873. } else if (!strcasecmp(v->name, "recordonfeature")) {
  27874. ast_copy_string(sip_cfg.default_record_on_feature, v->value, sizeof(sip_cfg.default_record_on_feature));
  27875. } else if (!strcasecmp(v->name, "recordofffeature")) {
  27876. ast_copy_string(sip_cfg.default_record_off_feature, v->value, sizeof(sip_cfg.default_record_off_feature));
  27877. } else if (!strcasecmp(v->name, "subscribecontext")) {
  27878. ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
  27879. } else if (!strcasecmp(v->name, "callcounter")) {
  27880. global_callcounter = ast_true(v->value) ? 1 : 0;
  27881. } else if (!strcasecmp(v->name, "allowguest")) {
  27882. sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
  27883. } else if (!strcasecmp(v->name, "realm")) {
  27884. ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
  27885. } else if (!strcasecmp(v->name, "domainsasrealm")) {
  27886. sip_cfg.domainsasrealm = ast_true(v->value);
  27887. } else if (!strcasecmp(v->name, "useragent")) {
  27888. ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
  27889. ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
  27890. } else if (!strcasecmp(v->name, "sdpsession")) {
  27891. ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
  27892. } else if (!strcasecmp(v->name, "sdpowner")) {
  27893. /* Field cannot contain spaces */
  27894. if (!strstr(v->value, " ")) {
  27895. ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
  27896. } else {
  27897. ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
  27898. }
  27899. } else if (!strcasecmp(v->name, "allowtransfer")) {
  27900. sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
  27901. } else if (!strcasecmp(v->name, "rtcachefriends")) {
  27902. ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
  27903. } else if (!strcasecmp(v->name, "rtsavesysname")) {
  27904. sip_cfg.rtsave_sysname = ast_true(v->value);
  27905. } else if (!strcasecmp(v->name, "rtsavepath")) {
  27906. sip_cfg.rtsave_path = ast_true(v->value);
  27907. } else if (!strcasecmp(v->name, "rtupdate")) {
  27908. sip_cfg.peer_rtupdate = ast_true(v->value);
  27909. } else if (!strcasecmp(v->name, "ignoreregexpire")) {
  27910. sip_cfg.ignore_regexpire = ast_true(v->value);
  27911. } else if (!strcasecmp(v->name, "timert1")) {
  27912. /* Defaults to 500ms, but RFC 3261 states that it is recommended
  27913. * for the value to be set higher, though a lower value is only
  27914. * allowed on private networks unconnected to the Internet. */
  27915. global_t1 = atoi(v->value);
  27916. } else if (!strcasecmp(v->name, "timerb")) {
  27917. int tmp = atoi(v->value);
  27918. if (tmp < 500) {
  27919. global_timer_b = global_t1 * 64;
  27920. ast_log(LOG_WARNING, "Invalid value for timerb ('%s'). Setting to default ('%d').\n", v->value, global_timer_b);
  27921. }
  27922. timerb_set = 1;
  27923. } else if (!strcasecmp(v->name, "t1min")) {
  27924. global_t1min = atoi(v->value);
  27925. } else if (!strcasecmp(v->name, "transport")) {
  27926. char *val = ast_strdupa(v->value);
  27927. char *trans;
  27928. default_transports = default_primary_transport = 0;
  27929. while ((trans = strsep(&val, ","))) {
  27930. trans = ast_skip_blanks(trans);
  27931. if (!strncasecmp(trans, "udp", 3)) {
  27932. default_transports |= AST_TRANSPORT_UDP;
  27933. } else if (!strncasecmp(trans, "tcp", 3)) {
  27934. default_transports |= AST_TRANSPORT_TCP;
  27935. } else if (!strncasecmp(trans, "tls", 3)) {
  27936. default_transports |= AST_TRANSPORT_TLS;
  27937. } else if (!strncasecmp(trans, "wss", 3)) {
  27938. default_transports |= AST_TRANSPORT_WSS;
  27939. } else if (!strncasecmp(trans, "ws", 2)) {
  27940. default_transports |= AST_TRANSPORT_WS;
  27941. } else {
  27942. ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
  27943. }
  27944. if (default_primary_transport == 0) {
  27945. default_primary_transport = default_transports;
  27946. }
  27947. }
  27948. } else if (!strcasecmp(v->name, "tcpenable")) {
  27949. if (!ast_false(v->value)) {
  27950. ast_debug(2, "Enabling TCP socket for listening\n");
  27951. sip_cfg.tcp_enabled = TRUE;
  27952. }
  27953. } else if (!strcasecmp(v->name, "tcpbindaddr")) {
  27954. if (ast_parse_arg(v->value, PARSE_ADDR,
  27955. &sip_tcp_desc.local_address)) {
  27956. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
  27957. v->name, v->value, v->lineno, config);
  27958. }
  27959. ast_debug(2, "Setting TCP socket address to %s\n",
  27960. ast_sockaddr_stringify(&sip_tcp_desc.local_address));
  27961. } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
  27962. global_dynamic_exclude_static = ast_true(v->value);
  27963. } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny") || !strcasecmp(v->name, "contactacl")) {
  27964. int ha_error = 0;
  27965. ast_append_acl(v->name + 7, v->value, &sip_cfg.contact_acl, &ha_error, &acl_change_subscription_needed);
  27966. if (ha_error) {
  27967. ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  27968. }
  27969. } else if (!strcasecmp(v->name, "rtautoclear")) {
  27970. int i = atoi(v->value);
  27971. if (i > 0) {
  27972. sip_cfg.rtautoclear = i;
  27973. } else {
  27974. i = 0;
  27975. }
  27976. ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
  27977. } else if (!strcasecmp(v->name, "usereqphone")) {
  27978. ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
  27979. } else if (!strcasecmp(v->name, "prematuremedia")) {
  27980. global_prematuremediafilter = ast_true(v->value);
  27981. } else if (!strcasecmp(v->name, "relaxdtmf")) {
  27982. global_relaxdtmf = ast_true(v->value);
  27983. } else if (!strcasecmp(v->name, "vmexten")) {
  27984. ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
  27985. } else if (!strcasecmp(v->name, "rtptimeout")) {
  27986. if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
  27987. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  27988. global_rtptimeout = 0;
  27989. }
  27990. } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
  27991. if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
  27992. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  27993. global_rtpholdtimeout = 0;
  27994. }
  27995. } else if (!strcasecmp(v->name, "rtpkeepalive")) {
  27996. if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
  27997. ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
  27998. global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
  27999. }
  28000. } else if (!strcasecmp(v->name, "compactheaders")) {
  28001. sip_cfg.compactheaders = ast_true(v->value);
  28002. } else if (!strcasecmp(v->name, "notifymimetype")) {
  28003. ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
  28004. } else if (!strcasecmp(v->name, "directrtpsetup")) {
  28005. sip_cfg.directrtpsetup = ast_true(v->value);
  28006. } else if (!strcasecmp(v->name, "notifyringing")) {
  28007. sip_cfg.notifyringing = ast_true(v->value);
  28008. } else if (!strcasecmp(v->name, "notifyhold")) {
  28009. sip_cfg.notifyhold = ast_true(v->value);
  28010. } else if (!strcasecmp(v->name, "notifycid")) {
  28011. if (!strcasecmp(v->value, "ignore-context")) {
  28012. sip_cfg.notifycid = IGNORE_CONTEXT;
  28013. } else {
  28014. sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
  28015. }
  28016. } else if (!strcasecmp(v->name, "alwaysauthreject")) {
  28017. sip_cfg.alwaysauthreject = ast_true(v->value);
  28018. } else if (!strcasecmp(v->name, "auth_options_requests")) {
  28019. if (ast_true(v->value)) {
  28020. sip_cfg.auth_options_requests = 1;
  28021. }
  28022. } else if (!strcasecmp(v->name, "auth_message_requests")) {
  28023. sip_cfg.auth_message_requests = ast_true(v->value) ? 1 : 0;
  28024. } else if (!strcasecmp(v->name, "accept_outofcall_message")) {
  28025. sip_cfg.accept_outofcall_message = ast_true(v->value) ? 1 : 0;
  28026. } else if (!strcasecmp(v->name, "outofcall_message_context")) {
  28027. ast_copy_string(sip_cfg.messagecontext, v->value, sizeof(sip_cfg.messagecontext));
  28028. } else if (!strcasecmp(v->name, "mohinterpret")) {
  28029. ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
  28030. } else if (!strcasecmp(v->name, "mohsuggest")) {
  28031. ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
  28032. } else if (!strcasecmp(v->name, "tonezone")) {
  28033. struct ast_tone_zone *new_zone;
  28034. if (!(new_zone = ast_get_indication_zone(v->value))) {
  28035. ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone in [general] at line %d. Check indications.conf for available country codes.\n", v->value, v->lineno);
  28036. } else {
  28037. ast_tone_zone_unref(new_zone);
  28038. ast_copy_string(default_zone, v->value, sizeof(default_zone));
  28039. }
  28040. } else if (!strcasecmp(v->name, "language")) {
  28041. ast_copy_string(default_language, v->value, sizeof(default_language));
  28042. } else if (!strcasecmp(v->name, "regcontext")) {
  28043. ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
  28044. stringp = newcontexts;
  28045. /* Let's remove any contexts that are no longer defined in regcontext */
  28046. cleanup_stale_contexts(stringp, oldregcontext);
  28047. /* Create contexts if they don't exist already */
  28048. while ((context = strsep(&stringp, "&"))) {
  28049. ast_copy_string(used_context, context, sizeof(used_context));
  28050. ast_context_find_or_create(NULL, NULL, context, "SIP");
  28051. }
  28052. ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
  28053. } else if (!strcasecmp(v->name, "regextenonqualify")) {
  28054. sip_cfg.regextenonqualify = ast_true(v->value);
  28055. } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
  28056. sip_cfg.legacy_useroption_parsing = ast_true(v->value);
  28057. } else if (!strcasecmp(v->name, "send_diversion")) {
  28058. sip_cfg.send_diversion = ast_true(v->value);
  28059. } else if (!strcasecmp(v->name, "callerid")) {
  28060. ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
  28061. } else if (!strcasecmp(v->name, "mwi_from")) {
  28062. ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
  28063. } else if (!strcasecmp(v->name, "fromdomain")) {
  28064. char *fromdomainport;
  28065. ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
  28066. if ((fromdomainport = strchr(default_fromdomain, ':'))) {
  28067. *fromdomainport++ = '\0';
  28068. if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
  28069. ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
  28070. }
  28071. } else {
  28072. default_fromdomainport = STANDARD_SIP_PORT;
  28073. }
  28074. } else if (!strcasecmp(v->name, "outboundproxy")) {
  28075. struct sip_proxy *proxy;
  28076. if (ast_strlen_zero(v->value)) {
  28077. ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
  28078. continue;
  28079. }
  28080. proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
  28081. if (!proxy) {
  28082. ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
  28083. continue;
  28084. }
  28085. } else if (!strcasecmp(v->name, "autocreatepeer")) {
  28086. if (!strcasecmp(v->value, "persist")) {
  28087. sip_cfg.autocreatepeer = AUTOPEERS_PERSIST;
  28088. } else {
  28089. sip_cfg.autocreatepeer = ast_true(v->value) ? AUTOPEERS_VOLATILE : AUTOPEERS_DISABLED;
  28090. }
  28091. } else if (!strcasecmp(v->name, "match_auth_username")) {
  28092. global_match_auth_username = ast_true(v->value);
  28093. } else if (!strcasecmp(v->name, "srvlookup")) {
  28094. sip_cfg.srvlookup = ast_true(v->value);
  28095. } else if (!strcasecmp(v->name, "pedantic")) {
  28096. sip_cfg.pedanticsipchecking = ast_true(v->value);
  28097. } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
  28098. max_expiry = atoi(v->value);
  28099. if (max_expiry < 1) {
  28100. max_expiry = DEFAULT_MAX_EXPIRY;
  28101. }
  28102. } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
  28103. min_expiry = atoi(v->value);
  28104. if (min_expiry < 1) {
  28105. min_expiry = DEFAULT_MIN_EXPIRY;
  28106. }
  28107. } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
  28108. default_expiry = atoi(v->value);
  28109. if (default_expiry < 1) {
  28110. default_expiry = DEFAULT_DEFAULT_EXPIRY;
  28111. }
  28112. } else if (!strcasecmp(v->name, "submaxexpirey") || !strcasecmp(v->name, "submaxexpiry")) {
  28113. max_subexpiry = atoi(v->value);
  28114. if (max_subexpiry < 1) {
  28115. max_subexpiry = DEFAULT_MAX_EXPIRY;
  28116. }
  28117. max_subexpiry_set = 1;
  28118. } else if (!strcasecmp(v->name, "subminexpirey") || !strcasecmp(v->name, "subminexpiry")) {
  28119. min_subexpiry = atoi(v->value);
  28120. if (min_subexpiry < 1) {
  28121. min_subexpiry = DEFAULT_MIN_EXPIRY;
  28122. }
  28123. min_subexpiry_set = 1;
  28124. } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
  28125. mwi_expiry = atoi(v->value);
  28126. if (mwi_expiry < 1) {
  28127. mwi_expiry = DEFAULT_MWI_EXPIRY;
  28128. }
  28129. } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
  28130. if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
  28131. &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
  28132. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
  28133. v->name, v->value, v->lineno, config);
  28134. }
  28135. } else if (!strcasecmp(v->name, "tcpauthlimit")) {
  28136. if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
  28137. &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
  28138. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
  28139. v->name, v->value, v->lineno, config);
  28140. }
  28141. } else if (!strcasecmp(v->name, "sipdebug")) {
  28142. if (ast_true(v->value))
  28143. sipdebug |= sip_debug_config;
  28144. } else if (!strcasecmp(v->name, "dumphistory")) {
  28145. dumphistory = ast_true(v->value);
  28146. } else if (!strcasecmp(v->name, "recordhistory")) {
  28147. recordhistory = ast_true(v->value);
  28148. } else if (!strcasecmp(v->name, "registertimeout")) {
  28149. global_reg_timeout = atoi(v->value);
  28150. if (global_reg_timeout < 1) {
  28151. global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
  28152. }
  28153. } else if (!strcasecmp(v->name, "registerattempts")) {
  28154. global_regattempts_max = atoi(v->value);
  28155. } else if (!strcasecmp(v->name, "register_retry_403")) {
  28156. global_reg_retry_403 = ast_true(v->value);
  28157. } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
  28158. if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
  28159. ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
  28160. }
  28161. } else if (!strcasecmp(v->name, "localnet")) {
  28162. struct ast_ha *na;
  28163. int ha_error = 0;
  28164. if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
  28165. ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
  28166. } else {
  28167. localaddr = na;
  28168. }
  28169. if (ha_error) {
  28170. ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
  28171. }
  28172. } else if (!strcasecmp(v->name, "media_address")) {
  28173. if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
  28174. ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
  28175. } else if (!strcasecmp(v->name, "rtpbindaddr")) {
  28176. if (ast_parse_arg(v->value, PARSE_ADDR, &rtpbindaddr)) {
  28177. ast_log(LOG_WARNING, "Invalid address for rtpbindaddr keyword: %s\n", v->value);
  28178. }
  28179. } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
  28180. if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
  28181. ast_log(LOG_WARNING,
  28182. "Invalid address for externaddr keyword: %s\n",
  28183. v->value);
  28184. }
  28185. externexpire = 0;
  28186. } else if (!strcasecmp(v->name, "externhost")) {
  28187. ast_copy_string(externhost, v->value, sizeof(externhost));
  28188. if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
  28189. ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
  28190. }
  28191. externexpire = time(NULL);
  28192. } else if (!strcasecmp(v->name, "externrefresh")) {
  28193. if (sscanf(v->value, "%30d", &externrefresh) != 1) {
  28194. ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
  28195. externrefresh = 10;
  28196. }
  28197. } else if (!strcasecmp(v->name, "externtcpport")) {
  28198. if (!(externtcpport = port_str2int(v->value, 0))) {
  28199. ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
  28200. externtcpport = 0;
  28201. }
  28202. } else if (!strcasecmp(v->name, "externtlsport")) {
  28203. if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
  28204. ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
  28205. }
  28206. } else if (!strcasecmp(v->name, "allow")) {
  28207. int error = ast_format_cap_update_by_allow_disallow(sip_cfg.caps, v->value, TRUE);
  28208. if (error) {
  28209. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  28210. }
  28211. } else if (!strcasecmp(v->name, "disallow")) {
  28212. int error = ast_format_cap_update_by_allow_disallow(sip_cfg.caps, v->value, FALSE);
  28213. if (error) {
  28214. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  28215. }
  28216. } else if (!strcasecmp(v->name, "preferred_codec_only")) {
  28217. ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
  28218. } else if (!strcasecmp(v->name, "autoframing")) {
  28219. global_autoframing = ast_true(v->value);
  28220. } else if (!strcasecmp(v->name, "allowexternaldomains")) {
  28221. sip_cfg.allow_external_domains = ast_true(v->value);
  28222. } else if (!strcasecmp(v->name, "autodomain")) {
  28223. auto_sip_domains = ast_true(v->value);
  28224. } else if (!strcasecmp(v->name, "domain")) {
  28225. char *domain = ast_strdupa(v->value);
  28226. char *cntx = strchr(domain, ',');
  28227. if (cntx) {
  28228. *cntx++ = '\0';
  28229. }
  28230. if (ast_strlen_zero(cntx)) {
  28231. ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
  28232. }
  28233. if (ast_strlen_zero(domain)) {
  28234. ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
  28235. } else {
  28236. add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
  28237. }
  28238. } else if (!strcasecmp(v->name, "register")) {
  28239. if (sip_register(v->value, v->lineno) == 0) {
  28240. registry_count++;
  28241. }
  28242. } else if (!strcasecmp(v->name, "mwi")) {
  28243. sip_subscribe_mwi(v->value, v->lineno);
  28244. } else if (!strcasecmp(v->name, "tos_sip")) {
  28245. if (ast_str2tos(v->value, &global_tos_sip)) {
  28246. ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
  28247. }
  28248. } else if (!strcasecmp(v->name, "tos_audio")) {
  28249. if (ast_str2tos(v->value, &global_tos_audio)) {
  28250. ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
  28251. }
  28252. } else if (!strcasecmp(v->name, "tos_video")) {
  28253. if (ast_str2tos(v->value, &global_tos_video)) {
  28254. ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
  28255. }
  28256. } else if (!strcasecmp(v->name, "tos_text")) {
  28257. if (ast_str2tos(v->value, &global_tos_text)) {
  28258. ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
  28259. }
  28260. } else if (!strcasecmp(v->name, "cos_sip")) {
  28261. if (ast_str2cos(v->value, &global_cos_sip)) {
  28262. ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
  28263. }
  28264. } else if (!strcasecmp(v->name, "cos_audio")) {
  28265. if (ast_str2cos(v->value, &global_cos_audio)) {
  28266. ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
  28267. }
  28268. } else if (!strcasecmp(v->name, "cos_video")) {
  28269. if (ast_str2cos(v->value, &global_cos_video)) {
  28270. ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
  28271. }
  28272. } else if (!strcasecmp(v->name, "cos_text")) {
  28273. if (ast_str2cos(v->value, &global_cos_text)) {
  28274. ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
  28275. }
  28276. } else if (!strcasecmp(v->name, "bindport")) {
  28277. if (sscanf(v->value, "%5d", &bindport) != 1) {
  28278. ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
  28279. }
  28280. } else if (!strcasecmp(v->name, "qualify")) {
  28281. if (!strcasecmp(v->value, "no")) {
  28282. default_qualify = 0;
  28283. } else if (!strcasecmp(v->value, "yes")) {
  28284. default_qualify = DEFAULT_MAXMS;
  28285. } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
  28286. ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
  28287. default_qualify = 0;
  28288. }
  28289. } else if (!strcasecmp(v->name, "keepalive")) {
  28290. if (!strcasecmp(v->value, "no")) {
  28291. default_keepalive = 0;
  28292. } else if (!strcasecmp(v->value, "yes")) {
  28293. default_keepalive = DEFAULT_KEEPALIVE_INTERVAL;
  28294. } else if (sscanf(v->value, "%30d", &default_keepalive) != 1) {
  28295. ast_log(LOG_WARNING, "Keep alive default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
  28296. default_keepalive = 0;
  28297. }
  28298. } else if (!strcasecmp(v->name, "qualifyfreq")) {
  28299. int i;
  28300. if (sscanf(v->value, "%30d", &i) == 1) {
  28301. global_qualifyfreq = i * 1000;
  28302. } else {
  28303. ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
  28304. global_qualifyfreq = DEFAULT_QUALIFYFREQ;
  28305. }
  28306. } else if (!strcasecmp(v->name, "authfailureevents")) {
  28307. global_authfailureevents = ast_true(v->value);
  28308. } else if (!strcasecmp(v->name, "maxcallbitrate")) {
  28309. default_maxcallbitrate = atoi(v->value);
  28310. if (default_maxcallbitrate < 0) {
  28311. default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
  28312. }
  28313. } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
  28314. sip_cfg.matchexternaddrlocally = ast_true(v->value);
  28315. } else if (!strcasecmp(v->name, "session-timers")) {
  28316. int i = (int) str2stmode(v->value);
  28317. if (i < 0) {
  28318. ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
  28319. global_st_mode = SESSION_TIMER_MODE_ACCEPT;
  28320. } else {
  28321. global_st_mode = i;
  28322. }
  28323. } else if (!strcasecmp(v->name, "session-expires")) {
  28324. if (sscanf(v->value, "%30d", &global_max_se) != 1) {
  28325. ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
  28326. global_max_se = DEFAULT_MAX_SE;
  28327. }
  28328. } else if (!strcasecmp(v->name, "session-minse")) {
  28329. if (sscanf(v->value, "%30d", &global_min_se) != 1) {
  28330. ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
  28331. global_min_se = DEFAULT_MIN_SE;
  28332. }
  28333. if (global_min_se < DEFAULT_MIN_SE) {
  28334. ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < %d secs\n", v->value, v->lineno, config, DEFAULT_MIN_SE);
  28335. global_min_se = DEFAULT_MIN_SE;
  28336. }
  28337. } else if (!strcasecmp(v->name, "session-refresher")) {
  28338. int i = (int) str2strefresherparam(v->value);
  28339. if (i < 0) {
  28340. ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
  28341. global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
  28342. } else {
  28343. global_st_refresher = i;
  28344. }
  28345. } else if (!strcasecmp(v->name, "storesipcause")) {
  28346. global_store_sip_cause = ast_true(v->value);
  28347. if (global_store_sip_cause) {
  28348. ast_log(LOG_WARNING, "Usage of SIP_CAUSE is deprecated. Please use HANGUPCAUSE instead.\n");
  28349. }
  28350. } else if (!strcasecmp(v->name, "qualifygap")) {
  28351. if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
  28352. ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
  28353. global_qualify_gap = DEFAULT_QUALIFY_GAP;
  28354. }
  28355. } else if (!strcasecmp(v->name, "qualifypeers")) {
  28356. if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
  28357. ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
  28358. global_qualify_peers = DEFAULT_QUALIFY_PEERS;
  28359. }
  28360. } else if (!strcasecmp(v->name, "disallowed_methods")) {
  28361. char *disallow = ast_strdupa(v->value);
  28362. mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
  28363. } else if (!strcasecmp(v->name, "shrinkcallerid")) {
  28364. if (ast_true(v->value)) {
  28365. global_shrinkcallerid = 1;
  28366. } else if (ast_false(v->value)) {
  28367. global_shrinkcallerid = 0;
  28368. } else {
  28369. ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
  28370. }
  28371. } else if (!strcasecmp(v->name, "use_q850_reason")) {
  28372. ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
  28373. } else if (!strcasecmp(v->name, "maxforwards")) {
  28374. if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
  28375. || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
  28376. ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
  28377. sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
  28378. }
  28379. } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
  28380. if (ast_true(v->value)) {
  28381. subscribe_network_change = 1;
  28382. } else if (ast_false(v->value)) {
  28383. subscribe_network_change = 0;
  28384. } else {
  28385. ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
  28386. }
  28387. } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
  28388. ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
  28389. } else if (!strcasecmp(v->name, "icesupport")) {
  28390. ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_ICE_SUPPORT);
  28391. } else if (!strcasecmp(v->name, "discard_remote_hold_retrieval")) {
  28392. ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_DISCARD_REMOTE_HOLD_RETRIEVAL);
  28393. } else if (!strcasecmp(v->name, "parkinglot")) {
  28394. ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
  28395. } else if (!strcasecmp(v->name, "refer_addheaders")) {
  28396. global_refer_addheaders = ast_true(v->value);
  28397. } else if (!strcasecmp(v->name, "websocket_write_timeout")) {
  28398. if (sscanf(v->value, "%30d", &sip_cfg.websocket_write_timeout) != 1
  28399. || sip_cfg.websocket_write_timeout < 0) {
  28400. ast_log(LOG_WARNING, "'%s' is not a valid websocket_write_timeout value at line %d. Using default '%d'.\n", v->value, v->lineno, AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT);
  28401. sip_cfg.websocket_write_timeout = AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT;
  28402. }
  28403. }
  28404. }
  28405. /* Override global defaults if setting found in general section */
  28406. ast_copy_flags(&global_flags[0], &setflags[0], mask[0].flags);
  28407. ast_copy_flags(&global_flags[1], &setflags[1], mask[1].flags);
  28408. ast_copy_flags(&global_flags[2], &setflags[2], mask[2].flags);
  28409. /* For backwards compatibility the corresponding registration timer value is used if subscription timer value isn't set by configuration */
  28410. if (!min_subexpiry_set) {
  28411. min_subexpiry = min_expiry;
  28412. }
  28413. if (!max_subexpiry_set) {
  28414. max_subexpiry = max_expiry;
  28415. }
  28416. if (reason != CHANNEL_MODULE_LOAD && sip_cfg.autocreatepeer != AUTOPEERS_PERSIST) {
  28417. ao2_t_callback(peers, OBJ_NODATA, peer_markall_autopeers_func, NULL, "callback to mark autopeers for destruction");
  28418. }
  28419. if (subscribe_network_change) {
  28420. network_change_stasis_subscribe();
  28421. } else {
  28422. network_change_stasis_unsubscribe();
  28423. }
  28424. if (global_t1 < global_t1min) {
  28425. ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d). Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
  28426. global_t1 = global_t1min;
  28427. }
  28428. if (global_timer_b < global_t1 * 64) {
  28429. if (timerb_set && timert1_set) {
  28430. ast_log(LOG_WARNING, "Timer B has been set lower than recommended (%d < 64 * timert1=%d). (RFC 3261, 17.1.1.2)\n", global_timer_b, global_t1);
  28431. } else if (timerb_set) {
  28432. if ((global_t1 = global_timer_b / 64) < global_t1min) {
  28433. ast_log(LOG_WARNING, "Timer B has been set lower than recommended (%d < 64 * timert1=%d). (RFC 3261, 17.1.1.2)\n", global_timer_b, global_t1);
  28434. global_t1 = global_t1min;
  28435. global_timer_b = global_t1 * 64;
  28436. }
  28437. } else {
  28438. global_timer_b = global_t1 * 64;
  28439. }
  28440. }
  28441. if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
  28442. ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
  28443. sip_cfg.allow_external_domains = 1;
  28444. }
  28445. /* If not or badly configured, set default transports */
  28446. if (!sip_cfg.tcp_enabled && (default_transports & AST_TRANSPORT_TCP)) {
  28447. ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
  28448. default_primary_transport &= ~AST_TRANSPORT_TCP;
  28449. default_transports &= ~AST_TRANSPORT_TCP;
  28450. }
  28451. if (!default_tls_cfg.enabled && (default_transports & AST_TRANSPORT_TLS)) {
  28452. ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
  28453. default_primary_transport &= ~AST_TRANSPORT_TLS;
  28454. default_transports &= ~AST_TRANSPORT_TLS;
  28455. }
  28456. if (!default_transports) {
  28457. ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
  28458. default_transports = default_primary_transport = AST_TRANSPORT_UDP;
  28459. } else if (!default_primary_transport) {
  28460. ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
  28461. default_primary_transport = AST_TRANSPORT_UDP;
  28462. }
  28463. /* Build list of authentication to various SIP realms, i.e. service providers */
  28464. for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
  28465. /* Format for authentication is auth = username:password@realm */
  28466. if (!strcasecmp(v->name, "auth")) {
  28467. add_realm_authentication(&authl, v->value, v->lineno);
  28468. }
  28469. }
  28470. if (bindport) {
  28471. if (ast_sockaddr_port(&bindaddr)) {
  28472. ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
  28473. "Using %d.\n", bindport);
  28474. }
  28475. ast_sockaddr_set_port(&bindaddr, bindport);
  28476. }
  28477. if (!ast_sockaddr_port(&bindaddr)) {
  28478. ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
  28479. }
  28480. /* Set UDP address and open socket */
  28481. ast_sockaddr_copy(&internip, &bindaddr);
  28482. if (ast_find_ourip(&internip, &bindaddr, 0)) {
  28483. ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
  28484. ast_config_destroy(cfg);
  28485. return 0;
  28486. }
  28487. ast_mutex_lock(&netlock);
  28488. if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
  28489. close(sipsock);
  28490. sipsock = -1;
  28491. }
  28492. if (sipsock < 0) {
  28493. sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
  28494. AF_INET6 : AF_INET, SOCK_DGRAM, 0);
  28495. if (sipsock < 0) {
  28496. ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
  28497. ast_config_destroy(cfg);
  28498. ast_mutex_unlock(&netlock);
  28499. return -1;
  28500. } else {
  28501. /* Allow SIP clients on the same host to access us: */
  28502. const int reuseFlag = 1;
  28503. setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
  28504. (const char*)&reuseFlag,
  28505. sizeof reuseFlag);
  28506. ast_enable_packet_fragmentation(sipsock);
  28507. if (ast_bind(sipsock, &bindaddr) < 0) {
  28508. ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
  28509. ast_sockaddr_stringify(&bindaddr), strerror(errno));
  28510. close(sipsock);
  28511. sipsock = -1;
  28512. } else {
  28513. ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
  28514. ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
  28515. }
  28516. }
  28517. } else {
  28518. ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
  28519. }
  28520. ast_mutex_unlock(&netlock);
  28521. /* Start TCP server */
  28522. if (sip_cfg.tcp_enabled) {
  28523. if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
  28524. ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
  28525. }
  28526. if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
  28527. ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
  28528. }
  28529. } else {
  28530. ast_sockaddr_setnull(&sip_tcp_desc.local_address);
  28531. }
  28532. ast_tcptls_server_start(&sip_tcp_desc);
  28533. if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
  28534. /* TCP server start failed. Tell the admin */
  28535. ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
  28536. } else {
  28537. ast_debug(2, "SIP TCP server started\n");
  28538. }
  28539. /* Start TLS server if needed */
  28540. memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
  28541. if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
  28542. if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
  28543. ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
  28544. ast_sockaddr_set_port(&sip_tls_desc.local_address,
  28545. STANDARD_TLS_PORT);
  28546. }
  28547. if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
  28548. ast_sockaddr_set_port(&sip_tls_desc.local_address,
  28549. STANDARD_TLS_PORT);
  28550. }
  28551. ast_tcptls_server_start(&sip_tls_desc);
  28552. if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
  28553. ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
  28554. sip_tls_desc.tls_cfg = NULL;
  28555. }
  28556. } else if (sip_tls_desc.tls_cfg->enabled) {
  28557. sip_tls_desc.tls_cfg = NULL;
  28558. ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
  28559. }
  28560. if (ucfg) {
  28561. struct ast_variable *gen;
  28562. int genhassip, genregistersip;
  28563. const char *hassip, *registersip;
  28564. genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
  28565. genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
  28566. gen = ast_variable_browse(ucfg, "general");
  28567. cat = ast_category_browse(ucfg, NULL);
  28568. while (cat) {
  28569. if (strcasecmp(cat, "general")) {
  28570. hassip = ast_variable_retrieve(ucfg, cat, "hassip");
  28571. registersip = ast_variable_retrieve(ucfg, cat, "registersip");
  28572. if (ast_true(hassip) || (!hassip && genhassip)) {
  28573. peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
  28574. if (peer) {
  28575. /* user.conf entries are always of type friend */
  28576. peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
  28577. ao2_t_link(peers, peer, "link peer into peer table");
  28578. if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
  28579. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  28580. }
  28581. sip_unref_peer(peer, "sip_unref_peer: from reload_config");
  28582. peer_count++;
  28583. }
  28584. }
  28585. if (ast_true(registersip) || (!registersip && genregistersip)) {
  28586. char tmp[256];
  28587. const char *host = ast_variable_retrieve(ucfg, cat, "host");
  28588. const char *username = ast_variable_retrieve(ucfg, cat, "username");
  28589. const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
  28590. const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
  28591. const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
  28592. if (!host) {
  28593. host = ast_variable_retrieve(ucfg, "general", "host");
  28594. }
  28595. if (!username) {
  28596. username = ast_variable_retrieve(ucfg, "general", "username");
  28597. }
  28598. if (!secret) {
  28599. secret = ast_variable_retrieve(ucfg, "general", "secret");
  28600. }
  28601. if (!contact) {
  28602. contact = "s";
  28603. }
  28604. if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
  28605. if (!ast_strlen_zero(secret)) {
  28606. if (!ast_strlen_zero(authuser)) {
  28607. snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
  28608. } else {
  28609. snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
  28610. }
  28611. } else if (!ast_strlen_zero(authuser)) {
  28612. snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
  28613. } else {
  28614. snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
  28615. }
  28616. if (sip_register(tmp, 0) == 0) {
  28617. registry_count++;
  28618. }
  28619. }
  28620. }
  28621. }
  28622. cat = ast_category_browse(ucfg, cat);
  28623. }
  28624. ast_config_destroy(ucfg);
  28625. }
  28626. /* Load peers, users and friends */
  28627. cat = NULL;
  28628. while ( (cat = ast_category_browse(cfg, cat)) ) {
  28629. const char *utype;
  28630. if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
  28631. continue;
  28632. utype = ast_variable_retrieve(cfg, cat, "type");
  28633. if (!utype) {
  28634. ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
  28635. continue;
  28636. } else {
  28637. if (!strcasecmp(utype, "user")) {
  28638. ;
  28639. } else if (!strcasecmp(utype, "friend")) {
  28640. ;
  28641. } else if (!strcasecmp(utype, "peer")) {
  28642. ;
  28643. } else {
  28644. ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
  28645. continue;
  28646. }
  28647. peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
  28648. if (peer) {
  28649. display_nat_warning(cat, reason, &peer->flags[0]);
  28650. ao2_t_link(peers, peer, "link peer into peers table");
  28651. if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
  28652. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  28653. }
  28654. sip_unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
  28655. peer_count++;
  28656. }
  28657. }
  28658. }
  28659. /* Add default domains - host name, IP address and IP:port
  28660. * Only do this if user added any sip domain with "localdomains"
  28661. * In order to *not* break backwards compatibility
  28662. * Some phones address us at IP only, some with additional port number
  28663. */
  28664. if (auto_sip_domains) {
  28665. char temp[MAXHOSTNAMELEN];
  28666. /* First our default IP address */
  28667. if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
  28668. add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
  28669. SIP_DOMAIN_AUTO, NULL);
  28670. } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
  28671. /* Our internal IP address, if configured */
  28672. add_sip_domain(ast_sockaddr_stringify_addr(&internip),
  28673. SIP_DOMAIN_AUTO, NULL);
  28674. } else {
  28675. ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
  28676. }
  28677. /* If TCP is running on a different IP than UDP, then add it too */
  28678. if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
  28679. !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
  28680. add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
  28681. SIP_DOMAIN_AUTO, NULL);
  28682. }
  28683. /* If TLS is running on a different IP than UDP and TCP, then add that too */
  28684. if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
  28685. !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
  28686. !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
  28687. &sip_tls_desc.local_address)) {
  28688. add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
  28689. SIP_DOMAIN_AUTO, NULL);
  28690. }
  28691. /* Our extern IP address, if configured */
  28692. if (!ast_sockaddr_isnull(&externaddr)) {
  28693. add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
  28694. SIP_DOMAIN_AUTO, NULL);
  28695. }
  28696. /* Extern host name (NAT traversal support) */
  28697. if (!ast_strlen_zero(externhost)) {
  28698. add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
  28699. }
  28700. /* Our host name */
  28701. if (!gethostname(temp, sizeof(temp))) {
  28702. add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
  28703. }
  28704. }
  28705. /* Release configuration from memory */
  28706. ast_config_destroy(cfg);
  28707. register_realtime_peers_with_callbackextens();
  28708. /* Load the list of manual NOTIFY types to support */
  28709. if (notify_types) {
  28710. ast_config_destroy(notify_types);
  28711. }
  28712. if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
  28713. ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
  28714. notify_types = NULL;
  28715. }
  28716. run_end = time(0);
  28717. ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
  28718. /* If an ACL change subscription is needed and doesn't exist, we need one. */
  28719. if (acl_change_subscription_needed) {
  28720. acl_change_stasis_subscribe();
  28721. }
  28722. return 0;
  28723. }
  28724. static int sip_allow_anyrtp_remote(struct ast_channel *chan1, struct ast_rtp_instance *instance, const char *rtptype)
  28725. {
  28726. struct sip_pvt *p;
  28727. struct ast_acl_list *acl = NULL;
  28728. int res = 1;
  28729. if (!(p = ast_channel_tech_pvt(chan1))) {
  28730. return 0;
  28731. }
  28732. sip_pvt_lock(p);
  28733. if (p->relatedpeer && p->relatedpeer->directmediaacl) {
  28734. acl = ast_duplicate_acl_list(p->relatedpeer->directmediaacl);
  28735. }
  28736. sip_pvt_unlock(p);
  28737. if (!acl) {
  28738. return res;
  28739. }
  28740. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  28741. struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
  28742. ast_rtp_instance_get_requested_target_address(instance, &them);
  28743. ast_rtp_instance_get_local_address(instance, &us);
  28744. if (ast_apply_acl(acl, &them, "SIP Direct Media ACL: ") == AST_SENSE_DENY) {
  28745. const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
  28746. const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
  28747. ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
  28748. rtptype, them_addr, us_addr);
  28749. res = 0;
  28750. }
  28751. }
  28752. ast_free_acl_list(acl);
  28753. return res;
  28754. }
  28755. static int sip_allow_rtp_remote(struct ast_channel *chan1, struct ast_rtp_instance *instance)
  28756. {
  28757. return sip_allow_anyrtp_remote(chan1, instance, "audio");
  28758. }
  28759. static int sip_allow_vrtp_remote(struct ast_channel *chan1, struct ast_rtp_instance *instance)
  28760. {
  28761. return sip_allow_anyrtp_remote(chan1, instance, "video");
  28762. }
  28763. static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
  28764. {
  28765. struct sip_pvt *p = NULL;
  28766. enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
  28767. if (!(p = ast_channel_tech_pvt(chan))) {
  28768. return AST_RTP_GLUE_RESULT_FORBID;
  28769. }
  28770. sip_pvt_lock(p);
  28771. if (!(p->rtp)) {
  28772. sip_pvt_unlock(p);
  28773. return AST_RTP_GLUE_RESULT_FORBID;
  28774. }
  28775. ao2_ref(p->rtp, +1);
  28776. *instance = p->rtp;
  28777. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  28778. res = AST_RTP_GLUE_RESULT_REMOTE;
  28779. } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
  28780. res = AST_RTP_GLUE_RESULT_REMOTE;
  28781. } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
  28782. res = AST_RTP_GLUE_RESULT_FORBID;
  28783. }
  28784. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
  28785. switch (p->t38.state) {
  28786. case T38_LOCAL_REINVITE:
  28787. case T38_PEER_REINVITE:
  28788. case T38_ENABLED:
  28789. res = AST_RTP_GLUE_RESULT_LOCAL;
  28790. break;
  28791. case T38_REJECTED:
  28792. default:
  28793. break;
  28794. }
  28795. }
  28796. if (p->srtp) {
  28797. res = AST_RTP_GLUE_RESULT_FORBID;
  28798. }
  28799. sip_pvt_unlock(p);
  28800. return res;
  28801. }
  28802. static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
  28803. {
  28804. struct sip_pvt *p = NULL;
  28805. enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
  28806. if (!(p = ast_channel_tech_pvt(chan))) {
  28807. return AST_RTP_GLUE_RESULT_FORBID;
  28808. }
  28809. sip_pvt_lock(p);
  28810. if (!(p->vrtp)) {
  28811. sip_pvt_unlock(p);
  28812. return AST_RTP_GLUE_RESULT_FORBID;
  28813. }
  28814. ao2_ref(p->vrtp, +1);
  28815. *instance = p->vrtp;
  28816. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  28817. res = AST_RTP_GLUE_RESULT_REMOTE;
  28818. }
  28819. sip_pvt_unlock(p);
  28820. return res;
  28821. }
  28822. static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
  28823. {
  28824. struct sip_pvt *p = NULL;
  28825. enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
  28826. if (!(p = ast_channel_tech_pvt(chan))) {
  28827. return AST_RTP_GLUE_RESULT_FORBID;
  28828. }
  28829. sip_pvt_lock(p);
  28830. if (!(p->trtp)) {
  28831. sip_pvt_unlock(p);
  28832. return AST_RTP_GLUE_RESULT_FORBID;
  28833. }
  28834. ao2_ref(p->trtp, +1);
  28835. *instance = p->trtp;
  28836. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  28837. res = AST_RTP_GLUE_RESULT_REMOTE;
  28838. }
  28839. sip_pvt_unlock(p);
  28840. return res;
  28841. }
  28842. static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active)
  28843. {
  28844. struct sip_pvt *p;
  28845. int changed = 0;
  28846. p = ast_channel_tech_pvt(chan);
  28847. if (!p) {
  28848. return -1;
  28849. }
  28850. sip_pvt_lock(p);
  28851. if (p->owner != chan) {
  28852. /* I suppose it could be argued that if this happens it is a bug. */
  28853. ast_debug(1, "The private is not owned by channel %s anymore.\n", ast_channel_name(chan));
  28854. sip_pvt_unlock(p);
  28855. return 0;
  28856. }
  28857. /* Disable early RTP bridge */
  28858. if ((instance || vinstance || tinstance) &&
  28859. !ast_channel_is_bridged(chan) &&
  28860. !sip_cfg.directrtpsetup) {
  28861. sip_pvt_unlock(p);
  28862. return 0;
  28863. }
  28864. if (p->alreadygone) {
  28865. /* If we're destroyed, don't bother */
  28866. sip_pvt_unlock(p);
  28867. return 0;
  28868. }
  28869. /* if this peer cannot handle reinvites of the media stream to devices
  28870. that are known to be behind a NAT, then stop the process now
  28871. */
  28872. if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
  28873. sip_pvt_unlock(p);
  28874. return 0;
  28875. }
  28876. if (instance) {
  28877. changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
  28878. if (p->rtp) {
  28879. /* Prevent audio RTCP reads */
  28880. ast_channel_set_fd(chan, 1, -1);
  28881. /* Silence RTCP while audio RTP is inactive */
  28882. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
  28883. }
  28884. } else if (!ast_sockaddr_isnull(&p->redirip)) {
  28885. memset(&p->redirip, 0, sizeof(p->redirip));
  28886. changed = 1;
  28887. if (p->rtp) {
  28888. /* Enable RTCP since it will be inactive if we're coming back
  28889. * from a reinvite */
  28890. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
  28891. /* Enable audio RTCP reads */
  28892. ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
  28893. }
  28894. }
  28895. if (vinstance) {
  28896. changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
  28897. if (p->vrtp) {
  28898. /* Prevent video RTCP reads */
  28899. ast_channel_set_fd(chan, 3, -1);
  28900. /* Silence RTCP while video RTP is inactive */
  28901. ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
  28902. }
  28903. } else if (!ast_sockaddr_isnull(&p->vredirip)) {
  28904. memset(&p->vredirip, 0, sizeof(p->vredirip));
  28905. changed = 1;
  28906. if (p->vrtp) {
  28907. /* Enable RTCP since it will be inactive if we're coming back
  28908. * from a reinvite */
  28909. ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
  28910. /* Enable video RTCP reads */
  28911. ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
  28912. }
  28913. }
  28914. if (tinstance) {
  28915. changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
  28916. } else if (!ast_sockaddr_isnull(&p->tredirip)) {
  28917. memset(&p->tredirip, 0, sizeof(p->tredirip));
  28918. changed = 1;
  28919. }
  28920. if (cap && ast_format_cap_count(cap) && !ast_format_cap_identical(cap, p->redircaps)) {
  28921. ast_format_cap_remove_by_type(p->redircaps, AST_MEDIA_TYPE_UNKNOWN);
  28922. ast_format_cap_append_from_cap(p->redircaps, cap, AST_MEDIA_TYPE_UNKNOWN);
  28923. changed = 1;
  28924. }
  28925. if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
  28926. /* We only wish to withhold sending the initial direct media reinvite on the incoming dialog.
  28927. * Further direct media reinvites beyond the initial should be sent. In order to allow further
  28928. * direct media reinvites to be sent, we clear this flag.
  28929. */
  28930. ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
  28931. sip_pvt_unlock(p);
  28932. return 0;
  28933. }
  28934. if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
  28935. if (ast_channel_state(chan) != AST_STATE_UP) { /* We are in early state */
  28936. if (p->do_history)
  28937. append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
  28938. ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
  28939. } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
  28940. ast_debug(3, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
  28941. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  28942. } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  28943. ast_debug(3, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
  28944. /* We have a pending Invite. Send re-invite when we're done with the invite */
  28945. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  28946. }
  28947. }
  28948. /* Reset lastrtprx timer */
  28949. p->lastrtprx = p->lastrtptx = time(NULL);
  28950. sip_pvt_unlock(p);
  28951. return 0;
  28952. }
  28953. static void sip_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
  28954. {
  28955. struct sip_pvt *p = ast_channel_tech_pvt(chan);
  28956. ast_format_cap_append_from_cap(result, !ast_format_cap_count(p->peercaps) ? p->caps : p->peercaps, AST_MEDIA_TYPE_UNKNOWN);
  28957. }
  28958. static struct ast_rtp_glue sip_rtp_glue = {
  28959. .type = "SIP",
  28960. .get_rtp_info = sip_get_rtp_peer,
  28961. .allow_rtp_remote = sip_allow_rtp_remote,
  28962. .get_vrtp_info = sip_get_vrtp_peer,
  28963. .allow_vrtp_remote = sip_allow_vrtp_remote,
  28964. .get_trtp_info = sip_get_trtp_peer,
  28965. .update_peer = sip_set_rtp_peer,
  28966. .get_codec = sip_get_codec,
  28967. };
  28968. static char *app_dtmfmode = "SIPDtmfMode";
  28969. static char *app_sipaddheader = "SIPAddHeader";
  28970. static char *app_sipremoveheader = "SIPRemoveHeader";
  28971. #ifdef TEST_FRAMEWORK
  28972. static char *app_sipsendcustominfo = "SIPSendCustomINFO";
  28973. #endif
  28974. /*! \brief Set the DTMFmode for an outbound SIP call (application) */
  28975. static int sip_dtmfmode(struct ast_channel *chan, const char *data)
  28976. {
  28977. struct sip_pvt *p;
  28978. const char *mode = data;
  28979. if (!data) {
  28980. ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
  28981. return 0;
  28982. }
  28983. ast_channel_lock(chan);
  28984. if (!IS_SIP_TECH(ast_channel_tech(chan))) {
  28985. ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
  28986. ast_channel_unlock(chan);
  28987. return 0;
  28988. }
  28989. p = ast_channel_tech_pvt(chan);
  28990. if (!p) {
  28991. ast_channel_unlock(chan);
  28992. return 0;
  28993. }
  28994. sip_pvt_lock(p);
  28995. if (!strcasecmp(mode, "info")) {
  28996. ast_clear_flag(&p->flags[0], SIP_DTMF);
  28997. ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
  28998. p->jointnoncodeccapability &= ~AST_RTP_DTMF;
  28999. } else if (!strcasecmp(mode, "shortinfo")) {
  29000. ast_clear_flag(&p->flags[0], SIP_DTMF);
  29001. ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
  29002. p->jointnoncodeccapability &= ~AST_RTP_DTMF;
  29003. } else if (!strcasecmp(mode, "rfc2833")) {
  29004. ast_clear_flag(&p->flags[0], SIP_DTMF);
  29005. ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
  29006. p->jointnoncodeccapability |= AST_RTP_DTMF;
  29007. } else if (!strcasecmp(mode, "inband")) {
  29008. ast_clear_flag(&p->flags[0], SIP_DTMF);
  29009. ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
  29010. p->jointnoncodeccapability &= ~AST_RTP_DTMF;
  29011. } else {
  29012. ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
  29013. }
  29014. if (p->rtp)
  29015. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  29016. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  29017. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  29018. enable_dsp_detect(p);
  29019. } else {
  29020. disable_dsp_detect(p);
  29021. }
  29022. sip_pvt_unlock(p);
  29023. ast_channel_unlock(chan);
  29024. return 0;
  29025. }
  29026. /*! \brief Add a SIP header to an outbound INVITE */
  29027. static int sip_addheader(struct ast_channel *chan, const char *data)
  29028. {
  29029. int no = 0;
  29030. int ok = FALSE;
  29031. char varbuf[30];
  29032. const char *inbuf = data;
  29033. char *subbuf;
  29034. if (ast_strlen_zero(inbuf)) {
  29035. ast_log(LOG_WARNING, "This application requires the argument: Header\n");
  29036. return 0;
  29037. }
  29038. ast_channel_lock(chan);
  29039. /* Check for headers */
  29040. while (!ok && no <= 50) {
  29041. no++;
  29042. snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
  29043. /* Compare without the leading underscores */
  29044. if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
  29045. ok = TRUE;
  29046. }
  29047. }
  29048. if (ok) {
  29049. size_t len = strlen(inbuf);
  29050. subbuf = ast_alloca(len + 1);
  29051. ast_get_encoded_str(inbuf, subbuf, len + 1);
  29052. pbx_builtin_setvar_helper(chan, varbuf, subbuf);
  29053. if (sipdebug) {
  29054. ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
  29055. }
  29056. } else {
  29057. ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
  29058. }
  29059. ast_channel_unlock(chan);
  29060. return 0;
  29061. }
  29062. /*! \brief Remove SIP headers added previously with SipAddHeader application */
  29063. static int sip_removeheader(struct ast_channel *chan, const char *data)
  29064. {
  29065. struct ast_var_t *newvariable;
  29066. struct varshead *headp;
  29067. int removeall = 0;
  29068. char *inbuf = (char *) data;
  29069. if (ast_strlen_zero(inbuf)) {
  29070. removeall = 1;
  29071. }
  29072. ast_channel_lock(chan);
  29073. headp=ast_channel_varshead(chan);
  29074. AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
  29075. if (strncmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
  29076. if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
  29077. if (sipdebug) {
  29078. ast_debug(1,"removing SIP Header \"%s\" as %s\n",
  29079. ast_var_value(newvariable),
  29080. ast_var_name(newvariable));
  29081. }
  29082. AST_LIST_REMOVE_CURRENT(entries);
  29083. ast_var_delete(newvariable);
  29084. }
  29085. }
  29086. }
  29087. AST_LIST_TRAVERSE_SAFE_END;
  29088. ast_channel_unlock(chan);
  29089. return 0;
  29090. }
  29091. #ifdef TEST_FRAMEWORK
  29092. /*! \brief Send a custom INFO message via AST_CONTROL_CUSTOM indication */
  29093. static int sip_sendcustominfo(struct ast_channel *chan, const char *data)
  29094. {
  29095. char *info_data, *useragent;
  29096. if (ast_strlen_zero(data)) {
  29097. ast_log(LOG_WARNING, "You must provide data to be sent\n");
  29098. return 0;
  29099. }
  29100. useragent = ast_strdupa(data);
  29101. info_data = strsep(&useragent, ",");
  29102. if (ast_sipinfo_send(chan, NULL, "text/plain", info_data, useragent)) {
  29103. ast_log(LOG_WARNING, "Failed to create payload for custom SIP INFO\n");
  29104. return 0;
  29105. }
  29106. return 0;
  29107. }
  29108. #endif
  29109. /*! \brief Transfer call before connect with a 302 redirect
  29110. \note Called by the transfer() dialplan application through the sip_transfer()
  29111. pbx interface function if the call is in ringing state
  29112. \todo Fix this function so that we wait for reply to the REFER and
  29113. react to errors, denials or other issues the other end might have.
  29114. */
  29115. static int sip_sipredirect(struct sip_pvt *p, const char *dest)
  29116. {
  29117. char *cdest;
  29118. char *extension, *domain;
  29119. cdest = ast_strdupa(dest);
  29120. extension = strsep(&cdest, "@");
  29121. domain = cdest;
  29122. if (ast_strlen_zero(extension)) {
  29123. ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
  29124. return 0;
  29125. }
  29126. /* we'll issue the redirect message here */
  29127. if (!domain) {
  29128. char *local_to_header;
  29129. char to_header[256];
  29130. ast_copy_string(to_header, sip_get_header(&p->initreq, "To"), sizeof(to_header));
  29131. if (ast_strlen_zero(to_header)) {
  29132. ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
  29133. return 0;
  29134. }
  29135. if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
  29136. && (local_to_header = strchr(local_to_header, '@'))) {
  29137. char ldomain[256];
  29138. memset(ldomain, 0, sizeof(ldomain));
  29139. local_to_header++;
  29140. /* This is okey because lhost and lport are as big as tmp */
  29141. sscanf(local_to_header, "%256[^<>; ]", ldomain);
  29142. if (ast_strlen_zero(ldomain)) {
  29143. ast_log(LOG_ERROR, "Can't find the host address\n");
  29144. return 0;
  29145. }
  29146. domain = ast_strdupa(ldomain);
  29147. }
  29148. }
  29149. ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
  29150. transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
  29151. sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Make sure we stop send this reply. */
  29152. sip_alreadygone(p);
  29153. if (p->owner) {
  29154. enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
  29155. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  29156. }
  29157. /* hangup here */
  29158. return 0;
  29159. }
  29160. static int sip_is_xml_parsable(void)
  29161. {
  29162. #ifdef HAVE_LIBXML2
  29163. return TRUE;
  29164. #else
  29165. return FALSE;
  29166. #endif
  29167. }
  29168. /*! \brief Send a poke to all known peers */
  29169. static void sip_poke_all_peers(void)
  29170. {
  29171. int ms = 0, num = 0;
  29172. struct ao2_iterator i;
  29173. struct sip_peer *peer;
  29174. if (!speerobjs) { /* No peers, just give up */
  29175. return;
  29176. }
  29177. i = ao2_iterator_init(peers, 0);
  29178. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  29179. ao2_lock(peer);
  29180. /* Don't schedule poking on a peer without qualify */
  29181. if (peer->maxms) {
  29182. if (num == global_qualify_peers) {
  29183. ms += global_qualify_gap;
  29184. num = 0;
  29185. } else {
  29186. num++;
  29187. }
  29188. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
  29189. sip_unref_peer(_data, "removing poke peer ref"),
  29190. sip_unref_peer(peer, "removing poke peer ref"),
  29191. sip_ref_peer(peer, "adding poke peer ref"));
  29192. }
  29193. ao2_unlock(peer);
  29194. sip_unref_peer(peer, "toss iterator peer ptr");
  29195. }
  29196. ao2_iterator_destroy(&i);
  29197. }
  29198. /*! \brief Send a keepalive to all known peers */
  29199. static void sip_keepalive_all_peers(void)
  29200. {
  29201. struct ao2_iterator i;
  29202. struct sip_peer *peer;
  29203. if (!speerobjs) { /* No peers, just give up */
  29204. return;
  29205. }
  29206. i = ao2_iterator_init(peers, 0);
  29207. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  29208. ao2_lock(peer);
  29209. AST_SCHED_REPLACE_UNREF(peer->keepalivesend, sched, 0, sip_send_keepalive, peer,
  29210. sip_unref_peer(_data, "removing poke peer ref"),
  29211. sip_unref_peer(peer, "removing poke peer ref"),
  29212. sip_ref_peer(peer, "adding poke peer ref"));
  29213. ao2_unlock(peer);
  29214. sip_unref_peer(peer, "toss iterator peer ptr");
  29215. }
  29216. ao2_iterator_destroy(&i);
  29217. }
  29218. /*! \brief Send all known registrations */
  29219. static void sip_send_all_registers(void)
  29220. {
  29221. int ms;
  29222. int regspacing;
  29223. struct ao2_iterator iter;
  29224. struct sip_registry *iterator;
  29225. if (!ao2_container_count(registry_list)) {
  29226. return;
  29227. }
  29228. regspacing = default_expiry * 1000 / ao2_container_count(registry_list);
  29229. if (regspacing > 100) {
  29230. regspacing = 100;
  29231. }
  29232. ms = regspacing;
  29233. iter = ao2_iterator_init(registry_list, 0);
  29234. while ((iterator = ao2_t_iterator_next(&iter, "sip_send_all_registers iter"))) {
  29235. ao2_lock(iterator);
  29236. ms += regspacing;
  29237. AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
  29238. ao2_t_ref(_data, -1, "REPLACE sched del decs the refcount"),
  29239. ao2_t_ref(iterator, -1, "REPLACE sched add failure decs the refcount"),
  29240. ao2_t_ref(iterator, +1, "REPLACE sched add incs the refcount"));
  29241. ao2_unlock(iterator);
  29242. ao2_t_ref(iterator, -1, "sip_send_all_registers iter");
  29243. }
  29244. ao2_iterator_destroy(&iter);
  29245. }
  29246. /*! \brief Send all MWI subscriptions */
  29247. static void sip_send_all_mwi_subscriptions(void)
  29248. {
  29249. struct ao2_iterator iter;
  29250. struct sip_subscription_mwi *iterator;
  29251. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29252. while ((iterator = ao2_t_iterator_next(&iter, "sip_send_all_mwi_subscriptions iter"))) {
  29253. ao2_lock(iterator);
  29254. AST_SCHED_DEL(sched, iterator->resub);
  29255. ao2_t_ref(iterator, +1, "mwi added to schedule");
  29256. if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, iterator)) < 0) {
  29257. ao2_t_ref(iterator, -1, "mwi failed to schedule");
  29258. }
  29259. ao2_unlock(iterator);
  29260. ao2_t_ref(iterator, -1, "sip_send_all_mwi_subscriptions iter");
  29261. }
  29262. ao2_iterator_destroy(&iter);
  29263. }
  29264. static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp, const char *a)
  29265. {
  29266. struct ast_rtp_engine_dtls *dtls;
  29267. /* If no RTP instance exists for this media stream don't bother processing the crypto line */
  29268. if (!rtp) {
  29269. ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
  29270. return FALSE;
  29271. }
  29272. if (strncasecmp(a, "crypto:", 7)) {
  29273. return FALSE;
  29274. }
  29275. /* skip "crypto:" */
  29276. a += strlen("crypto:");
  29277. if (!*srtp) {
  29278. if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  29279. ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
  29280. return FALSE;
  29281. }
  29282. if (!(*srtp = ast_sdp_srtp_alloc())) {
  29283. return FALSE;
  29284. }
  29285. }
  29286. if (!(*srtp)->crypto && !((*srtp)->crypto = ast_sdp_crypto_alloc())) {
  29287. return FALSE;
  29288. }
  29289. if (ast_sdp_crypto_process(rtp, *srtp, a) < 0) {
  29290. return FALSE;
  29291. }
  29292. if ((dtls = ast_rtp_instance_get_dtls(rtp))) {
  29293. dtls->stop(rtp);
  29294. p->dtls_cfg.enabled = 0;
  29295. }
  29296. return TRUE;
  29297. }
  29298. /*! \brief Reload module */
  29299. static int sip_do_reload(enum channelreloadreason reason)
  29300. {
  29301. time_t start_poke, end_poke;
  29302. reload_config(reason);
  29303. ast_sched_dump(sched);
  29304. start_poke = time(0);
  29305. /* Prune peers who still are supposed to be deleted */
  29306. unlink_marked_peers_from_tables();
  29307. ast_debug(4, "--------------- Done destroying pruned peers\n");
  29308. /* Send qualify (OPTIONS) to all peers */
  29309. sip_poke_all_peers();
  29310. /* Send keepalive to all peers */
  29311. sip_keepalive_all_peers();
  29312. /* Register with all services */
  29313. sip_send_all_registers();
  29314. sip_send_all_mwi_subscriptions();
  29315. end_poke = time(0);
  29316. ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
  29317. ast_debug(4, "--------------- SIP reload done\n");
  29318. return 0;
  29319. }
  29320. /*! \brief Force reload of module from cli */
  29321. static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  29322. {
  29323. static struct sip_peer *tmp_peer, *new_peer;
  29324. switch (cmd) {
  29325. case CLI_INIT:
  29326. e->command = "sip reload";
  29327. e->usage =
  29328. "Usage: sip reload\n"
  29329. " Reloads SIP configuration from sip.conf\n";
  29330. return NULL;
  29331. case CLI_GENERATE:
  29332. return NULL;
  29333. }
  29334. ast_mutex_lock(&sip_reload_lock);
  29335. if (sip_reloading) {
  29336. ast_verbose("Previous SIP reload not yet done\n");
  29337. } else {
  29338. sip_reloading = TRUE;
  29339. sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
  29340. }
  29341. ast_mutex_unlock(&sip_reload_lock);
  29342. restart_monitor();
  29343. tmp_peer = bogus_peer;
  29344. /* Create new bogus peer possibly with new global settings. */
  29345. if ((new_peer = temp_peer("(bogus_peer)"))) {
  29346. ast_string_field_set(new_peer, md5secret, BOGUS_PEER_MD5SECRET);
  29347. ast_clear_flag(&new_peer->flags[0], SIP_INSECURE);
  29348. bogus_peer = new_peer;
  29349. ao2_t_ref(tmp_peer, -1, "unref the old bogus_peer during reload");
  29350. } else {
  29351. ast_log(LOG_ERROR, "Could not update the fake authentication peer.\n");
  29352. /* You probably have bigger (memory?) issues to worry about though.. */
  29353. }
  29354. return CLI_SUCCESS;
  29355. }
  29356. /*! \brief Part of Asterisk module interface */
  29357. static int reload(void)
  29358. {
  29359. if (sip_reload(0, 0, NULL)) {
  29360. return 0;
  29361. }
  29362. return 1;
  29363. }
  29364. /*! \brief Return the first entry from ast_sockaddr_resolve filtered by address family
  29365. *
  29366. * \warning Using this function probably means you have a faulty design.
  29367. */
  29368. static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
  29369. const char* name, int flag, int family)
  29370. {
  29371. struct ast_sockaddr *addrs;
  29372. int addrs_cnt;
  29373. addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
  29374. if (addrs_cnt <= 0) {
  29375. return 1;
  29376. }
  29377. if (addrs_cnt > 1) {
  29378. ast_debug(1, "Multiple addresses, using the first one only\n");
  29379. }
  29380. ast_sockaddr_copy(addr, &addrs[0]);
  29381. ast_free(addrs);
  29382. return 0;
  29383. }
  29384. /*! \brief Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
  29385. *
  29386. * \warning Using this function probably means you have a faulty design.
  29387. */
  29388. static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
  29389. const char* name, int flag)
  29390. {
  29391. return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(AST_TRANSPORT_UDP));
  29392. }
  29393. /*! \brief Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
  29394. *
  29395. * \warning Using this function probably means you have a faulty design.
  29396. */
  29397. static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
  29398. const char* name, int flag, unsigned int transport)
  29399. {
  29400. return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
  29401. }
  29402. /*! \brief
  29403. * \note The only member of the peer used here is the name field
  29404. */
  29405. static int peer_hash_cb(const void *obj, const int flags)
  29406. {
  29407. const struct sip_peer *peer = obj;
  29408. return ast_str_case_hash(peer->name);
  29409. }
  29410. /*!
  29411. * \note The only member of the peer used here is the name field
  29412. */
  29413. static int peer_cmp_cb(void *obj, void *arg, int flags)
  29414. {
  29415. struct sip_peer *peer = obj, *peer2 = arg;
  29416. return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
  29417. }
  29418. /*!
  29419. * Hash function based on the the peer's ip address. For IPv6, we use the end
  29420. * of the address.
  29421. * \todo Find a better hashing function
  29422. */
  29423. static int peer_iphash_cb(const void *obj, const int flags)
  29424. {
  29425. const struct sip_peer *peer = obj;
  29426. int ret = 0;
  29427. if (ast_sockaddr_isnull(&peer->addr)) {
  29428. ast_log(LOG_ERROR, "Empty address\n");
  29429. }
  29430. ret = ast_sockaddr_hash(&peer->addr);
  29431. if (ret < 0) {
  29432. ret = -ret;
  29433. }
  29434. return ret;
  29435. }
  29436. /*!
  29437. * Match Peers by IP and Port number.
  29438. *
  29439. * This function has two modes.
  29440. * - If the peer arg does not have INSECURE_PORT set, then we will only return
  29441. * a match for a peer that matches both the IP and port.
  29442. * - If the peer arg does have the INSECURE_PORT flag set, then we will only
  29443. * return a match for a peer that matches the IP and has insecure=port
  29444. * in its configuration.
  29445. *
  29446. * This callback will be used twice when doing peer matching. There is a first
  29447. * pass for full IP+port matching, and a second pass in case there is a match
  29448. * that meets the insecure=port criteria.
  29449. *
  29450. * \note Connections coming in over TCP or TLS should never be matched by port.
  29451. *
  29452. * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
  29453. */
  29454. static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags)
  29455. {
  29456. struct sip_peer *peer = obj, *peer2 = arg;
  29457. char *callback = data;
  29458. if (!ast_strlen_zero(callback) && strcasecmp(peer->callback, callback)) {
  29459. /* We require a callback extension match, but don't have one */
  29460. return 0;
  29461. }
  29462. /* At this point, we match the callback extension if we need to. Carry on. */
  29463. if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
  29464. /* IP doesn't match */
  29465. return 0;
  29466. }
  29467. /* We matched the IP, check to see if we need to match by port as well. */
  29468. if ((peer->transports & peer2->transports) & (AST_TRANSPORT_TLS | AST_TRANSPORT_TCP)) {
  29469. /* peer matching on port is not possible with TCP/TLS */
  29470. return CMP_MATCH | CMP_STOP;
  29471. } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
  29472. /* We are allowing match without port for peers configured that
  29473. * way in this pass through the peers. */
  29474. return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
  29475. (CMP_MATCH | CMP_STOP) : 0;
  29476. }
  29477. /* Now only return a match if the port matches, as well. */
  29478. return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
  29479. (CMP_MATCH | CMP_STOP) : 0;
  29480. }
  29481. static int peer_ipcmp_cb(void *obj, void *arg, int flags)
  29482. {
  29483. return peer_ipcmp_cb_full(obj, arg, NULL, flags);
  29484. }
  29485. static int threadt_hash_cb(const void *obj, const int flags)
  29486. {
  29487. const struct sip_threadinfo *th = obj;
  29488. return ast_sockaddr_hash(&th->tcptls_session->remote_address);
  29489. }
  29490. static int threadt_cmp_cb(void *obj, void *arg, int flags)
  29491. {
  29492. struct sip_threadinfo *th = obj, *th2 = arg;
  29493. return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
  29494. }
  29495. /*!
  29496. * \note The only member of the dialog used here callid string
  29497. */
  29498. static int dialog_hash_cb(const void *obj, const int flags)
  29499. {
  29500. const struct sip_pvt *pvt = obj;
  29501. return ast_str_case_hash(pvt->callid);
  29502. }
  29503. /*!
  29504. * \note Same as dialog_cmp_cb, except without the CMP_STOP on match
  29505. */
  29506. static int dialog_find_multiple(void *obj, void *arg, int flags)
  29507. {
  29508. struct sip_pvt *pvt = obj, *pvt2 = arg;
  29509. return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
  29510. }
  29511. /*!
  29512. * \note The only member of the dialog used here callid string
  29513. */
  29514. static int dialog_cmp_cb(void *obj, void *arg, int flags)
  29515. {
  29516. struct sip_pvt *pvt = obj, *pvt2 = arg;
  29517. return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
  29518. }
  29519. static int registry_hash_cb(const void *obj, const int flags)
  29520. {
  29521. const struct sip_registry *object;
  29522. const char *key;
  29523. switch (flags & OBJ_SEARCH_MASK) {
  29524. case OBJ_SEARCH_KEY:
  29525. key = obj;
  29526. break;
  29527. case OBJ_SEARCH_OBJECT:
  29528. object = obj;
  29529. key = object->configvalue;
  29530. break;
  29531. default:
  29532. /* Hash can only work on something with a full key. */
  29533. ast_assert(0);
  29534. return 0;
  29535. }
  29536. return ast_str_hash(key);
  29537. }
  29538. static int registry_cmp_cb(void *obj, void *arg, int flags)
  29539. {
  29540. const struct sip_registry *object_left = obj;
  29541. const struct sip_registry *object_right = arg;
  29542. const char *right_key = arg;
  29543. int cmp;
  29544. switch (flags & OBJ_SEARCH_MASK) {
  29545. case OBJ_SEARCH_OBJECT:
  29546. right_key = object_right->configvalue;
  29547. /* Fall through */
  29548. case OBJ_SEARCH_KEY:
  29549. cmp = strcmp(object_left->configvalue, right_key);
  29550. break;
  29551. default:
  29552. cmp = 0;
  29553. break;
  29554. }
  29555. if (cmp) {
  29556. return 0;
  29557. }
  29558. return CMP_MATCH;
  29559. }
  29560. /*! \brief SIP Cli commands definition */
  29561. static struct ast_cli_entry cli_sip[] = {
  29562. AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
  29563. AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
  29564. AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
  29565. AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
  29566. AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
  29567. AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
  29568. AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
  29569. AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
  29570. AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
  29571. AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
  29572. AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
  29573. AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
  29574. AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
  29575. AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
  29576. AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
  29577. AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
  29578. AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
  29579. AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
  29580. AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
  29581. AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
  29582. AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
  29583. AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
  29584. AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
  29585. };
  29586. /*! \brief SIP test registration */
  29587. static void sip_register_tests(void)
  29588. {
  29589. sip_config_parser_register_tests();
  29590. sip_request_parser_register_tests();
  29591. sip_dialplan_function_register_tests();
  29592. }
  29593. /*! \brief SIP test registration */
  29594. static void sip_unregister_tests(void)
  29595. {
  29596. sip_config_parser_unregister_tests();
  29597. sip_request_parser_unregister_tests();
  29598. sip_dialplan_function_unregister_tests();
  29599. }
  29600. #ifdef TEST_FRAMEWORK
  29601. AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
  29602. {
  29603. struct ao2_iterator iter;
  29604. struct sip_subscription_mwi *iterator;
  29605. int found = 0;
  29606. enum ast_test_result_state res = AST_TEST_PASS;
  29607. const char *mwi1 = "1234@mysipprovider.com/1234";
  29608. const char *mwi2 = "1234:password@mysipprovider.com/1234";
  29609. const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
  29610. const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
  29611. const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
  29612. const char *mwi6 = "1234:password";
  29613. switch (cmd) {
  29614. case TEST_INIT:
  29615. info->name = "sip_mwi_subscribe_parse_test";
  29616. info->category = "/channels/chan_sip/";
  29617. info->summary = "SIP MWI subscribe line parse unit test";
  29618. info->description =
  29619. "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
  29620. return AST_TEST_NOT_RUN;
  29621. case TEST_EXECUTE:
  29622. break;
  29623. }
  29624. if (sip_subscribe_mwi(mwi1, 1)) {
  29625. res = AST_TEST_FAIL;
  29626. } else {
  29627. found = 0;
  29628. res = AST_TEST_FAIL;
  29629. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29630. while ((iterator = ao2_t_iterator_next(&iter, "test_sip_mwi_subscribe_parse mwi1"))) {
  29631. ao2_lock(iterator);
  29632. if (
  29633. !strcmp(iterator->hostname, "mysipprovider.com") &&
  29634. !strcmp(iterator->username, "1234") &&
  29635. !strcmp(iterator->secret, "") &&
  29636. !strcmp(iterator->authuser, "") &&
  29637. !strcmp(iterator->mailbox, "1234") &&
  29638. iterator->portno == 0) {
  29639. found = 1;
  29640. res = AST_TEST_PASS;
  29641. }
  29642. ao2_unlock(iterator);
  29643. ao2_t_ref(iterator, -1, "test_sip_mwi_subscribe_parse mwi1");
  29644. }
  29645. ao2_iterator_destroy(&iter);
  29646. if (!found) {
  29647. ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
  29648. }
  29649. }
  29650. if (sip_subscribe_mwi(mwi2, 1)) {
  29651. res = AST_TEST_FAIL;
  29652. } else {
  29653. found = 0;
  29654. res = AST_TEST_FAIL;
  29655. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29656. while ((iterator = ao2_t_iterator_next(&iter, "test_sip_mwi_subscribe_parse mwi2"))) {
  29657. ao2_lock(iterator);
  29658. if (
  29659. !strcmp(iterator->hostname, "mysipprovider.com") &&
  29660. !strcmp(iterator->username, "1234") &&
  29661. !strcmp(iterator->secret, "password") &&
  29662. !strcmp(iterator->authuser, "") &&
  29663. !strcmp(iterator->mailbox, "1234") &&
  29664. iterator->portno == 0) {
  29665. found = 1;
  29666. res = AST_TEST_PASS;
  29667. }
  29668. ao2_unlock(iterator);
  29669. ao2_t_ref(iterator, -1, "test_sip_mwi_subscribe_parse mwi2");
  29670. }
  29671. ao2_iterator_destroy(&iter);
  29672. if (!found) {
  29673. ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
  29674. }
  29675. }
  29676. if (sip_subscribe_mwi(mwi3, 1)) {
  29677. res = AST_TEST_FAIL;
  29678. } else {
  29679. found = 0;
  29680. res = AST_TEST_FAIL;
  29681. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29682. while ((iterator = ao2_t_iterator_next(&iter, "test_sip_mwi_subscribe_parse mwi3"))) {
  29683. ao2_lock(iterator);
  29684. if (
  29685. !strcmp(iterator->hostname, "mysipprovider.com") &&
  29686. !strcmp(iterator->username, "1234") &&
  29687. !strcmp(iterator->secret, "password") &&
  29688. !strcmp(iterator->authuser, "") &&
  29689. !strcmp(iterator->mailbox, "1234") &&
  29690. iterator->portno == 5061) {
  29691. found = 1;
  29692. res = AST_TEST_PASS;
  29693. }
  29694. ao2_unlock(iterator);
  29695. ao2_t_ref(iterator, -1, "test_sip_mwi_subscribe_parse mwi3");
  29696. }
  29697. ao2_iterator_destroy(&iter);
  29698. if (!found) {
  29699. ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
  29700. }
  29701. }
  29702. if (sip_subscribe_mwi(mwi4, 1)) {
  29703. res = AST_TEST_FAIL;
  29704. } else {
  29705. found = 0;
  29706. res = AST_TEST_FAIL;
  29707. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29708. while ((iterator = ao2_t_iterator_next(&iter, "test_sip_mwi_subscribe_parse mwi4"))) {
  29709. ao2_lock(iterator);
  29710. if (
  29711. !strcmp(iterator->hostname, "mysipprovider.com") &&
  29712. !strcmp(iterator->username, "1234") &&
  29713. !strcmp(iterator->secret, "password") &&
  29714. !strcmp(iterator->authuser, "authuser") &&
  29715. !strcmp(iterator->mailbox, "1234") &&
  29716. iterator->portno == 0) {
  29717. found = 1;
  29718. res = AST_TEST_PASS;
  29719. }
  29720. ao2_unlock(iterator);
  29721. ao2_t_ref(iterator, -1, "test_sip_mwi_subscribe_parse mwi4");
  29722. }
  29723. ao2_iterator_destroy(&iter);
  29724. if (!found) {
  29725. ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
  29726. }
  29727. }
  29728. if (sip_subscribe_mwi(mwi5, 1)) {
  29729. res = AST_TEST_FAIL;
  29730. } else {
  29731. found = 0;
  29732. res = AST_TEST_FAIL;
  29733. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29734. while ((iterator = ao2_t_iterator_next(&iter, "test_sip_mwi_subscribe_parse mwi4"))) {
  29735. ao2_lock(iterator);
  29736. if (
  29737. !strcmp(iterator->hostname, "mysipprovider.com") &&
  29738. !strcmp(iterator->username, "1234") &&
  29739. !strcmp(iterator->secret, "password") &&
  29740. !strcmp(iterator->authuser, "authuser") &&
  29741. !strcmp(iterator->mailbox, "1234") &&
  29742. iterator->portno == 5061) {
  29743. found = 1;
  29744. res = AST_TEST_PASS;
  29745. }
  29746. ao2_unlock(iterator);
  29747. ao2_t_ref(iterator, -1, "test_sip_mwi_subscribe_parse mwi4");
  29748. }
  29749. ao2_iterator_destroy(&iter);
  29750. if (!found) {
  29751. ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
  29752. }
  29753. }
  29754. if (sip_subscribe_mwi(mwi6, 1)) {
  29755. res = AST_TEST_PASS;
  29756. } else {
  29757. res = AST_TEST_FAIL;
  29758. }
  29759. return res;
  29760. }
  29761. AST_TEST_DEFINE(test_sip_peers_get)
  29762. {
  29763. struct sip_peer *peer;
  29764. struct ast_data *node;
  29765. struct ast_data_query query = {
  29766. .path = "/asterisk/channel/sip/peers",
  29767. .search = "peers/peer/name=test_peer_data_provider"
  29768. };
  29769. switch (cmd) {
  29770. case TEST_INIT:
  29771. info->name = "sip_peers_get_data_test";
  29772. info->category = "/main/data/sip/peers/";
  29773. info->summary = "SIP peers data providers unit test";
  29774. info->description =
  29775. "Tests whether the SIP peers data provider implementation works as expected.";
  29776. return AST_TEST_NOT_RUN;
  29777. case TEST_EXECUTE:
  29778. break;
  29779. }
  29780. /* Create the peer that we will retrieve. */
  29781. peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
  29782. if (!peer) {
  29783. return AST_TEST_FAIL;
  29784. }
  29785. peer->type = SIP_TYPE_USER;
  29786. peer->call_limit = 10;
  29787. ao2_link(peers, peer);
  29788. /* retrieve the chan_sip/peers tree and check the created peer. */
  29789. node = ast_data_get(&query);
  29790. if (!node) {
  29791. ao2_unlink(peers, peer);
  29792. ao2_ref(peer, -1);
  29793. return AST_TEST_FAIL;
  29794. }
  29795. /* compare item. */
  29796. if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
  29797. ao2_unlink(peers, peer);
  29798. ao2_ref(peer, -1);
  29799. ast_data_free(node);
  29800. return AST_TEST_FAIL;
  29801. }
  29802. if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
  29803. ao2_unlink(peers, peer);
  29804. ao2_ref(peer, -1);
  29805. ast_data_free(node);
  29806. return AST_TEST_FAIL;
  29807. }
  29808. if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
  29809. ao2_unlink(peers, peer);
  29810. ao2_ref(peer, -1);
  29811. ast_data_free(node);
  29812. return AST_TEST_FAIL;
  29813. }
  29814. /* release resources */
  29815. ast_data_free(node);
  29816. ao2_unlink(peers, peer);
  29817. ao2_ref(peer, -1);
  29818. return AST_TEST_PASS;
  29819. }
  29820. /*!
  29821. * \brief Imitation TCP reception loop
  29822. *
  29823. * This imitates the logic used by SIP's TCP code. Its purpose
  29824. * is to either
  29825. * 1) Combine fragments into a single message
  29826. * 2) Break up combined messages into single messages
  29827. *
  29828. * \param fragments The message fragments. This simulates the data received on a TCP socket.
  29829. * \param num_fragments This indicates the number of fragments to receive
  29830. * \param overflow This is a place to stash extra data if more than one message is received
  29831. * in a single fragment
  29832. * \param[out] messages The parsed messages are placed in this array
  29833. * \param[out] num_messages The number of messages that were parsed
  29834. * \param test Used for printing messages
  29835. * \retval 0 Success
  29836. * \retval -1 Failure
  29837. */
  29838. static int mock_tcp_loop(char *fragments[], size_t num_fragments,
  29839. struct ast_str **overflow, char **messages, int *num_messages, struct ast_test* test)
  29840. {
  29841. struct ast_str *req_data;
  29842. int i = 0;
  29843. int res = 0;
  29844. req_data = ast_str_create(128);
  29845. ast_str_reset(*overflow);
  29846. while (i < num_fragments || ast_str_strlen(*overflow) > 0) {
  29847. enum message_integrity message_integrity = MESSAGE_FRAGMENT;
  29848. ast_str_reset(req_data);
  29849. while (message_integrity == MESSAGE_FRAGMENT) {
  29850. if (ast_str_strlen(*overflow) > 0) {
  29851. ast_str_append(&req_data, 0, "%s", ast_str_buffer(*overflow));
  29852. ast_str_reset(*overflow);
  29853. } else {
  29854. ast_str_append(&req_data, 0, "%s", fragments[i++]);
  29855. }
  29856. message_integrity = check_message_integrity(&req_data, overflow);
  29857. }
  29858. if (strcmp(ast_str_buffer(req_data), messages[*num_messages])) {
  29859. ast_test_status_update(test, "Mismatch in SIP messages.\n");
  29860. ast_test_status_update(test, "Expected message:\n%s", messages[*num_messages]);
  29861. ast_test_status_update(test, "Parsed message:\n%s", ast_str_buffer(req_data));
  29862. res = -1;
  29863. goto end;
  29864. } else {
  29865. ast_test_status_update(test, "Successfully read message:\n%s", ast_str_buffer(req_data));
  29866. }
  29867. (*num_messages)++;
  29868. }
  29869. end:
  29870. ast_free(req_data);
  29871. return res;
  29872. };
  29873. AST_TEST_DEFINE(test_tcp_message_fragmentation)
  29874. {
  29875. /* Normal single message in one fragment */
  29876. char *normal[] = {
  29877. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29878. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29879. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29880. "To: <sip:bob@example.org:5060>\r\n"
  29881. "Call-ID: 12345\r\n"
  29882. "CSeq: 1 INVITE\r\n"
  29883. "Contact: sip:127.0.0.1:5061\r\n"
  29884. "Max-Forwards: 70\r\n"
  29885. "Content-Type: application/sdp\r\n"
  29886. "Content-Length: 130\r\n"
  29887. "\r\n"
  29888. "v=0\r\n"
  29889. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29890. "s=-\r\n"
  29891. "c=IN IP4 127.0.0.1\r\n"
  29892. "t=0 0\r\n"
  29893. "m=audio 10000 RTP/AVP 0\r\n"
  29894. "a=rtpmap:0 PCMU/8000\r\n"
  29895. };
  29896. /* Single message in two fragments.
  29897. * Fragments combine to make "normal"
  29898. */
  29899. char *fragmented[] = {
  29900. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29901. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29902. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29903. "To: <sip:bob@example.org:5060>\r\n"
  29904. "Call-ID: 12345\r\n"
  29905. "CSeq: 1 INVITE\r\n"
  29906. "Contact: sip:127.0.0.1:5061\r\n"
  29907. "Max-Forwards: ",
  29908. "70\r\n"
  29909. "Content-Type: application/sdp\r\n"
  29910. "Content-Length: 130\r\n"
  29911. "\r\n"
  29912. "v=0\r\n"
  29913. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29914. "s=-\r\n"
  29915. "c=IN IP4 127.0.0.1\r\n"
  29916. "t=0 0\r\n"
  29917. "m=audio 10000 RTP/AVP 0\r\n"
  29918. "a=rtpmap:0 PCMU/8000\r\n"
  29919. };
  29920. /* Single message in two fragments, divided precisely at the body
  29921. * Fragments combine to make "normal"
  29922. */
  29923. char *fragmented_body[] = {
  29924. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29925. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29926. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29927. "To: <sip:bob@example.org:5060>\r\n"
  29928. "Call-ID: 12345\r\n"
  29929. "CSeq: 1 INVITE\r\n"
  29930. "Contact: sip:127.0.0.1:5061\r\n"
  29931. "Max-Forwards: 70\r\n"
  29932. "Content-Type: application/sdp\r\n"
  29933. "Content-Length: 130\r\n"
  29934. "\r\n",
  29935. "v=0\r\n"
  29936. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29937. "s=-\r\n"
  29938. "c=IN IP4 127.0.0.1\r\n"
  29939. "t=0 0\r\n"
  29940. "m=audio 10000 RTP/AVP 0\r\n"
  29941. "a=rtpmap:0 PCMU/8000\r\n"
  29942. };
  29943. /* Single message in three fragments
  29944. * Fragments combine to make "normal"
  29945. */
  29946. char *multi_fragment[] = {
  29947. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29948. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29949. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29950. "To: <sip:bob@example.org:5060>\r\n"
  29951. "Call-ID: 12345\r\n"
  29952. "CSeq: 1 INVITE\r\n",
  29953. "Contact: sip:127.0.0.1:5061\r\n"
  29954. "Max-Forwards: 70\r\n"
  29955. "Content-Type: application/sdp\r\n"
  29956. "Content-Length: 130\r\n"
  29957. "\r\n"
  29958. "v=0\r\n"
  29959. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29960. "s=-\r\n"
  29961. "c=IN IP4",
  29962. " 127.0.0.1\r\n"
  29963. "t=0 0\r\n"
  29964. "m=audio 10000 RTP/AVP 0\r\n"
  29965. "a=rtpmap:0 PCMU/8000\r\n"
  29966. };
  29967. /* Two messages in a single fragment
  29968. * Fragments split into "multi_message_divided"
  29969. */
  29970. char *multi_message[] = {
  29971. "SIP/2.0 100 Trying\r\n"
  29972. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29973. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29974. "To: <sip:bob@example.org:5060>\r\n"
  29975. "Call-ID: 12345\r\n"
  29976. "CSeq: 1 INVITE\r\n"
  29977. "Contact: <sip:bob@example.org:5060>\r\n"
  29978. "Content-Length: 0\r\n"
  29979. "\r\n"
  29980. "SIP/2.0 180 Ringing\r\n"
  29981. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29982. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29983. "To: <sip:bob@example.org:5060>\r\n"
  29984. "Call-ID: 12345\r\n"
  29985. "CSeq: 1 INVITE\r\n"
  29986. "Contact: <sip:bob@example.org:5060>\r\n"
  29987. "Content-Length: 0\r\n"
  29988. "\r\n"
  29989. };
  29990. char *multi_message_divided[] = {
  29991. "SIP/2.0 100 Trying\r\n"
  29992. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29993. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29994. "To: <sip:bob@example.org:5060>\r\n"
  29995. "Call-ID: 12345\r\n"
  29996. "CSeq: 1 INVITE\r\n"
  29997. "Contact: <sip:bob@example.org:5060>\r\n"
  29998. "Content-Length: 0\r\n"
  29999. "\r\n",
  30000. "SIP/2.0 180 Ringing\r\n"
  30001. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30002. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30003. "To: <sip:bob@example.org:5060>\r\n"
  30004. "Call-ID: 12345\r\n"
  30005. "CSeq: 1 INVITE\r\n"
  30006. "Contact: <sip:bob@example.org:5060>\r\n"
  30007. "Content-Length: 0\r\n"
  30008. "\r\n"
  30009. };
  30010. /* Two messages with bodies combined into one fragment
  30011. * Fragments split into "multi_message_body_divided"
  30012. */
  30013. char *multi_message_body[] = {
  30014. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30015. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30016. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30017. "To: <sip:bob@example.org:5060>\r\n"
  30018. "Call-ID: 12345\r\n"
  30019. "CSeq: 1 INVITE\r\n"
  30020. "Contact: sip:127.0.0.1:5061\r\n"
  30021. "Max-Forwards: 70\r\n"
  30022. "Content-Type: application/sdp\r\n"
  30023. "Content-Length: 130\r\n"
  30024. "\r\n"
  30025. "v=0\r\n"
  30026. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30027. "s=-\r\n"
  30028. "c=IN IP4 127.0.0.1\r\n"
  30029. "t=0 0\r\n"
  30030. "m=audio 10000 RTP/AVP 0\r\n"
  30031. "a=rtpmap:0 PCMU/8000\r\n"
  30032. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30033. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30034. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30035. "To: <sip:bob@example.org:5060>\r\n"
  30036. "Call-ID: 12345\r\n"
  30037. "CSeq: 2 INVITE\r\n"
  30038. "Contact: sip:127.0.0.1:5061\r\n"
  30039. "Max-Forwards: 70\r\n"
  30040. "Content-Type: application/sdp\r\n"
  30041. "Content-Length: 130\r\n"
  30042. "\r\n"
  30043. "v=0\r\n"
  30044. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30045. "s=-\r\n"
  30046. "c=IN IP4 127.0.0.1\r\n"
  30047. "t=0 0\r\n"
  30048. "m=audio 10000 RTP/AVP 0\r\n"
  30049. "a=rtpmap:0 PCMU/8000\r\n"
  30050. };
  30051. char *multi_message_body_divided[] = {
  30052. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30053. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30054. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30055. "To: <sip:bob@example.org:5060>\r\n"
  30056. "Call-ID: 12345\r\n"
  30057. "CSeq: 1 INVITE\r\n"
  30058. "Contact: sip:127.0.0.1:5061\r\n"
  30059. "Max-Forwards: 70\r\n"
  30060. "Content-Type: application/sdp\r\n"
  30061. "Content-Length: 130\r\n"
  30062. "\r\n"
  30063. "v=0\r\n"
  30064. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30065. "s=-\r\n"
  30066. "c=IN IP4 127.0.0.1\r\n"
  30067. "t=0 0\r\n"
  30068. "m=audio 10000 RTP/AVP 0\r\n"
  30069. "a=rtpmap:0 PCMU/8000\r\n",
  30070. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30071. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30072. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30073. "To: <sip:bob@example.org:5060>\r\n"
  30074. "Call-ID: 12345\r\n"
  30075. "CSeq: 2 INVITE\r\n"
  30076. "Contact: sip:127.0.0.1:5061\r\n"
  30077. "Max-Forwards: 70\r\n"
  30078. "Content-Type: application/sdp\r\n"
  30079. "Content-Length: 130\r\n"
  30080. "\r\n"
  30081. "v=0\r\n"
  30082. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30083. "s=-\r\n"
  30084. "c=IN IP4 127.0.0.1\r\n"
  30085. "t=0 0\r\n"
  30086. "m=audio 10000 RTP/AVP 0\r\n"
  30087. "a=rtpmap:0 PCMU/8000\r\n"
  30088. };
  30089. /* Two messages that appear in two fragments. Fragment
  30090. * boundaries do not align with message boundaries.
  30091. * Fragments combine to make "multi_message_divided"
  30092. */
  30093. char *multi_message_in_fragments[] = {
  30094. "SIP/2.0 100 Trying\r\n"
  30095. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30096. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30097. "To: <sip:bob@example.org:5060>\r\n"
  30098. "Call-ID: 12345\r\n"
  30099. "CSeq: 1 INVI",
  30100. "TE\r\n"
  30101. "Contact: <sip:bob@example.org:5060>\r\n"
  30102. "Content-Length: 0\r\n"
  30103. "\r\n"
  30104. "SIP/2.0 180 Ringing\r\n"
  30105. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30106. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30107. "To: <sip:bob@example.org:5060>\r\n"
  30108. "Call-ID: 12345\r\n"
  30109. "CSeq: 1 INVITE\r\n"
  30110. "Contact: <sip:bob@example.org:5060>\r\n"
  30111. "Content-Length: 0\r\n"
  30112. "\r\n"
  30113. };
  30114. /* Message with compact content-length header
  30115. * Same as "normal" but with compact content-length header
  30116. */
  30117. char *compact[] = {
  30118. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30119. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30120. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30121. "To: <sip:bob@example.org:5060>\r\n"
  30122. "Call-ID: 12345\r\n"
  30123. "CSeq: 1 INVITE\r\n"
  30124. "Contact: sip:127.0.0.1:5061\r\n"
  30125. "Max-Forwards: 70\r\n"
  30126. "Content-Type: application/sdp\r\n"
  30127. "l:130\r\n" /* intentionally no space */
  30128. "\r\n"
  30129. "v=0\r\n"
  30130. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30131. "s=-\r\n"
  30132. "c=IN IP4 127.0.0.1\r\n"
  30133. "t=0 0\r\n"
  30134. "m=audio 10000 RTP/AVP 0\r\n"
  30135. "a=rtpmap:0 PCMU/8000\r\n"
  30136. };
  30137. /* Message with faux content-length headers
  30138. * Same as "normal" but with extra fake content-length headers
  30139. */
  30140. char *faux[] = {
  30141. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30142. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30143. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30144. "To: <sip:bob@example.org:5060>\r\n"
  30145. "Call-ID: 12345\r\n"
  30146. "CSeq: 1 INVITE\r\n"
  30147. "Contact: sip:127.0.0.1:5061\r\n"
  30148. "Max-Forwards: 70\r\n"
  30149. "Content-Type: application/sdp\r\n"
  30150. "DisContent-Length: 0\r\n"
  30151. "MalContent-Length: 60\r\n"
  30152. "Content-Length:130\r\n" /* intentionally no space */
  30153. "\r\n"
  30154. "v=0\r\n"
  30155. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30156. "s=-\r\n"
  30157. "c=IN IP4 127.0.0.1\r\n"
  30158. "t=0 0\r\n"
  30159. "m=audio 10000 RTP/AVP 0\r\n"
  30160. "a=rtpmap:0 PCMU/8000\r\n"
  30161. };
  30162. /* Message with folded Content-Length header
  30163. * Message is "normal" with Content-Length spread across three lines
  30164. *
  30165. * This is the test that requires pedantic=yes in order to pass
  30166. */
  30167. char *folded[] = {
  30168. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30169. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30170. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30171. "To: <sip:bob@example.org:5060>\r\n"
  30172. "Call-ID: 12345\r\n"
  30173. "CSeq: 1 INVITE\r\n"
  30174. "Contact: sip:127.0.0.1:5061\r\n"
  30175. "Max-Forwards: 70\r\n"
  30176. "Content-Type: application/sdp\r\n"
  30177. "Content-Length: \t\r\n"
  30178. "\t \r\n"
  30179. " 130\t \r\n"
  30180. "\r\n"
  30181. "v=0\r\n"
  30182. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30183. "s=-\r\n"
  30184. "c=IN IP4 127.0.0.1\r\n"
  30185. "t=0 0\r\n"
  30186. "m=audio 10000 RTP/AVP 0\r\n"
  30187. "a=rtpmap:0 PCMU/8000\r\n"
  30188. };
  30189. /* Message with compact Content-length header in message and
  30190. * full Content-Length header in the body. Ensure that the header
  30191. * in the message is read and that the one in the body is ignored
  30192. */
  30193. char *cl_in_body[] = {
  30194. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30195. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30196. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30197. "To: <sip:bob@example.org:5060>\r\n"
  30198. "Call-ID: 12345\r\n"
  30199. "CSeq: 1 INVITE\r\n"
  30200. "Contact: sip:127.0.0.1:5061\r\n"
  30201. "Max-Forwards: 70\r\n"
  30202. "Content-Type: application/sdp\r\n"
  30203. "l: 149\r\n"
  30204. "\r\n"
  30205. "v=0\r\n"
  30206. "Content-Length: 0\r\n"
  30207. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30208. "s=-\r\n"
  30209. "c=IN IP4 127.0.0.1\r\n"
  30210. "t=0 0\r\n"
  30211. "m=audio 10000 RTP/AVP 0\r\n"
  30212. "a=rtpmap:0 PCMU/8000\r\n"
  30213. };
  30214. struct ast_str *overflow;
  30215. struct {
  30216. char **fragments;
  30217. char **expected;
  30218. int num_expected;
  30219. const char *description;
  30220. } tests[] = {
  30221. { normal, normal, 1, "normal" },
  30222. { fragmented, normal, 1, "fragmented" },
  30223. { fragmented_body, normal, 1, "fragmented_body" },
  30224. { multi_fragment, normal, 1, "multi_fragment" },
  30225. { multi_message, multi_message_divided, 2, "multi_message" },
  30226. { multi_message_body, multi_message_body_divided, 2, "multi_message_body" },
  30227. { multi_message_in_fragments, multi_message_divided, 2, "multi_message_in_fragments" },
  30228. { compact, compact, 1, "compact" },
  30229. { faux, faux, 1, "faux" },
  30230. { folded, folded, 1, "folded" },
  30231. { cl_in_body, cl_in_body, 1, "cl_in_body" },
  30232. };
  30233. int i;
  30234. enum ast_test_result_state res = AST_TEST_PASS;
  30235. switch (cmd) {
  30236. case TEST_INIT:
  30237. info->name = "sip_tcp_message_fragmentation";
  30238. info->category = "/main/sip/transport/";
  30239. info->summary = "SIP TCP message fragmentation test";
  30240. info->description =
  30241. "Tests reception of different TCP messages that have been fragmented or"
  30242. "run together. This test mimicks the code that TCP reception uses.";
  30243. return AST_TEST_NOT_RUN;
  30244. case TEST_EXECUTE:
  30245. break;
  30246. }
  30247. if (!sip_cfg.pedanticsipchecking) {
  30248. ast_log(LOG_WARNING, "Not running test. Pedantic SIP checking is not enabled, so it is guaranteed to fail\n");
  30249. return AST_TEST_NOT_RUN;
  30250. }
  30251. overflow = ast_str_create(128);
  30252. if (!overflow) {
  30253. return AST_TEST_FAIL;
  30254. }
  30255. for (i = 0; i < ARRAY_LEN(tests); ++i) {
  30256. int num_messages = 0;
  30257. if (mock_tcp_loop(tests[i].fragments, ARRAY_LEN(tests[i].fragments),
  30258. &overflow, tests[i].expected, &num_messages, test)) {
  30259. ast_test_status_update(test, "Failed to parse message '%s'\n", tests[i].description);
  30260. res = AST_TEST_FAIL;
  30261. break;
  30262. }
  30263. if (num_messages != tests[i].num_expected) {
  30264. ast_test_status_update(test, "Did not receive the expected number of messages. "
  30265. "Expected %d but received %d\n", tests[i].num_expected, num_messages);
  30266. res = AST_TEST_FAIL;
  30267. break;
  30268. }
  30269. }
  30270. ast_free(overflow);
  30271. return res;
  30272. }
  30273. AST_TEST_DEFINE(get_in_brackets_const_test)
  30274. {
  30275. const char *input;
  30276. const char *start = NULL;
  30277. int len = 0;
  30278. int res;
  30279. #define CHECK_RESULTS(in, expected_res, expected_start, expected_len) do { \
  30280. input = (in); \
  30281. res = get_in_brackets_const(input, &start, &len); \
  30282. if ((expected_res) != res) { \
  30283. ast_test_status_update(test, "Unexpected result: %d != %d\n", expected_res, res); \
  30284. return AST_TEST_FAIL; \
  30285. } \
  30286. if ((expected_start) != start) { \
  30287. const char *e = expected_start ? expected_start : "(null)"; \
  30288. const char *a = start ? start : "(null)"; \
  30289. ast_test_status_update(test, "Unexpected start: %s != %s\n", e, a); \
  30290. return AST_TEST_FAIL; \
  30291. } \
  30292. if ((expected_len) != len) { \
  30293. ast_test_status_update(test, "Unexpected len: %d != %d\n", expected_len, len); \
  30294. return AST_TEST_FAIL; \
  30295. } \
  30296. } while(0)
  30297. switch (cmd) {
  30298. case TEST_INIT:
  30299. info->name = __func__;
  30300. info->category = "/channels/chan_sip/";
  30301. info->summary = "get_in_brackets_const test";
  30302. info->description =
  30303. "Tests the get_in_brackets_const function";
  30304. return AST_TEST_NOT_RUN;
  30305. case TEST_EXECUTE:
  30306. break;
  30307. }
  30308. CHECK_RESULTS("", 1, NULL, -1);
  30309. CHECK_RESULTS("normal <test>", 0, input + 8, 4);
  30310. CHECK_RESULTS("\"normal\" <test>", 0, input + 10, 4);
  30311. CHECK_RESULTS("not normal <test", -1, NULL, -1);
  30312. CHECK_RESULTS("\"yes < really\" <test>", 0, input + 16, 4);
  30313. CHECK_RESULTS("\"even > this\" <test>", 0, input + 15, 4);
  30314. CHECK_RESULTS("<sip:id1@10.10.10.10;lr>", 0, input + 1, 22);
  30315. CHECK_RESULTS("<sip:id1@10.10.10.10;lr>, <sip:id1@10.10.10.20;lr>", 0, input + 1, 22);
  30316. CHECK_RESULTS("<sip:id1,id2@10.10.10.10;lr>", 0, input + 1, 26);
  30317. CHECK_RESULTS("<sip:id1@10., <sip:id2@10.10.10.10;lr>", 0, input + 1, 36);
  30318. CHECK_RESULTS("\"quoted text\" <sip:dlg1@10.10.10.10;lr>", 0, input + 15, 23);
  30319. return AST_TEST_PASS;
  30320. }
  30321. #endif
  30322. #define DATA_EXPORT_SIP_PEER(MEMBER) \
  30323. MEMBER(sip_peer, name, AST_DATA_STRING) \
  30324. MEMBER(sip_peer, secret, AST_DATA_PASSWORD) \
  30325. MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD) \
  30326. MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD) \
  30327. MEMBER(sip_peer, context, AST_DATA_STRING) \
  30328. MEMBER(sip_peer, subscribecontext, AST_DATA_STRING) \
  30329. MEMBER(sip_peer, username, AST_DATA_STRING) \
  30330. MEMBER(sip_peer, accountcode, AST_DATA_STRING) \
  30331. MEMBER(sip_peer, tohost, AST_DATA_STRING) \
  30332. MEMBER(sip_peer, regexten, AST_DATA_STRING) \
  30333. MEMBER(sip_peer, fromuser, AST_DATA_STRING) \
  30334. MEMBER(sip_peer, fromdomain, AST_DATA_STRING) \
  30335. MEMBER(sip_peer, fullcontact, AST_DATA_STRING) \
  30336. MEMBER(sip_peer, cid_num, AST_DATA_STRING) \
  30337. MEMBER(sip_peer, cid_name, AST_DATA_STRING) \
  30338. MEMBER(sip_peer, vmexten, AST_DATA_STRING) \
  30339. MEMBER(sip_peer, language, AST_DATA_STRING) \
  30340. MEMBER(sip_peer, mohinterpret, AST_DATA_STRING) \
  30341. MEMBER(sip_peer, mohsuggest, AST_DATA_STRING) \
  30342. MEMBER(sip_peer, parkinglot, AST_DATA_STRING) \
  30343. MEMBER(sip_peer, useragent, AST_DATA_STRING) \
  30344. MEMBER(sip_peer, mwi_from, AST_DATA_STRING) \
  30345. MEMBER(sip_peer, engine, AST_DATA_STRING) \
  30346. MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING) \
  30347. MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN) \
  30348. MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN) \
  30349. MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN) \
  30350. MEMBER(sip_peer, inuse, AST_DATA_INTEGER) \
  30351. MEMBER(sip_peer, ringing, AST_DATA_INTEGER) \
  30352. MEMBER(sip_peer, onhold, AST_DATA_INTEGER) \
  30353. MEMBER(sip_peer, call_limit, AST_DATA_INTEGER) \
  30354. MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER) \
  30355. MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
  30356. MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS) \
  30357. MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
  30358. MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS) \
  30359. MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS) \
  30360. MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS) \
  30361. MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS) \
  30362. MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS) \
  30363. MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS) \
  30364. MEMBER(sip_peer, description, AST_DATA_STRING)
  30365. AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
  30366. static int peers_data_provider_get(const struct ast_data_search *search,
  30367. struct ast_data *data_root)
  30368. {
  30369. struct sip_peer *peer;
  30370. struct ao2_iterator i;
  30371. struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
  30372. struct ast_data *data_sip_options;
  30373. int total_mailboxes, x;
  30374. struct sip_mailbox *mailbox;
  30375. i = ao2_iterator_init(peers, 0);
  30376. while ((peer = ao2_iterator_next(&i))) {
  30377. ao2_lock(peer);
  30378. data_peer = ast_data_add_node(data_root, "peer");
  30379. if (!data_peer) {
  30380. ao2_unlock(peer);
  30381. ao2_ref(peer, -1);
  30382. continue;
  30383. }
  30384. ast_data_add_structure(sip_peer, data_peer, peer);
  30385. /* transfer mode */
  30386. enum_node = ast_data_add_node(data_peer, "allowtransfer");
  30387. if (!enum_node) {
  30388. ao2_unlock(peer);
  30389. ao2_ref(peer, -1);
  30390. continue;
  30391. }
  30392. ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
  30393. ast_data_add_int(enum_node, "value", peer->allowtransfer);
  30394. /* transports */
  30395. ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
  30396. /* peer type */
  30397. if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
  30398. ast_data_add_str(data_peer, "type", "friend");
  30399. } else if (peer->type & SIP_TYPE_PEER) {
  30400. ast_data_add_str(data_peer, "type", "peer");
  30401. } else if (peer->type & SIP_TYPE_USER) {
  30402. ast_data_add_str(data_peer, "type", "user");
  30403. }
  30404. /* mailboxes */
  30405. total_mailboxes = 0;
  30406. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  30407. if (!total_mailboxes) {
  30408. data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
  30409. if (!data_peer_mailboxes) {
  30410. break;
  30411. }
  30412. total_mailboxes++;
  30413. }
  30414. data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
  30415. if (!data_peer_mailbox) {
  30416. continue;
  30417. }
  30418. ast_data_add_str(data_peer_mailbox, "id", mailbox->id);
  30419. }
  30420. /* amaflags */
  30421. enum_node = ast_data_add_node(data_peer, "amaflags");
  30422. if (!enum_node) {
  30423. ao2_unlock(peer);
  30424. ao2_ref(peer, -1);
  30425. continue;
  30426. }
  30427. ast_data_add_int(enum_node, "value", peer->amaflags);
  30428. ast_data_add_str(enum_node, "text", ast_channel_amaflags2string(peer->amaflags));
  30429. /* sip options */
  30430. data_sip_options = ast_data_add_node(data_peer, "sipoptions");
  30431. if (!data_sip_options) {
  30432. ao2_unlock(peer);
  30433. ao2_ref(peer, -1);
  30434. continue;
  30435. }
  30436. for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
  30437. ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
  30438. }
  30439. /* callingpres */
  30440. enum_node = ast_data_add_node(data_peer, "callingpres");
  30441. if (!enum_node) {
  30442. ao2_unlock(peer);
  30443. ao2_ref(peer, -1);
  30444. continue;
  30445. }
  30446. ast_data_add_int(enum_node, "value", peer->callingpres);
  30447. ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
  30448. /* codecs */
  30449. ast_data_add_codecs(data_peer, "codecs", peer->caps);
  30450. if (!ast_data_search_match(search, data_peer)) {
  30451. ast_data_remove_node(data_root, data_peer);
  30452. }
  30453. ao2_unlock(peer);
  30454. ao2_ref(peer, -1);
  30455. }
  30456. ao2_iterator_destroy(&i);
  30457. return 0;
  30458. }
  30459. static const struct ast_data_handler peers_data_provider = {
  30460. .version = AST_DATA_HANDLER_VERSION,
  30461. .get = peers_data_provider_get
  30462. };
  30463. static const struct ast_data_entry sip_data_providers[] = {
  30464. AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
  30465. };
  30466. static const struct ast_sip_api_tech chan_sip_api_provider = {
  30467. .version = AST_SIP_API_VERSION,
  30468. .name = "chan_sip",
  30469. .sipinfo_send = sipinfo_send,
  30470. };
  30471. static int unload_module(void);
  30472. /*!
  30473. * \brief Load the module
  30474. *
  30475. * Module loading including tests for configuration or dependencies.
  30476. * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
  30477. * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
  30478. * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
  30479. * configuration file or other non-critical problem return
  30480. * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
  30481. */
  30482. static int load_module(void)
  30483. {
  30484. ast_verbose("SIP channel loading...\n");
  30485. if (STASIS_MESSAGE_TYPE_INIT(session_timeout_type)) {
  30486. unload_module();
  30487. return AST_MODULE_LOAD_FAILURE;
  30488. }
  30489. if (!(sip_tech.capabilities = ast_format_cap_alloc(0))) {
  30490. unload_module();
  30491. return AST_MODULE_LOAD_FAILURE;
  30492. }
  30493. if (ast_sip_api_provider_register(&chan_sip_api_provider)) {
  30494. unload_module();
  30495. return AST_MODULE_LOAD_FAILURE;
  30496. }
  30497. /* the fact that ao2_containers can't resize automatically is a major worry! */
  30498. /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
  30499. peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
  30500. peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
  30501. dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
  30502. dialogs_needdestroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_needdestroy");
  30503. dialogs_rtpcheck = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs for rtpchecks");
  30504. threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
  30505. if (!peers || !peers_by_ip || !dialogs || !dialogs_needdestroy || !dialogs_rtpcheck
  30506. || !threadt) {
  30507. ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
  30508. unload_module();
  30509. return AST_MODULE_LOAD_FAILURE;
  30510. }
  30511. if (!(sip_cfg.caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  30512. unload_module();
  30513. return AST_MODULE_LOAD_FAILURE;
  30514. }
  30515. ast_format_cap_append_by_type(sip_tech.capabilities, AST_MEDIA_TYPE_AUDIO);
  30516. registry_list = ao2_t_container_alloc(HASH_REGISTRY_SIZE, registry_hash_cb, registry_cmp_cb, "allocate registry_list");
  30517. subscription_mwi_list = ao2_t_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX,
  30518. AO2_CONTAINER_ALLOC_OPT_INSERT_BEGIN, NULL, NULL, "allocate subscription_mwi_list");
  30519. if (!(sched = ast_sched_context_create())) {
  30520. ast_log(LOG_ERROR, "Unable to create scheduler context\n");
  30521. unload_module();
  30522. return AST_MODULE_LOAD_FAILURE;
  30523. }
  30524. if (!(io = io_context_create())) {
  30525. ast_log(LOG_ERROR, "Unable to create I/O context\n");
  30526. unload_module();
  30527. return AST_MODULE_LOAD_FAILURE;
  30528. }
  30529. sip_reloadreason = CHANNEL_MODULE_LOAD;
  30530. can_parse_xml = sip_is_xml_parsable();
  30531. if (reload_config(sip_reloadreason)) { /* Load the configuration from sip.conf */
  30532. unload_module();
  30533. return AST_MODULE_LOAD_DECLINE;
  30534. }
  30535. /* Initialize bogus peer. Can be done first after reload_config() */
  30536. if (!(bogus_peer = temp_peer("(bogus_peer)"))) {
  30537. ast_log(LOG_ERROR, "Unable to create bogus_peer for authentication\n");
  30538. unload_module();
  30539. return AST_MODULE_LOAD_FAILURE;
  30540. }
  30541. /* Make sure the auth will always fail. */
  30542. ast_string_field_set(bogus_peer, md5secret, BOGUS_PEER_MD5SECRET);
  30543. ast_clear_flag(&bogus_peer->flags[0], SIP_INSECURE);
  30544. /* Prepare the version that does not require DTMF BEGIN frames.
  30545. * We need to use tricks such as memcpy and casts because the variable
  30546. * has const fields.
  30547. */
  30548. memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
  30549. memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
  30550. if (ast_msg_tech_register(&sip_msg_tech)) {
  30551. unload_module();
  30552. return AST_MODULE_LOAD_FAILURE;
  30553. }
  30554. /* Make sure we can register our sip channel type */
  30555. if (ast_channel_register(&sip_tech)) {
  30556. ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
  30557. unload_module();
  30558. return AST_MODULE_LOAD_FAILURE;
  30559. }
  30560. #ifdef TEST_FRAMEWORK
  30561. AST_TEST_REGISTER(test_sip_peers_get);
  30562. AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
  30563. AST_TEST_REGISTER(test_tcp_message_fragmentation);
  30564. AST_TEST_REGISTER(get_in_brackets_const_test);
  30565. #endif
  30566. /* Register AstData providers */
  30567. ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
  30568. /* Register all CLI functions for SIP */
  30569. ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
  30570. /* Tell the RTP engine about our RTP glue */
  30571. ast_rtp_glue_register(&sip_rtp_glue);
  30572. /* Register dialplan applications */
  30573. ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
  30574. ast_register_application_xml(app_sipaddheader, sip_addheader);
  30575. ast_register_application_xml(app_sipremoveheader, sip_removeheader);
  30576. #ifdef TEST_FRAMEWORK
  30577. ast_register_application_xml(app_sipsendcustominfo, sip_sendcustominfo);
  30578. #endif
  30579. /* Register dialplan functions */
  30580. ast_custom_function_register(&sip_header_function);
  30581. ast_custom_function_register(&sippeer_function);
  30582. ast_custom_function_register(&checksipdomain_function);
  30583. /* Register manager commands */
  30584. ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
  30585. ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
  30586. ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
  30587. ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
  30588. ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
  30589. ast_manager_register_xml("SIPpeerstatus", EVENT_FLAG_SYSTEM, manager_sip_peer_status);
  30590. sip_poke_all_peers();
  30591. sip_keepalive_all_peers();
  30592. sip_send_all_registers();
  30593. sip_send_all_mwi_subscriptions();
  30594. initialize_escs();
  30595. if (sip_epa_register(&cc_epa_static_data)) {
  30596. unload_module();
  30597. return AST_MODULE_LOAD_DECLINE;
  30598. }
  30599. if (sip_reqresp_parser_init() == -1) {
  30600. ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
  30601. unload_module();
  30602. return AST_MODULE_LOAD_DECLINE;
  30603. }
  30604. if (can_parse_xml) {
  30605. /* SIP CC agents require the ability to parse XML PIDF bodies
  30606. * in incoming PUBLISH requests
  30607. */
  30608. if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
  30609. unload_module();
  30610. return AST_MODULE_LOAD_DECLINE;
  30611. }
  30612. }
  30613. if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
  30614. unload_module();
  30615. return AST_MODULE_LOAD_DECLINE;
  30616. }
  30617. if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
  30618. unload_module();
  30619. return AST_MODULE_LOAD_DECLINE;
  30620. }
  30621. /* And start the monitor for the first time */
  30622. restart_monitor();
  30623. ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
  30624. "name", RQ_CHAR, 10,
  30625. "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
  30626. "port", RQ_UINTEGER2, 5,
  30627. "regseconds", RQ_INTEGER4, 11,
  30628. "defaultuser", RQ_CHAR, 10,
  30629. "fullcontact", RQ_CHAR, 35,
  30630. "regserver", RQ_CHAR, 20,
  30631. "useragent", RQ_CHAR, 20,
  30632. "lastms", RQ_INTEGER4, 11,
  30633. SENTINEL);
  30634. sip_register_tests();
  30635. network_change_stasis_subscribe();
  30636. ast_websocket_add_protocol("sip", sip_websocket_callback);
  30637. return AST_MODULE_LOAD_SUCCESS;
  30638. }
  30639. /*! \brief PBX unload module API */
  30640. static int unload_module(void)
  30641. {
  30642. struct sip_pvt *p;
  30643. struct sip_threadinfo *th;
  30644. struct ast_context *con;
  30645. struct ao2_iterator i;
  30646. int wait_count;
  30647. ast_sip_api_provider_unregister();
  30648. ast_websocket_remove_protocol("sip", sip_websocket_callback);
  30649. network_change_stasis_unsubscribe();
  30650. acl_change_event_stasis_unsubscribe();
  30651. ast_sched_dump(sched);
  30652. /* First, take us out of the channel type list */
  30653. ast_channel_unregister(&sip_tech);
  30654. ast_msg_tech_unregister(&sip_msg_tech);
  30655. /* Unregister dial plan functions */
  30656. ast_custom_function_unregister(&sippeer_function);
  30657. ast_custom_function_unregister(&sip_header_function);
  30658. ast_custom_function_unregister(&checksipdomain_function);
  30659. /* Unregister dial plan applications */
  30660. ast_unregister_application(app_dtmfmode);
  30661. ast_unregister_application(app_sipaddheader);
  30662. ast_unregister_application(app_sipremoveheader);
  30663. #ifdef TEST_FRAMEWORK
  30664. ast_unregister_application(app_sipsendcustominfo);
  30665. AST_TEST_UNREGISTER(test_sip_peers_get);
  30666. AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
  30667. AST_TEST_UNREGISTER(test_tcp_message_fragmentation);
  30668. AST_TEST_UNREGISTER(get_in_brackets_const_test);
  30669. #endif
  30670. /* Unregister all the AstData providers */
  30671. ast_data_unregister(NULL);
  30672. /* Unregister CLI commands */
  30673. ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
  30674. /* Disconnect from RTP engine */
  30675. ast_rtp_glue_unregister(&sip_rtp_glue);
  30676. /* Unregister AMI actions */
  30677. ast_manager_unregister("SIPpeers");
  30678. ast_manager_unregister("SIPshowpeer");
  30679. ast_manager_unregister("SIPqualifypeer");
  30680. ast_manager_unregister("SIPshowregistry");
  30681. ast_manager_unregister("SIPnotify");
  30682. ast_manager_unregister("SIPpeerstatus");
  30683. /* Kill TCP/TLS server threads */
  30684. if (sip_tcp_desc.master) {
  30685. ast_tcptls_server_stop(&sip_tcp_desc);
  30686. }
  30687. if (sip_tls_desc.master) {
  30688. ast_tcptls_server_stop(&sip_tls_desc);
  30689. }
  30690. ast_ssl_teardown(sip_tls_desc.tls_cfg);
  30691. /* Kill all existing TCP/TLS threads */
  30692. i = ao2_iterator_init(threadt, 0);
  30693. while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
  30694. pthread_t thread = th->threadid;
  30695. th->stop = 1;
  30696. pthread_kill(thread, SIGURG);
  30697. ao2_t_ref(th, -1, "decrement ref from iterator");
  30698. }
  30699. ao2_iterator_destroy(&i);
  30700. /* Hangup all dialogs if they have an owner */
  30701. i = ao2_iterator_init(dialogs, 0);
  30702. while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  30703. if (p->owner)
  30704. ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
  30705. ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
  30706. }
  30707. ao2_iterator_destroy(&i);
  30708. unlink_all_peers_from_tables();
  30709. ast_mutex_lock(&monlock);
  30710. if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
  30711. pthread_t th = monitor_thread;
  30712. monitor_thread = AST_PTHREADT_STOP;
  30713. pthread_cancel(th);
  30714. pthread_kill(th, SIGURG);
  30715. ast_mutex_unlock(&monlock);
  30716. pthread_join(th, NULL);
  30717. } else {
  30718. monitor_thread = AST_PTHREADT_STOP;
  30719. ast_mutex_unlock(&monlock);
  30720. }
  30721. /* Destroy all the dialogs and free their memory */
  30722. i = ao2_iterator_init(dialogs, 0);
  30723. while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  30724. dialog_unlink_all(p);
  30725. ao2_t_ref(p, -1, "throw away iterator result");
  30726. }
  30727. ao2_iterator_destroy(&i);
  30728. /* Free memory for local network address mask */
  30729. ast_free_ha(localaddr);
  30730. ast_mutex_lock(&authl_lock);
  30731. if (authl) {
  30732. ao2_t_cleanup(authl, "Removing global authentication");
  30733. authl = NULL;
  30734. }
  30735. ast_mutex_unlock(&authl_lock);
  30736. sip_epa_unregister_all();
  30737. destroy_escs();
  30738. ast_free(default_tls_cfg.certfile);
  30739. ast_free(default_tls_cfg.pvtfile);
  30740. ast_free(default_tls_cfg.cipher);
  30741. ast_free(default_tls_cfg.cafile);
  30742. ast_free(default_tls_cfg.capath);
  30743. ast_rtp_dtls_cfg_free(&default_dtls_cfg);
  30744. cleanup_all_regs();
  30745. ao2_cleanup(registry_list);
  30746. {
  30747. struct ao2_iterator iter;
  30748. struct sip_subscription_mwi *iterator;
  30749. iter = ao2_iterator_init(subscription_mwi_list, 0);
  30750. while ((iterator = ao2_t_iterator_next(&iter, "unload_module iter"))) {
  30751. ao2_lock(iterator);
  30752. if (iterator->dnsmgr) {
  30753. ast_dnsmgr_release(iterator->dnsmgr);
  30754. iterator->dnsmgr = NULL;
  30755. ao2_t_ref(iterator, -1, "dnsmgr release");
  30756. }
  30757. ao2_unlock(iterator);
  30758. ao2_t_ref(iterator, -1, "unload_module iter");
  30759. }
  30760. ao2_iterator_destroy(&iter);
  30761. }
  30762. ao2_cleanup(subscription_mwi_list);
  30763. /*
  30764. * Wait awhile for the TCP/TLS thread container to become empty.
  30765. *
  30766. * XXX This is a hack, but the worker threads cannot be created
  30767. * joinable. They can die on their own and remove themselves
  30768. * from the container thus resulting in a huge memory leak.
  30769. */
  30770. wait_count = 1000;
  30771. while (ao2_container_count(threadt) && --wait_count) {
  30772. sched_yield();
  30773. }
  30774. if (!wait_count) {
  30775. ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
  30776. }
  30777. ao2_t_cleanup(bogus_peer, "unref the bogus_peer");
  30778. ao2_t_cleanup(peers, "unref the peers table");
  30779. ao2_t_cleanup(peers_by_ip, "unref the peers_by_ip table");
  30780. ao2_t_cleanup(dialogs, "unref the dialogs table");
  30781. ao2_t_cleanup(dialogs_needdestroy, "unref dialogs_needdestroy");
  30782. ao2_t_cleanup(dialogs_rtpcheck, "unref dialogs_rtpcheck");
  30783. ao2_t_cleanup(threadt, "unref the thread table");
  30784. ao2_t_cleanup(sip_monitor_instances, "unref the sip_monitor_instances table");
  30785. clear_sip_domains();
  30786. sip_cfg.contact_acl = ast_free_acl_list(sip_cfg.contact_acl);
  30787. if (sipsock_read_id) {
  30788. ast_io_remove(io, sipsock_read_id);
  30789. sipsock_read_id = NULL;
  30790. }
  30791. close(sipsock);
  30792. io_context_destroy(io);
  30793. ast_sched_context_destroy(sched);
  30794. con = ast_context_find(used_context);
  30795. if (con) {
  30796. ast_context_destroy(con, "SIP");
  30797. }
  30798. ast_unload_realtime("sipregs");
  30799. ast_unload_realtime("sippeers");
  30800. ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
  30801. ast_cc_agent_unregister(&sip_cc_agent_callbacks);
  30802. sip_reqresp_parser_exit();
  30803. sip_unregister_tests();
  30804. if (notify_types) {
  30805. ast_config_destroy(notify_types);
  30806. notify_types = NULL;
  30807. }
  30808. ao2_cleanup(sip_tech.capabilities);
  30809. sip_tech.capabilities = NULL;
  30810. ao2_cleanup(sip_cfg.caps);
  30811. sip_cfg.caps = NULL;
  30812. STASIS_MESSAGE_TYPE_CLEANUP(session_timeout_type);
  30813. return 0;
  30814. }
  30815. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
  30816. .support_level = AST_MODULE_SUPPORT_CORE,
  30817. .load = load_module,
  30818. .unload = unload_module,
  30819. .reload = reload,
  30820. .load_pri = AST_MODPRI_CHANNEL_DRIVER,
  30821. .nonoptreq = "res_crypto,res_http_websocket",
  30822. );