chan_sip.c 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641
  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 char externhost[MAXHOSTNAMELEN]; /*!< External host name */
  1000. static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
  1001. static int externrefresh = 10; /*!< Refresh timer for DNS-based external address (dyndns) */
  1002. static uint16_t externtcpport; /*!< external tcp port */
  1003. static uint16_t externtlsport; /*!< external tls port */
  1004. /*! \brief List of local networks
  1005. * We store "localnet" addresses from the config file into an access list,
  1006. * marked as 'DENY', so the call to ast_apply_ha() will return
  1007. * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
  1008. * (i.e. presumably public) addresses.
  1009. */
  1010. static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
  1011. static int ourport_tcp; /*!< The port used for TCP connections */
  1012. static int ourport_tls; /*!< The port used for TCP/TLS connections */
  1013. static struct ast_sockaddr debugaddr;
  1014. static struct ast_config *notify_types = NULL; /*!< The list of manual NOTIFY types we know how to send */
  1015. /*! some list management macros. */
  1016. #define UNLINK(element, head, prev) do { \
  1017. if (prev) \
  1018. (prev)->next = (element)->next; \
  1019. else \
  1020. (head) = (element)->next; \
  1021. } while (0)
  1022. struct ao2_container *sip_monitor_instances;
  1023. struct show_peers_context;
  1024. /*---------------------------- Forward declarations of functions in chan_sip.c */
  1025. /* Note: This is added to help splitting up chan_sip.c into several files
  1026. in coming releases. */
  1027. /*--- PBX interface functions */
  1028. 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);
  1029. static int sip_devicestate(const char *data);
  1030. static int sip_sendtext(struct ast_channel *ast, const char *text);
  1031. static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
  1032. static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
  1033. static int sip_hangup(struct ast_channel *ast);
  1034. static int sip_answer(struct ast_channel *ast);
  1035. static struct ast_frame *sip_read(struct ast_channel *ast);
  1036. static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
  1037. static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
  1038. static int sip_transfer(struct ast_channel *ast, const char *dest);
  1039. static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
  1040. static int sip_senddigit_begin(struct ast_channel *ast, char digit);
  1041. static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
  1042. static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
  1043. static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
  1044. static const char *sip_get_callid(struct ast_channel *chan);
  1045. static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
  1046. static int sip_standard_port(enum ast_transport type, int port);
  1047. static int sip_prepare_socket(struct sip_pvt *p);
  1048. static int get_address_family_filter(unsigned int transport);
  1049. /*--- Transmitting responses and requests */
  1050. static int sipsock_read(int *id, int fd, short events, void *ignore);
  1051. static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
  1052. static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
  1053. static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
  1054. static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
  1055. static int retrans_pkt(const void *data);
  1056. 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);
  1057. static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1058. static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1059. static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1060. 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);
  1061. static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
  1062. 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);
  1063. static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
  1064. static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
  1065. static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
  1066. static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
  1067. static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
  1068. static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
  1069. static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
  1070. static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
  1071. static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
  1072. static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
  1073. static int transmit_info_with_vidupdate(struct sip_pvt *p);
  1074. static int transmit_message(struct sip_pvt *p, int init, int auth);
  1075. static int transmit_refer(struct sip_pvt *p, const char *dest);
  1076. static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
  1077. static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
  1078. static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
  1079. static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
  1080. static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
  1081. static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
  1082. static void copy_request(struct sip_request *dst, const struct sip_request *src);
  1083. static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
  1084. static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
  1085. static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
  1086. /* Misc dialog routines */
  1087. static int __sip_autodestruct(const void *data);
  1088. static int update_call_counter(struct sip_pvt *fup, int event);
  1089. static int auto_congest(const void *arg);
  1090. static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
  1091. static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
  1092. static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, const char *pathbuf);
  1093. static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
  1094. struct sip_request *req, const char *uri);
  1095. static int get_sip_pvt_from_replaces(const char *callid, const char *totag, const char *fromtag,
  1096. struct sip_pvt **out_pvt, struct ast_channel **out_chan);
  1097. static void check_pendings(struct sip_pvt *p);
  1098. static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan);
  1099. static void *sip_pickup_thread(void *stuff);
  1100. static int sip_pickup(struct ast_channel *chan);
  1101. static int sip_sipredirect(struct sip_pvt *p, const char *dest);
  1102. static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
  1103. /*--- Codec handling / SDP */
  1104. static void try_suggested_sip_codec(struct sip_pvt *p);
  1105. static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
  1106. static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
  1107. static int find_sdp(struct sip_request *req);
  1108. static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
  1109. static int process_sdp_o(const char *o, struct sip_pvt *p);
  1110. static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
  1111. static int process_sdp_a_sendonly(const char *a, int *sendonly);
  1112. static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
  1113. static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
  1114. static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
  1115. static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
  1116. 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);
  1117. static int process_sdp_a_image(const char *a, struct sip_pvt *p);
  1118. static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
  1119. static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
  1120. static void start_ice(struct ast_rtp_instance *instance, int offer);
  1121. static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
  1122. struct ast_str **m_buf, struct ast_str **a_buf,
  1123. int debug, int *min_packet_size, int *max_packet_size);
  1124. static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
  1125. struct ast_str **m_buf, struct ast_str **a_buf,
  1126. int debug);
  1127. static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
  1128. static void do_setnat(struct sip_pvt *p);
  1129. static void stop_media_flows(struct sip_pvt *p);
  1130. /*--- Authentication stuff */
  1131. static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
  1132. static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
  1133. static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
  1134. const char *secret, const char *md5secret, int sipmethod,
  1135. const char *uri, enum xmittype reliable);
  1136. static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
  1137. int sipmethod, const char *uri, enum xmittype reliable,
  1138. struct ast_sockaddr *addr, struct sip_peer **authpeer);
  1139. static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
  1140. /*--- Domain handling */
  1141. static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
  1142. static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
  1143. static void clear_sip_domains(void);
  1144. /*--- SIP realm authentication */
  1145. static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
  1146. static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
  1147. /*--- Misc functions */
  1148. static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
  1149. static int reload_config(enum channelreloadreason reason);
  1150. static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
  1151. static int expire_register(const void *data);
  1152. static void *do_monitor(void *data);
  1153. static int restart_monitor(void);
  1154. static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
  1155. static struct ast_variable *copy_vars(struct ast_variable *src);
  1156. static int dialog_find_multiple(void *obj, void *arg, int flags);
  1157. static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
  1158. /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
  1159. static int sip_refer_alloc(struct sip_pvt *p);
  1160. static int sip_notify_alloc(struct sip_pvt *p);
  1161. static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
  1162. static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
  1163. static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
  1164. /*--- Device monitoring and Device/extension state/event handling */
  1165. static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
  1166. static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
  1167. static int sip_poke_noanswer(const void *data);
  1168. static int sip_poke_peer(struct sip_peer *peer, int force);
  1169. static void sip_poke_all_peers(void);
  1170. static void sip_peer_hold(struct sip_pvt *p, int hold);
  1171. static void mwi_event_cb(void *, struct stasis_subscription *, struct stasis_message *);
  1172. static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
  1173. static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
  1174. static void sip_keepalive_all_peers(void);
  1175. /*--- Applications, functions, CLI and manager command helpers */
  1176. static const char *sip_nat_mode(const struct sip_pvt *p);
  1177. static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1178. static char *transfermode2str(enum transfermodes mode) attribute_const;
  1179. static int peer_status(struct sip_peer *peer, char *status, int statuslen);
  1180. static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1181. static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
  1182. static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
  1183. static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1184. static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1185. static void print_group(int fd, ast_group_t group, int crlf);
  1186. static void print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
  1187. static const char *dtmfmode2str(int mode) attribute_const;
  1188. static int str2dtmfmode(const char *str) attribute_unused;
  1189. static const char *insecure2str(int mode) attribute_const;
  1190. static const char *allowoverlap2str(int mode) attribute_const;
  1191. static void cleanup_stale_contexts(char *new, char *old);
  1192. static const char *domain_mode_to_text(const enum domain_mode mode);
  1193. static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1194. static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
  1195. static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1196. static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
  1197. static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1198. static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1199. static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1200. static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1201. static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1202. static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
  1203. static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
  1204. static char *complete_sip_peer(const char *word, int state, int flags2);
  1205. static char *complete_sip_registered_peer(const char *word, int state, int flags2);
  1206. static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
  1207. static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
  1208. static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
  1209. static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
  1210. static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1211. static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1212. static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1213. static char *sip_do_debug_ip(int fd, const char *arg);
  1214. static char *sip_do_debug_peer(int fd, const char *arg);
  1215. static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1216. static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1217. static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1218. static int sip_dtmfmode(struct ast_channel *chan, const char *data);
  1219. static int sip_addheader(struct ast_channel *chan, const char *data);
  1220. static int sip_do_reload(enum channelreloadreason reason);
  1221. static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1222. static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
  1223. const char *name, int flag, int family);
  1224. static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
  1225. const char *name, int flag);
  1226. static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
  1227. const char *name, int flag, unsigned int transport);
  1228. /*--- Debugging
  1229. Functions for enabling debug per IP or fully, or enabling history logging for
  1230. a SIP dialog
  1231. */
  1232. static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
  1233. static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
  1234. static inline int sip_debug_test_pvt(struct sip_pvt *p);
  1235. static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
  1236. static void sip_dump_history(struct sip_pvt *dialog);
  1237. /*--- Device object handling */
  1238. static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
  1239. static int update_call_counter(struct sip_pvt *fup, int event);
  1240. static void sip_destroy_peer(struct sip_peer *peer);
  1241. static void sip_destroy_peer_fn(void *peer);
  1242. static void set_peer_defaults(struct sip_peer *peer);
  1243. static struct sip_peer *temp_peer(const char *name);
  1244. static void register_peer_exten(struct sip_peer *peer, int onoff);
  1245. static int sip_poke_peer_s(const void *data);
  1246. static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
  1247. static void reg_source_db(struct sip_peer *peer);
  1248. static void destroy_association(struct sip_peer *peer);
  1249. static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
  1250. static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
  1251. static void set_socket_transport(struct sip_socket *socket, int transport);
  1252. static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
  1253. /* Realtime device support */
  1254. 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);
  1255. static void update_peer(struct sip_peer *p, int expire);
  1256. static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
  1257. static const char *get_name_from_variable(const struct ast_variable *var);
  1258. static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
  1259. static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1260. /*--- Internal UA client handling (outbound registrations) */
  1261. static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
  1262. static void sip_registry_destroy(void *reg);
  1263. static int sip_register(const char *value, int lineno);
  1264. static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
  1265. static int sip_reregister(const void *data);
  1266. static int __sip_do_register(struct sip_registry *r);
  1267. static int sip_reg_timeout(const void *data);
  1268. static void sip_send_all_registers(void);
  1269. static int sip_reinvite_retry(const void *data);
  1270. /*--- Parsing SIP requests and responses */
  1271. static int determine_firstline_parts(struct sip_request *req);
  1272. static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
  1273. static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
  1274. static int find_sip_method(const char *msg);
  1275. static unsigned int parse_allowed_methods(struct sip_request *req);
  1276. static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
  1277. static int parse_request(struct sip_request *req);
  1278. static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
  1279. static int method_match(enum sipmethod id, const char *name);
  1280. static void parse_copy(struct sip_request *dst, const struct sip_request *src);
  1281. static void parse_oli(struct sip_request *req, struct ast_channel *chan);
  1282. static const char *find_alias(const char *name, const char *_default);
  1283. static const char *__get_header(const struct sip_request *req, const char *name, int *start);
  1284. static void lws2sws(struct ast_str *msgbuf);
  1285. static void extract_uri(struct sip_pvt *p, struct sip_request *req);
  1286. static char *remove_uri_parameters(char *uri);
  1287. static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
  1288. static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
  1289. static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
  1290. static int set_address_from_contact(struct sip_pvt *pvt);
  1291. static void check_via(struct sip_pvt *p, const struct sip_request *req);
  1292. static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
  1293. static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason, char **reason_str);
  1294. static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
  1295. static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
  1296. static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
  1297. static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
  1298. static int get_domain(const char *str, char *domain, int len);
  1299. static void get_realm(struct sip_pvt *p, const struct sip_request *req);
  1300. static char *get_content(struct sip_request *req);
  1301. /*-- TCP connection handling ---*/
  1302. static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
  1303. static void *sip_tcp_worker_fn(void *);
  1304. /*--- Constructing requests and responses */
  1305. static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
  1306. static int init_req(struct sip_request *req, int sipmethod, const char *recip);
  1307. static void deinit_req(struct sip_request *req);
  1308. static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
  1309. static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
  1310. static int init_resp(struct sip_request *resp, const char *msg);
  1311. static inline int resp_needs_contact(const char *msg, enum sipmethod method);
  1312. static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1313. static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
  1314. static void build_via(struct sip_pvt *p);
  1315. static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
  1316. static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
  1317. static char *generate_random_string(char *buf, size_t size);
  1318. static void build_callid_pvt(struct sip_pvt *pvt);
  1319. static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
  1320. static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
  1321. static void build_localtag_registry(struct sip_registry *reg);
  1322. static void make_our_tag(struct sip_pvt *pvt);
  1323. static int add_header(struct sip_request *req, const char *var, const char *value);
  1324. static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
  1325. static int add_content(struct sip_request *req, const char *line);
  1326. static int finalize_content(struct sip_request *req);
  1327. static void destroy_msg_headers(struct sip_pvt *pvt);
  1328. static int add_text(struct sip_request *req, struct sip_pvt *p);
  1329. static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
  1330. static int add_rpid(struct sip_request *req, struct sip_pvt *p);
  1331. static int add_vidupdate(struct sip_request *req);
  1332. static void add_route(struct sip_request *req, struct sip_route *route, int skip);
  1333. static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
  1334. static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
  1335. static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
  1336. static void set_destination(struct sip_pvt *p, const char *uri);
  1337. static void add_date(struct sip_request *req);
  1338. static void add_expires(struct sip_request *req, int expires);
  1339. static void build_contact(struct sip_pvt *p);
  1340. /*------Request handling functions */
  1341. static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
  1342. static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
  1343. 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);
  1344. static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
  1345. static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
  1346. static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
  1347. static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
  1348. static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
  1349. static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
  1350. static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
  1351. static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
  1352. static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req,
  1353. int *nounlock, struct sip_pvt *replaces_pvt, struct ast_channel *replaces_chan);
  1354. static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
  1355. static int local_attended_transfer(struct sip_pvt *transferer, struct ast_channel *transferer_chan, uint32_t seqno, int *nounlock);
  1356. /*------Response handling functions */
  1357. static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1358. static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1359. static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1360. static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1361. static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1362. static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1363. static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1364. /*------ SRTP Support -------- */
  1365. static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp, const char *a);
  1366. /*------ T38 Support --------- */
  1367. static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
  1368. static void change_t38_state(struct sip_pvt *p, int state);
  1369. /*------ Session-Timers functions --------- */
  1370. static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
  1371. static int proc_session_timer(const void *vp);
  1372. static void stop_session_timer(struct sip_pvt *p);
  1373. static void start_session_timer(struct sip_pvt *p);
  1374. static void restart_session_timer(struct sip_pvt *p);
  1375. static const char *strefresherparam2str(enum st_refresher r);
  1376. static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
  1377. static int parse_minse(const char *p_hdrval, int *const p_interval);
  1378. static int st_get_se(struct sip_pvt *, int max);
  1379. static enum st_refresher st_get_refresher(struct sip_pvt *);
  1380. static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
  1381. static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
  1382. /*------- RTP Glue functions -------- */
  1383. 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);
  1384. /*!--- SIP MWI Subscription support */
  1385. static int sip_subscribe_mwi(const char *value, int lineno);
  1386. static void sip_subscribe_mwi_destroy(void *data);
  1387. static void sip_send_all_mwi_subscriptions(void);
  1388. static int sip_subscribe_mwi_do(const void *data);
  1389. static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
  1390. /*! \brief Definition of this channel for PBX channel registration */
  1391. struct ast_channel_tech sip_tech = {
  1392. .type = "SIP",
  1393. .description = "Session Initiation Protocol (SIP)",
  1394. .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
  1395. .requester = sip_request_call, /* called with chan unlocked */
  1396. .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
  1397. .call = sip_call, /* called with chan locked */
  1398. .send_html = sip_sendhtml,
  1399. .hangup = sip_hangup, /* called with chan locked */
  1400. .answer = sip_answer, /* called with chan locked */
  1401. .read = sip_read, /* called with chan locked */
  1402. .write = sip_write, /* called with chan locked */
  1403. .write_video = sip_write, /* called with chan locked */
  1404. .write_text = sip_write,
  1405. .indicate = sip_indicate, /* called with chan locked */
  1406. .transfer = sip_transfer, /* called with chan locked */
  1407. .fixup = sip_fixup, /* called with chan locked */
  1408. .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
  1409. .send_digit_end = sip_senddigit_end,
  1410. .early_bridge = ast_rtp_instance_early_bridge,
  1411. .send_text = sip_sendtext, /* called with chan locked */
  1412. .func_channel_read = sip_acf_channel_read,
  1413. .setoption = sip_setoption,
  1414. .queryoption = sip_queryoption,
  1415. .get_pvt_uniqueid = sip_get_callid,
  1416. };
  1417. /*! \brief This version of the sip channel tech has no send_digit_begin
  1418. * callback so that the core knows that the channel does not want
  1419. * DTMF BEGIN frames.
  1420. * The struct is initialized just before registering the channel driver,
  1421. * and is for use with channels using SIP INFO DTMF.
  1422. */
  1423. struct ast_channel_tech sip_tech_info;
  1424. /*------- CC Support -------- */
  1425. static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
  1426. static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
  1427. static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
  1428. static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
  1429. static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
  1430. static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
  1431. static int sip_cc_agent_recall(struct ast_cc_agent *agent);
  1432. static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
  1433. static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
  1434. .type = "SIP",
  1435. .init = sip_cc_agent_init,
  1436. .start_offer_timer = sip_cc_agent_start_offer_timer,
  1437. .stop_offer_timer = sip_cc_agent_stop_offer_timer,
  1438. .respond = sip_cc_agent_respond,
  1439. .status_request = sip_cc_agent_status_request,
  1440. .start_monitoring = sip_cc_agent_start_monitoring,
  1441. .callee_available = sip_cc_agent_recall,
  1442. .destructor = sip_cc_agent_destructor,
  1443. };
  1444. /* -------- End of declarations of structures, constants and forward declarations of functions
  1445. Below starts actual code
  1446. ------------------------
  1447. */
  1448. static int sip_epa_register(const struct epa_static_data *static_data)
  1449. {
  1450. struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
  1451. if (!backend) {
  1452. return -1;
  1453. }
  1454. backend->static_data = static_data;
  1455. AST_LIST_LOCK(&epa_static_data_list);
  1456. AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
  1457. AST_LIST_UNLOCK(&epa_static_data_list);
  1458. return 0;
  1459. }
  1460. static void sip_epa_unregister_all(void)
  1461. {
  1462. struct epa_backend *backend;
  1463. AST_LIST_LOCK(&epa_static_data_list);
  1464. while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
  1465. ast_free(backend);
  1466. }
  1467. AST_LIST_UNLOCK(&epa_static_data_list);
  1468. }
  1469. static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
  1470. static void cc_epa_destructor(void *data)
  1471. {
  1472. struct sip_epa_entry *epa_entry = data;
  1473. struct cc_epa_entry *cc_entry = epa_entry->instance_data;
  1474. ast_free(cc_entry);
  1475. }
  1476. static const struct epa_static_data cc_epa_static_data = {
  1477. .event = CALL_COMPLETION,
  1478. .name = "call-completion",
  1479. .handle_error = cc_handle_publish_error,
  1480. .destructor = cc_epa_destructor,
  1481. };
  1482. static const struct epa_static_data *find_static_data(const char * const event_package)
  1483. {
  1484. const struct epa_backend *backend = NULL;
  1485. AST_LIST_LOCK(&epa_static_data_list);
  1486. AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
  1487. if (!strcmp(backend->static_data->name, event_package)) {
  1488. break;
  1489. }
  1490. }
  1491. AST_LIST_UNLOCK(&epa_static_data_list);
  1492. return backend ? backend->static_data : NULL;
  1493. }
  1494. static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
  1495. {
  1496. struct sip_epa_entry *epa_entry;
  1497. const struct epa_static_data *static_data;
  1498. if (!(static_data = find_static_data(event_package))) {
  1499. return NULL;
  1500. }
  1501. if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
  1502. return NULL;
  1503. }
  1504. epa_entry->static_data = static_data;
  1505. ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
  1506. return epa_entry;
  1507. }
  1508. static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
  1509. {
  1510. enum ast_cc_service_type service;
  1511. for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
  1512. if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
  1513. return service;
  1514. }
  1515. }
  1516. return AST_CC_NONE;
  1517. }
  1518. /* Even state compositors code */
  1519. static void esc_entry_destructor(void *obj)
  1520. {
  1521. struct sip_esc_entry *esc_entry = obj;
  1522. if (esc_entry->sched_id > -1) {
  1523. AST_SCHED_DEL(sched, esc_entry->sched_id);
  1524. }
  1525. }
  1526. static int esc_hash_fn(const void *obj, const int flags)
  1527. {
  1528. const struct sip_esc_entry *entry = obj;
  1529. return ast_str_hash(entry->entity_tag);
  1530. }
  1531. static int esc_cmp_fn(void *obj, void *arg, int flags)
  1532. {
  1533. struct sip_esc_entry *entry1 = obj;
  1534. struct sip_esc_entry *entry2 = arg;
  1535. return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
  1536. }
  1537. static struct event_state_compositor *get_esc(const char * const event_package) {
  1538. int i;
  1539. for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
  1540. if (!strcasecmp(event_package, event_state_compositors[i].name)) {
  1541. return &event_state_compositors[i];
  1542. }
  1543. }
  1544. return NULL;
  1545. }
  1546. static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
  1547. struct sip_esc_entry *entry;
  1548. struct sip_esc_entry finder;
  1549. ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
  1550. entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
  1551. return entry;
  1552. }
  1553. static int publish_expire(const void *data)
  1554. {
  1555. struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
  1556. struct event_state_compositor *esc = get_esc(esc_entry->event);
  1557. ast_assert(esc != NULL);
  1558. ao2_unlink(esc->compositor, esc_entry);
  1559. ao2_ref(esc_entry, -1);
  1560. return 0;
  1561. }
  1562. static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
  1563. {
  1564. int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
  1565. struct event_state_compositor *esc = get_esc(esc_entry->event);
  1566. ast_assert(esc != NULL);
  1567. if (is_linked) {
  1568. ao2_unlink(esc->compositor, esc_entry);
  1569. }
  1570. snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
  1571. ao2_link(esc->compositor, esc_entry);
  1572. }
  1573. static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
  1574. {
  1575. struct sip_esc_entry *esc_entry;
  1576. int expires_ms;
  1577. if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
  1578. return NULL;
  1579. }
  1580. esc_entry->event = esc->name;
  1581. expires_ms = expires * 1000;
  1582. /* Bump refcount for scheduler */
  1583. ao2_ref(esc_entry, +1);
  1584. esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
  1585. /* Note: This links the esc_entry into the ESC properly */
  1586. create_new_sip_etag(esc_entry, 0);
  1587. return esc_entry;
  1588. }
  1589. static int initialize_escs(void)
  1590. {
  1591. int i, res = 0;
  1592. for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
  1593. if (!((event_state_compositors[i].compositor) =
  1594. ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
  1595. res = -1;
  1596. }
  1597. }
  1598. return res;
  1599. }
  1600. static void destroy_escs(void)
  1601. {
  1602. int i;
  1603. for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
  1604. ao2_cleanup(event_state_compositors[i].compositor);
  1605. }
  1606. }
  1607. static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
  1608. {
  1609. struct ast_cc_agent *agent = obj;
  1610. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1611. const char *uri = arg;
  1612. return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
  1613. }
  1614. static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
  1615. {
  1616. struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
  1617. return agent;
  1618. }
  1619. static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
  1620. {
  1621. struct ast_cc_agent *agent = obj;
  1622. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1623. const char *uri = arg;
  1624. return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
  1625. }
  1626. static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
  1627. {
  1628. struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
  1629. return agent;
  1630. }
  1631. static int find_by_callid_helper(void *obj, void *arg, int flags)
  1632. {
  1633. struct ast_cc_agent *agent = obj;
  1634. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1635. struct sip_pvt *call_pvt = arg;
  1636. return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
  1637. }
  1638. static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
  1639. {
  1640. struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
  1641. return agent;
  1642. }
  1643. static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
  1644. {
  1645. struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
  1646. struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
  1647. if (!agent_pvt) {
  1648. return -1;
  1649. }
  1650. ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
  1651. ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
  1652. ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
  1653. agent_pvt->offer_timer_id = -1;
  1654. agent->private_data = agent_pvt;
  1655. sip_pvt_lock(call_pvt);
  1656. ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
  1657. sip_pvt_unlock(call_pvt);
  1658. return 0;
  1659. }
  1660. static int sip_offer_timer_expire(const void *data)
  1661. {
  1662. struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
  1663. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1664. agent_pvt->offer_timer_id = -1;
  1665. return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
  1666. }
  1667. static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
  1668. {
  1669. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1670. int when;
  1671. when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
  1672. agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
  1673. return 0;
  1674. }
  1675. static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
  1676. {
  1677. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1678. AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
  1679. return 0;
  1680. }
  1681. static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
  1682. {
  1683. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1684. sip_pvt_lock(agent_pvt->subscribe_pvt);
  1685. ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  1686. if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
  1687. /* The second half of this if statement may be a bit hard to grasp,
  1688. * so here's an explanation. When a subscription comes into
  1689. * chan_sip, as long as it is not malformed, it will be passed
  1690. * to the CC core. If the core senses an out-of-order state transition,
  1691. * then the core will call this callback with the "reason" set to a
  1692. * failure condition.
  1693. * However, an out-of-order state transition will occur during a resubscription
  1694. * for CC. In such a case, we can see that we have already generated a notify_uri
  1695. * and so we can detect that this isn't a *real* failure. Rather, it is just
  1696. * something the core doesn't recognize as a legitimate SIP state transition.
  1697. * Thus we respond with happiness and flowers.
  1698. */
  1699. transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
  1700. transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
  1701. } else {
  1702. transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
  1703. }
  1704. sip_pvt_unlock(agent_pvt->subscribe_pvt);
  1705. agent_pvt->is_available = TRUE;
  1706. }
  1707. static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
  1708. {
  1709. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1710. enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
  1711. return ast_cc_agent_status_response(agent->core_id, state);
  1712. }
  1713. static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
  1714. {
  1715. /* To start monitoring just means to wait for an incoming PUBLISH
  1716. * to tell us that the caller has become available again. No special
  1717. * action is needed
  1718. */
  1719. return 0;
  1720. }
  1721. static int sip_cc_agent_recall(struct ast_cc_agent *agent)
  1722. {
  1723. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1724. /* If we have received a PUBLISH beforehand stating that the caller in question
  1725. * is not available, we can save ourself a bit of effort here and just report
  1726. * the caller as busy
  1727. */
  1728. if (!agent_pvt->is_available) {
  1729. return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
  1730. agent->device_name);
  1731. }
  1732. /* Otherwise, we transmit a NOTIFY to the caller and await either
  1733. * a PUBLISH or an INVITE
  1734. */
  1735. sip_pvt_lock(agent_pvt->subscribe_pvt);
  1736. transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
  1737. sip_pvt_unlock(agent_pvt->subscribe_pvt);
  1738. return 0;
  1739. }
  1740. static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
  1741. {
  1742. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1743. if (!agent_pvt) {
  1744. /* The agent constructor probably failed. */
  1745. return;
  1746. }
  1747. sip_cc_agent_stop_offer_timer(agent);
  1748. if (agent_pvt->subscribe_pvt) {
  1749. sip_pvt_lock(agent_pvt->subscribe_pvt);
  1750. if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  1751. /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
  1752. * the subscriber know something went wrong
  1753. */
  1754. transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
  1755. }
  1756. sip_pvt_unlock(agent_pvt->subscribe_pvt);
  1757. agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
  1758. }
  1759. ast_free(agent_pvt);
  1760. }
  1761. static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
  1762. {
  1763. const struct sip_monitor_instance *monitor_instance = obj;
  1764. return monitor_instance->core_id;
  1765. }
  1766. static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
  1767. {
  1768. struct sip_monitor_instance *monitor_instance1 = obj;
  1769. struct sip_monitor_instance *monitor_instance2 = arg;
  1770. return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
  1771. }
  1772. static void sip_monitor_instance_destructor(void *data)
  1773. {
  1774. struct sip_monitor_instance *monitor_instance = data;
  1775. if (monitor_instance->subscription_pvt) {
  1776. sip_pvt_lock(monitor_instance->subscription_pvt);
  1777. monitor_instance->subscription_pvt->expiry = 0;
  1778. transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
  1779. sip_pvt_unlock(monitor_instance->subscription_pvt);
  1780. dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
  1781. }
  1782. if (monitor_instance->suspension_entry) {
  1783. monitor_instance->suspension_entry->body[0] = '\0';
  1784. transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
  1785. ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
  1786. }
  1787. ast_string_field_free_memory(monitor_instance);
  1788. }
  1789. 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)
  1790. {
  1791. struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
  1792. if (!monitor_instance) {
  1793. return NULL;
  1794. }
  1795. if (ast_string_field_init(monitor_instance, 256)) {
  1796. ao2_ref(monitor_instance, -1);
  1797. return NULL;
  1798. }
  1799. ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
  1800. ast_string_field_set(monitor_instance, peername, peername);
  1801. ast_string_field_set(monitor_instance, device_name, device_name);
  1802. monitor_instance->core_id = core_id;
  1803. ao2_link(sip_monitor_instances, monitor_instance);
  1804. return monitor_instance;
  1805. }
  1806. static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
  1807. {
  1808. struct sip_monitor_instance *monitor_instance = obj;
  1809. return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
  1810. }
  1811. static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
  1812. {
  1813. struct sip_monitor_instance *monitor_instance = obj;
  1814. return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
  1815. }
  1816. static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
  1817. static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
  1818. static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
  1819. static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
  1820. static void sip_cc_monitor_destructor(void *private_data);
  1821. static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
  1822. .type = "SIP",
  1823. .request_cc = sip_cc_monitor_request_cc,
  1824. .suspend = sip_cc_monitor_suspend,
  1825. .unsuspend = sip_cc_monitor_unsuspend,
  1826. .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
  1827. .destructor = sip_cc_monitor_destructor,
  1828. };
  1829. static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
  1830. {
  1831. struct sip_monitor_instance *monitor_instance = monitor->private_data;
  1832. enum ast_cc_service_type service = monitor->service_offered;
  1833. int when;
  1834. if (!monitor_instance) {
  1835. return -1;
  1836. }
  1837. if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
  1838. return -1;
  1839. }
  1840. when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
  1841. ast_get_ccnr_available_timer(monitor->interface->config_params);
  1842. sip_pvt_lock(monitor_instance->subscription_pvt);
  1843. ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
  1844. create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
  1845. ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
  1846. monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
  1847. monitor_instance->subscription_pvt->expiry = when;
  1848. transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
  1849. sip_pvt_unlock(monitor_instance->subscription_pvt);
  1850. ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
  1851. *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
  1852. return 0;
  1853. }
  1854. static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
  1855. {
  1856. struct ast_str *body = ast_str_alloca(size);
  1857. char tuple_id[32];
  1858. generate_random_string(tuple_id, sizeof(tuple_id));
  1859. /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
  1860. * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
  1861. */
  1862. ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  1863. /* XXX The entity attribute is currently set to the peer name associated with the
  1864. * dialog. This is because we currently only call this function for call-completion
  1865. * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
  1866. * event packages, it may be crucial to have a proper URI as the presentity so this
  1867. * should be revisited as support is expanded.
  1868. */
  1869. ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
  1870. ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
  1871. ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
  1872. ast_str_append(&body, 0, "</tuple>\n");
  1873. ast_str_append(&body, 0, "</presence>\n");
  1874. ast_copy_string(pidf_body, ast_str_buffer(body), size);
  1875. return 0;
  1876. }
  1877. static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
  1878. {
  1879. struct sip_monitor_instance *monitor_instance = monitor->private_data;
  1880. enum sip_publish_type publish_type;
  1881. struct cc_epa_entry *cc_entry;
  1882. if (!monitor_instance) {
  1883. return -1;
  1884. }
  1885. if (!monitor_instance->suspension_entry) {
  1886. /* We haven't yet allocated the suspension entry, so let's give it a shot */
  1887. if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
  1888. ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
  1889. ao2_ref(monitor_instance, -1);
  1890. return -1;
  1891. }
  1892. if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
  1893. ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
  1894. ao2_ref(monitor_instance, -1);
  1895. return -1;
  1896. }
  1897. cc_entry->core_id = monitor->core_id;
  1898. monitor_instance->suspension_entry->instance_data = cc_entry;
  1899. publish_type = SIP_PUBLISH_INITIAL;
  1900. } else {
  1901. publish_type = SIP_PUBLISH_MODIFY;
  1902. cc_entry = monitor_instance->suspension_entry->instance_data;
  1903. }
  1904. cc_entry->current_state = CC_CLOSED;
  1905. if (ast_strlen_zero(monitor_instance->notify_uri)) {
  1906. /* If we have no set notify_uri, then what this means is that we have
  1907. * not received a NOTIFY from this destination stating that he is
  1908. * currently available.
  1909. *
  1910. * This situation can arise when the core calls the suspend callbacks
  1911. * of multiple destinations. If one of the other destinations aside
  1912. * from this one notified Asterisk that he is available, then there
  1913. * is no reason to take any suspension action on this device. Rather,
  1914. * we should return now and if we receive a NOTIFY while monitoring
  1915. * is still "suspended" then we can immediately respond with the
  1916. * proper PUBLISH to let this endpoint know what is going on.
  1917. */
  1918. return 0;
  1919. }
  1920. construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
  1921. return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
  1922. }
  1923. static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
  1924. {
  1925. struct sip_monitor_instance *monitor_instance = monitor->private_data;
  1926. struct cc_epa_entry *cc_entry;
  1927. if (!monitor_instance) {
  1928. return -1;
  1929. }
  1930. ast_assert(monitor_instance->suspension_entry != NULL);
  1931. cc_entry = monitor_instance->suspension_entry->instance_data;
  1932. cc_entry->current_state = CC_OPEN;
  1933. if (ast_strlen_zero(monitor_instance->notify_uri)) {
  1934. /* This means we are being asked to unsuspend a call leg we never
  1935. * sent a PUBLISH on. As such, there is no reason to send another
  1936. * PUBLISH at this point either. We can just return instead.
  1937. */
  1938. return 0;
  1939. }
  1940. construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
  1941. return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
  1942. }
  1943. static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
  1944. {
  1945. if (*sched_id != -1) {
  1946. AST_SCHED_DEL(sched, *sched_id);
  1947. ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
  1948. }
  1949. return 0;
  1950. }
  1951. static void sip_cc_monitor_destructor(void *private_data)
  1952. {
  1953. struct sip_monitor_instance *monitor_instance = private_data;
  1954. ao2_unlink(sip_monitor_instances, monitor_instance);
  1955. ast_module_unref(ast_module_info->self);
  1956. }
  1957. static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
  1958. {
  1959. char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
  1960. char *uri;
  1961. char *purpose;
  1962. char *service_str;
  1963. static const char cc_purpose[] = "purpose=call-completion";
  1964. static const int cc_purpose_len = sizeof(cc_purpose) - 1;
  1965. if (ast_strlen_zero(call_info)) {
  1966. /* No Call-Info present. Definitely no CC offer */
  1967. return -1;
  1968. }
  1969. uri = strsep(&call_info, ";");
  1970. while ((purpose = strsep(&call_info, ";"))) {
  1971. if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
  1972. break;
  1973. }
  1974. }
  1975. if (!purpose) {
  1976. /* We didn't find the appropriate purpose= parameter. Oh well */
  1977. return -1;
  1978. }
  1979. /* Okay, call-completion has been offered. Let's figure out what type of service this is */
  1980. while ((service_str = strsep(&call_info, ";"))) {
  1981. if (!strncmp(service_str, "m=", 2)) {
  1982. break;
  1983. }
  1984. }
  1985. if (!service_str) {
  1986. /* So they didn't offer a particular service, We'll just go with CCBS since it really
  1987. * doesn't matter anyway
  1988. */
  1989. service_str = "BS";
  1990. } else {
  1991. /* We already determined that there is an "m=" so no need to check
  1992. * the result of this strsep
  1993. */
  1994. strsep(&service_str, "=");
  1995. }
  1996. if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
  1997. /* Invalid service offered */
  1998. return -1;
  1999. }
  2000. ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
  2001. return 0;
  2002. }
  2003. /*
  2004. * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
  2005. *
  2006. * After taking care of some formalities to be sure that this call is eligible for CC,
  2007. * we first try to see if we can make use of native CC. We grab the information from
  2008. * the passed-in sip_request (which is always a response to an INVITE). If we can
  2009. * use native CC monitoring for the call, then so be it.
  2010. *
  2011. * If native cc monitoring is not possible or not supported, then we will instead attempt
  2012. * to use generic monitoring. Falling back to generic from a failed attempt at using native
  2013. * monitoring will only work if the monitor policy of the endpoint is "always"
  2014. *
  2015. * \param pvt The current dialog. Contains CC parameters for the endpoint
  2016. * \param req The response to the INVITE we want to inspect
  2017. * \param service The service to use if generic monitoring is to be used. For native
  2018. * monitoring, we get the service from the SIP response itself
  2019. */
  2020. static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
  2021. {
  2022. enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
  2023. int core_id;
  2024. char interface_name[AST_CHANNEL_NAME];
  2025. if (monitor_policy == AST_CC_MONITOR_NEVER) {
  2026. /* Don't bother, just return */
  2027. return;
  2028. }
  2029. if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
  2030. /* For some reason, CC is invalid, so don't try it! */
  2031. return;
  2032. }
  2033. ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
  2034. if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
  2035. char subscribe_uri[SIPBUFSIZE];
  2036. char device_name[AST_CHANNEL_NAME];
  2037. enum ast_cc_service_type offered_service;
  2038. struct sip_monitor_instance *monitor_instance;
  2039. if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
  2040. /* If CC isn't being offered to us, or for some reason the CC offer is
  2041. * not formatted correctly, then it may still be possible to use generic
  2042. * call completion since the monitor policy may be "always"
  2043. */
  2044. goto generic;
  2045. }
  2046. ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
  2047. if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
  2048. /* Same deal. We can try using generic still */
  2049. goto generic;
  2050. }
  2051. /* We bump the refcount of chan_sip because once we queue this frame, the CC core
  2052. * will have a reference to callbacks in this module. We decrement the module
  2053. * refcount once the monitor destructor is called
  2054. */
  2055. ast_module_ref(ast_module_info->self);
  2056. ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
  2057. ao2_ref(monitor_instance, -1);
  2058. return;
  2059. }
  2060. generic:
  2061. if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
  2062. ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
  2063. }
  2064. }
  2065. /*! \brief Working TLS connection configuration */
  2066. static struct ast_tls_config sip_tls_cfg;
  2067. /*! \brief Default TLS connection configuration */
  2068. static struct ast_tls_config default_tls_cfg;
  2069. /*! \brief The TCP server definition */
  2070. static struct ast_tcptls_session_args sip_tcp_desc = {
  2071. .accept_fd = -1,
  2072. .master = AST_PTHREADT_NULL,
  2073. .tls_cfg = NULL,
  2074. .poll_timeout = -1,
  2075. .name = "SIP TCP server",
  2076. .accept_fn = ast_tcptls_server_root,
  2077. .worker_fn = sip_tcp_worker_fn,
  2078. };
  2079. /*! \brief The TCP/TLS server definition */
  2080. static struct ast_tcptls_session_args sip_tls_desc = {
  2081. .accept_fd = -1,
  2082. .master = AST_PTHREADT_NULL,
  2083. .tls_cfg = &sip_tls_cfg,
  2084. .poll_timeout = -1,
  2085. .name = "SIP TLS server",
  2086. .accept_fn = ast_tcptls_server_root,
  2087. .worker_fn = sip_tcp_worker_fn,
  2088. };
  2089. /*! \brief Append to SIP dialog history
  2090. \return Always returns 0 */
  2091. #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
  2092. struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
  2093. {
  2094. if (p)
  2095. #ifdef REF_DEBUG
  2096. __ao2_ref_debug(p, 1, tag, file, line, func);
  2097. #else
  2098. ao2_ref(p, 1);
  2099. #endif
  2100. else
  2101. ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
  2102. return p;
  2103. }
  2104. struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
  2105. {
  2106. if (p)
  2107. #ifdef REF_DEBUG
  2108. __ao2_ref_debug(p, -1, tag, file, line, func);
  2109. #else
  2110. ao2_ref(p, -1);
  2111. #endif
  2112. return NULL;
  2113. }
  2114. /*! \brief map from an integer value to a string.
  2115. * If no match is found, return errorstring
  2116. */
  2117. static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
  2118. {
  2119. const struct _map_x_s *cur;
  2120. for (cur = table; cur->s; cur++) {
  2121. if (cur->x == x) {
  2122. return cur->s;
  2123. }
  2124. }
  2125. return errorstring;
  2126. }
  2127. /*! \brief map from a string to an integer value, case insensitive.
  2128. * If no match is found, return errorvalue.
  2129. */
  2130. static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
  2131. {
  2132. const struct _map_x_s *cur;
  2133. for (cur = table; cur->s; cur++) {
  2134. if (!strcasecmp(cur->s, s)) {
  2135. return cur->x;
  2136. }
  2137. }
  2138. return errorvalue;
  2139. }
  2140. static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
  2141. {
  2142. enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
  2143. int i;
  2144. for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
  2145. if (!strcasecmp(text, sip_reason_table[i].text)) {
  2146. ast = sip_reason_table[i].code;
  2147. break;
  2148. }
  2149. }
  2150. return ast;
  2151. }
  2152. static const char *sip_reason_code_to_str(struct ast_party_redirecting_reason *reason, int *table_lookup)
  2153. {
  2154. int code = reason->code;
  2155. /* If there's a specific string set, then we just
  2156. * use it.
  2157. */
  2158. if (!ast_strlen_zero(reason->str)) {
  2159. /* If we care about whether this can be found in
  2160. * the table, then we need to check about that.
  2161. */
  2162. if (table_lookup) {
  2163. /* If the string is literally "unknown" then don't bother with the lookup
  2164. * because it can lead to a false negative.
  2165. */
  2166. if (!strcasecmp(reason->str, "unknown") ||
  2167. sip_reason_str_to_code(reason->str) != AST_REDIRECTING_REASON_UNKNOWN) {
  2168. *table_lookup = TRUE;
  2169. } else {
  2170. *table_lookup = FALSE;
  2171. }
  2172. }
  2173. return reason->str;
  2174. }
  2175. if (table_lookup) {
  2176. *table_lookup = TRUE;
  2177. }
  2178. if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
  2179. return sip_reason_table[code].text;
  2180. }
  2181. return "unknown";
  2182. }
  2183. /*!
  2184. * \brief generic function for determining if a correct transport is being
  2185. * used to contact a peer
  2186. *
  2187. * this is done as a macro so that the "tmpl" var can be passed either a
  2188. * sip_request or a sip_peer
  2189. */
  2190. #define check_request_transport(peer, tmpl) ({ \
  2191. int ret = 0; \
  2192. if (peer->socket.type == tmpl->socket.type) \
  2193. ; \
  2194. else if (!(peer->transports & tmpl->socket.type)) {\
  2195. ast_log(LOG_ERROR, \
  2196. "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
  2197. sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
  2198. ); \
  2199. ret = 1; \
  2200. } else if (peer->socket.type & AST_TRANSPORT_TLS) { \
  2201. ast_log(LOG_WARNING, \
  2202. "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
  2203. peer->name, sip_get_transport(tmpl->socket.type) \
  2204. ); \
  2205. } else { \
  2206. ast_debug(1, \
  2207. "peer '%s' has contacted us over %s even though we prefer %s.\n", \
  2208. peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
  2209. ); \
  2210. }\
  2211. (ret); \
  2212. })
  2213. /*! \brief
  2214. * duplicate a list of channel variables, \return the copy.
  2215. */
  2216. static struct ast_variable *copy_vars(struct ast_variable *src)
  2217. {
  2218. struct ast_variable *res = NULL, *tmp, *v = NULL;
  2219. for (v = src ; v ; v = v->next) {
  2220. if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
  2221. tmp->next = res;
  2222. res = tmp;
  2223. }
  2224. }
  2225. return res;
  2226. }
  2227. static void tcptls_packet_destructor(void *obj)
  2228. {
  2229. struct tcptls_packet *packet = obj;
  2230. ast_free(packet->data);
  2231. }
  2232. static void sip_tcptls_client_args_destructor(void *obj)
  2233. {
  2234. struct ast_tcptls_session_args *args = obj;
  2235. if (args->tls_cfg) {
  2236. ast_free(args->tls_cfg->certfile);
  2237. ast_free(args->tls_cfg->pvtfile);
  2238. ast_free(args->tls_cfg->cipher);
  2239. ast_free(args->tls_cfg->cafile);
  2240. ast_free(args->tls_cfg->capath);
  2241. ast_ssl_teardown(args->tls_cfg);
  2242. }
  2243. ast_free(args->tls_cfg);
  2244. ast_free((char *) args->name);
  2245. }
  2246. static void sip_threadinfo_destructor(void *obj)
  2247. {
  2248. struct sip_threadinfo *th = obj;
  2249. struct tcptls_packet *packet;
  2250. if (th->alert_pipe[1] > -1) {
  2251. close(th->alert_pipe[0]);
  2252. }
  2253. if (th->alert_pipe[1] > -1) {
  2254. close(th->alert_pipe[1]);
  2255. }
  2256. th->alert_pipe[0] = th->alert_pipe[1] = -1;
  2257. while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
  2258. ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
  2259. }
  2260. if (th->tcptls_session) {
  2261. ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
  2262. }
  2263. }
  2264. /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
  2265. static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
  2266. {
  2267. struct sip_threadinfo *th;
  2268. if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
  2269. return NULL;
  2270. }
  2271. th->alert_pipe[0] = th->alert_pipe[1] = -1;
  2272. if (pipe(th->alert_pipe) == -1) {
  2273. ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
  2274. ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
  2275. return NULL;
  2276. }
  2277. ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
  2278. th->tcptls_session = tcptls_session;
  2279. th->type = transport ? transport : (tcptls_session->ssl ? AST_TRANSPORT_TLS: AST_TRANSPORT_TCP);
  2280. ao2_t_link(threadt, th, "Adding new tcptls helper thread");
  2281. ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
  2282. return th;
  2283. }
  2284. /*! \brief used to indicate to a tcptls thread that data is ready to be written */
  2285. static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
  2286. {
  2287. int res = len;
  2288. struct sip_threadinfo *th = NULL;
  2289. struct tcptls_packet *packet = NULL;
  2290. struct sip_threadinfo tmp = {
  2291. .tcptls_session = tcptls_session,
  2292. };
  2293. enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
  2294. if (!tcptls_session) {
  2295. return XMIT_ERROR;
  2296. }
  2297. ao2_lock(tcptls_session);
  2298. if ((tcptls_session->fd == -1) ||
  2299. !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
  2300. !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
  2301. !(packet->data = ast_str_create(len))) {
  2302. goto tcptls_write_setup_error;
  2303. }
  2304. /* goto tcptls_write_error should _NOT_ be used beyond this point */
  2305. ast_str_set(&packet->data, 0, "%s", (char *) buf);
  2306. packet->len = len;
  2307. /* alert tcptls thread handler that there is a packet to be sent.
  2308. * must lock the thread info object to guarantee control of the
  2309. * packet queue */
  2310. ao2_lock(th);
  2311. if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
  2312. ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
  2313. ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
  2314. packet = NULL;
  2315. res = XMIT_ERROR;
  2316. } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
  2317. AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
  2318. }
  2319. ao2_unlock(th);
  2320. ao2_unlock(tcptls_session);
  2321. ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
  2322. return res;
  2323. tcptls_write_setup_error:
  2324. if (th) {
  2325. ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
  2326. }
  2327. if (packet) {
  2328. ao2_t_ref(packet, -1, "could not allocate packet's data");
  2329. }
  2330. ao2_unlock(tcptls_session);
  2331. return XMIT_ERROR;
  2332. }
  2333. /*! \brief SIP TCP connection handler */
  2334. static void *sip_tcp_worker_fn(void *data)
  2335. {
  2336. struct ast_tcptls_session_instance *tcptls_session = data;
  2337. return _sip_tcp_helper_thread(tcptls_session);
  2338. }
  2339. /*! \brief SIP WebSocket connection handler */
  2340. static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
  2341. {
  2342. int res;
  2343. if (ast_websocket_set_nonblock(session)) {
  2344. goto end;
  2345. }
  2346. if (ast_websocket_set_timeout(session, sip_cfg.websocket_write_timeout)) {
  2347. goto end;
  2348. }
  2349. while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
  2350. char *payload;
  2351. uint64_t payload_len;
  2352. enum ast_websocket_opcode opcode;
  2353. int fragmented;
  2354. if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
  2355. /* We err on the side of caution and terminate the session if any error occurs */
  2356. break;
  2357. }
  2358. if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
  2359. struct sip_request req = { 0, };
  2360. char data[payload_len + 1];
  2361. if (!(req.data = ast_str_create(payload_len + 1))) {
  2362. goto end;
  2363. }
  2364. strncpy(data, payload, payload_len);
  2365. data[payload_len] = '\0';
  2366. if (ast_str_set(&req.data, -1, "%s", data) == AST_DYNSTR_BUILD_FAILED) {
  2367. deinit_req(&req);
  2368. goto end;
  2369. }
  2370. req.socket.fd = ast_websocket_fd(session);
  2371. set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? AST_TRANSPORT_WSS : AST_TRANSPORT_WS);
  2372. req.socket.ws_session = session;
  2373. handle_request_do(&req, ast_websocket_remote_address(session));
  2374. deinit_req(&req);
  2375. } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
  2376. break;
  2377. }
  2378. }
  2379. end:
  2380. ast_websocket_unref(session);
  2381. }
  2382. /*! \brief Check if the authtimeout has expired.
  2383. * \param start the time when the session started
  2384. *
  2385. * \retval 0 the timeout has expired
  2386. * \retval -1 error
  2387. * \return the number of milliseconds until the timeout will expire
  2388. */
  2389. static int sip_check_authtimeout(time_t start)
  2390. {
  2391. int timeout;
  2392. time_t now;
  2393. if(time(&now) == -1) {
  2394. ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
  2395. return -1;
  2396. }
  2397. timeout = (authtimeout - (now - start)) * 1000;
  2398. if (timeout < 0) {
  2399. /* we have timed out */
  2400. return 0;
  2401. }
  2402. return timeout;
  2403. }
  2404. /*!
  2405. * \brief Indication of a TCP message's integrity
  2406. */
  2407. enum message_integrity {
  2408. /*!
  2409. * The message has an error in it with
  2410. * regards to its Content-Length header
  2411. */
  2412. MESSAGE_INVALID,
  2413. /*!
  2414. * The message is incomplete
  2415. */
  2416. MESSAGE_FRAGMENT,
  2417. /*!
  2418. * The data contains a complete message
  2419. * plus a fragment of another.
  2420. */
  2421. MESSAGE_FRAGMENT_COMPLETE,
  2422. /*!
  2423. * The message is complete
  2424. */
  2425. MESSAGE_COMPLETE,
  2426. };
  2427. /*!
  2428. * \brief
  2429. * Get the content length from an unparsed SIP message
  2430. *
  2431. * \param message The unparsed SIP message headers
  2432. * \return The value of the Content-Length header or -1 if message is invalid
  2433. */
  2434. static int read_raw_content_length(const char *message)
  2435. {
  2436. char *content_length_str;
  2437. int content_length = -1;
  2438. struct ast_str *msg_copy;
  2439. char *msg;
  2440. /* Using a ast_str because lws2sws takes one of those */
  2441. if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
  2442. return -1;
  2443. }
  2444. ast_str_set(&msg_copy, 0, "%s", message);
  2445. if (sip_cfg.pedanticsipchecking) {
  2446. lws2sws(msg_copy);
  2447. }
  2448. msg = ast_str_buffer(msg_copy);
  2449. /* Let's find a Content-Length header */
  2450. if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
  2451. content_length_str += sizeof("\nContent-Length:") - 1;
  2452. } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
  2453. content_length_str += sizeof("\nl:") - 1;
  2454. } else {
  2455. /* RFC 3261 18.3
  2456. * "In the case of stream-oriented transports such as TCP, the Content-
  2457. * Length header field indicates the size of the body. The Content-
  2458. * Length header field MUST be used with stream oriented transports."
  2459. */
  2460. goto done;
  2461. }
  2462. /* Double-check that this is a complete header */
  2463. if (!strchr(content_length_str, '\n')) {
  2464. goto done;
  2465. }
  2466. if (sscanf(content_length_str, "%30d", &content_length) != 1) {
  2467. content_length = -1;
  2468. }
  2469. done:
  2470. ast_free(msg_copy);
  2471. return content_length;
  2472. }
  2473. /*!
  2474. * \brief Check that a message received over TCP is a full message
  2475. *
  2476. * This will take the information read in and then determine if
  2477. * 1) The message is a full SIP request
  2478. * 2) The message is a partial SIP request
  2479. * 3) The message contains a full SIP request along with another partial request
  2480. * \param data The unparsed incoming SIP message.
  2481. * \param request The resulting request with extra fragments removed.
  2482. * \param overflow If the message contains more than a full request, this is the remainder of the message
  2483. * \return The resulting integrity of the message
  2484. */
  2485. static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
  2486. {
  2487. char *message = ast_str_buffer(*request);
  2488. char *body;
  2489. int content_length;
  2490. int message_len = ast_str_strlen(*request);
  2491. int body_len;
  2492. /* Important pieces to search for in a SIP request are \r\n\r\n. This
  2493. * marks either
  2494. * 1) The division between the headers and body
  2495. * 2) The end of the SIP request
  2496. */
  2497. body = strstr(message, "\r\n\r\n");
  2498. if (!body) {
  2499. /* This is clearly a partial message since we haven't reached an end
  2500. * yet.
  2501. */
  2502. return MESSAGE_FRAGMENT;
  2503. }
  2504. body += sizeof("\r\n\r\n") - 1;
  2505. body_len = message_len - (body - message);
  2506. body[-1] = '\0';
  2507. content_length = read_raw_content_length(message);
  2508. body[-1] = '\n';
  2509. if (content_length < 0) {
  2510. return MESSAGE_INVALID;
  2511. } else if (content_length == 0) {
  2512. /* We've definitely received an entire message. We need
  2513. * to check if there's also a fragment of another message
  2514. * in addition.
  2515. */
  2516. if (body_len == 0) {
  2517. return MESSAGE_COMPLETE;
  2518. } else {
  2519. ast_str_append(overflow, 0, "%s", body);
  2520. ast_str_truncate(*request, message_len - body_len);
  2521. return MESSAGE_FRAGMENT_COMPLETE;
  2522. }
  2523. }
  2524. /* Positive content length. Let's see what sort of
  2525. * message body we're dealing with.
  2526. */
  2527. if (body_len < content_length) {
  2528. /* We don't have the full message body yet */
  2529. return MESSAGE_FRAGMENT;
  2530. } else if (body_len > content_length) {
  2531. /* We have the full message plus a fragment of a further
  2532. * message
  2533. */
  2534. ast_str_append(overflow, 0, "%s", body + content_length);
  2535. ast_str_truncate(*request, message_len - (body_len - content_length));
  2536. return MESSAGE_FRAGMENT_COMPLETE;
  2537. } else {
  2538. /* Yay! Full message with no extra content */
  2539. return MESSAGE_COMPLETE;
  2540. }
  2541. }
  2542. /*!
  2543. * \brief Read SIP request or response from a TCP/TLS connection
  2544. *
  2545. * \param req The request structure to be filled in
  2546. * \param tcptls_session The TCP/TLS connection from which to read
  2547. * \retval -1 Failed to read data
  2548. * \retval 0 Successfully read data
  2549. */
  2550. static int sip_tcptls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
  2551. int authenticated, time_t start)
  2552. {
  2553. enum message_integrity message_integrity = MESSAGE_FRAGMENT;
  2554. while (message_integrity == MESSAGE_FRAGMENT) {
  2555. size_t datalen;
  2556. if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
  2557. char readbuf[4097];
  2558. int timeout;
  2559. int res;
  2560. if (!tcptls_session->client && !authenticated) {
  2561. if ((timeout = sip_check_authtimeout(start)) < 0) {
  2562. return -1;
  2563. }
  2564. if (timeout == 0) {
  2565. ast_debug(2, "SIP TCP/TLS server timed out\n");
  2566. return -1;
  2567. }
  2568. } else {
  2569. timeout = -1;
  2570. }
  2571. res = ast_wait_for_input(tcptls_session->fd, timeout);
  2572. if (res < 0) {
  2573. ast_debug(2, "SIP TCP/TLS server :: ast_wait_for_input returned %d\n", res);
  2574. return -1;
  2575. } else if (res == 0) {
  2576. ast_debug(2, "SIP TCP/TLS server timed out\n");
  2577. return -1;
  2578. }
  2579. res = ast_tcptls_server_read(tcptls_session, readbuf, sizeof(readbuf) - 1);
  2580. if (res < 0) {
  2581. if (errno == EAGAIN || errno == EINTR) {
  2582. continue;
  2583. }
  2584. ast_debug(2, "SIP TCP/TLS server error when receiving data\n");
  2585. return -1;
  2586. } else if (res == 0) {
  2587. ast_debug(2, "SIP TCP/TLS server has shut down\n");
  2588. return -1;
  2589. }
  2590. readbuf[res] = '\0';
  2591. ast_str_append(&req->data, 0, "%s", readbuf);
  2592. } else {
  2593. ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
  2594. ast_str_reset(tcptls_session->overflow_buf);
  2595. }
  2596. datalen = ast_str_strlen(req->data);
  2597. if (datalen > SIP_MAX_PACKET_SIZE) {
  2598. ast_log(LOG_WARNING, "Rejecting TCP/TLS packet from '%s' because way too large: %zu\n",
  2599. ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
  2600. return -1;
  2601. }
  2602. message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
  2603. }
  2604. return 0;
  2605. }
  2606. /*! \brief SIP TCP thread management function
  2607. This function reads from the socket, parses the packet into a request
  2608. */
  2609. static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
  2610. {
  2611. int res, timeout = -1, authenticated = 0, flags;
  2612. time_t start;
  2613. struct sip_request req = { 0, } , reqcpy = { 0, };
  2614. struct sip_threadinfo *me = NULL;
  2615. char buf[1024] = "";
  2616. struct pollfd fds[2] = { { 0 }, { 0 }, };
  2617. struct ast_tcptls_session_args *ca = NULL;
  2618. /* If this is a server session, then the connection has already been
  2619. * setup. Check if the authlimit has been reached and if not create the
  2620. * threadinfo object so we can access this thread for writing.
  2621. *
  2622. * if this is a client connection more work must be done.
  2623. * 1. We own the parent session args for a client connection. This pointer needs
  2624. * to be held on to so we can decrement it's ref count on thread destruction.
  2625. * 2. The threadinfo object was created before this thread was launched, however
  2626. * it must be found within the threadt table.
  2627. * 3. Last, the tcptls_session must be started.
  2628. */
  2629. if (!tcptls_session->client) {
  2630. if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
  2631. /* unauth_sessions is decremented in the cleanup code */
  2632. goto cleanup;
  2633. }
  2634. if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
  2635. ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
  2636. goto cleanup;
  2637. }
  2638. flags |= O_NONBLOCK;
  2639. if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
  2640. ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
  2641. goto cleanup;
  2642. }
  2643. if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? AST_TRANSPORT_TLS : AST_TRANSPORT_TCP))) {
  2644. goto cleanup;
  2645. }
  2646. ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
  2647. } else {
  2648. struct sip_threadinfo tmp = {
  2649. .tcptls_session = tcptls_session,
  2650. };
  2651. if ((!(ca = tcptls_session->parent)) ||
  2652. (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
  2653. (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
  2654. goto cleanup;
  2655. }
  2656. }
  2657. flags = 1;
  2658. if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
  2659. ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
  2660. goto cleanup;
  2661. }
  2662. me->threadid = pthread_self();
  2663. ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
  2664. /* set up pollfd to watch for reads on both the socket and the alert_pipe */
  2665. fds[0].fd = tcptls_session->fd;
  2666. fds[1].fd = me->alert_pipe[0];
  2667. fds[0].events = fds[1].events = POLLIN | POLLPRI;
  2668. if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
  2669. goto cleanup;
  2670. }
  2671. if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
  2672. goto cleanup;
  2673. }
  2674. if(time(&start) == -1) {
  2675. ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
  2676. goto cleanup;
  2677. }
  2678. /*
  2679. * We cannot let the stream exclusively wait for data to arrive.
  2680. * We have to wake up the task to send outgoing messages.
  2681. */
  2682. ast_tcptls_stream_set_exclusive_input(tcptls_session->stream_cookie, 0);
  2683. ast_tcptls_stream_set_timeout_sequence(tcptls_session->stream_cookie, ast_tvnow(),
  2684. tcptls_session->client ? -1 : (authtimeout * 1000));
  2685. for (;;) {
  2686. struct ast_str *str_save;
  2687. if (!tcptls_session->client && req.authenticated && !authenticated) {
  2688. authenticated = 1;
  2689. ast_tcptls_stream_set_timeout_disable(tcptls_session->stream_cookie);
  2690. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  2691. }
  2692. /* calculate the timeout for unauthenticated server sessions */
  2693. if (!tcptls_session->client && !authenticated ) {
  2694. if ((timeout = sip_check_authtimeout(start)) < 0) {
  2695. goto cleanup;
  2696. }
  2697. if (timeout == 0) {
  2698. ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
  2699. goto cleanup;
  2700. }
  2701. } else {
  2702. timeout = -1;
  2703. }
  2704. if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
  2705. res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
  2706. if (res < 0) {
  2707. ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
  2708. goto cleanup;
  2709. } else if (res == 0) {
  2710. /* timeout */
  2711. ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
  2712. goto cleanup;
  2713. }
  2714. }
  2715. /*
  2716. * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
  2717. * and writes from alert_pipe fd.
  2718. */
  2719. if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
  2720. fds[0].revents = 0;
  2721. /* clear request structure */
  2722. str_save = req.data;
  2723. memset(&req, 0, sizeof(req));
  2724. req.data = str_save;
  2725. ast_str_reset(req.data);
  2726. str_save = reqcpy.data;
  2727. memset(&reqcpy, 0, sizeof(reqcpy));
  2728. reqcpy.data = str_save;
  2729. ast_str_reset(reqcpy.data);
  2730. memset(buf, 0, sizeof(buf));
  2731. if (tcptls_session->ssl) {
  2732. set_socket_transport(&req.socket, AST_TRANSPORT_TLS);
  2733. req.socket.port = htons(ourport_tls);
  2734. } else {
  2735. set_socket_transport(&req.socket, AST_TRANSPORT_TCP);
  2736. req.socket.port = htons(ourport_tcp);
  2737. }
  2738. req.socket.fd = tcptls_session->fd;
  2739. res = sip_tcptls_read(&req, tcptls_session, authenticated, start);
  2740. if (res < 0) {
  2741. goto cleanup;
  2742. }
  2743. req.socket.tcptls_session = tcptls_session;
  2744. req.socket.ws_session = NULL;
  2745. handle_request_do(&req, &tcptls_session->remote_address);
  2746. }
  2747. if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
  2748. enum sip_tcptls_alert alert;
  2749. struct tcptls_packet *packet;
  2750. fds[1].revents = 0;
  2751. if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
  2752. ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
  2753. continue;
  2754. }
  2755. switch (alert) {
  2756. case TCPTLS_ALERT_STOP:
  2757. goto cleanup;
  2758. case TCPTLS_ALERT_DATA:
  2759. ao2_lock(me);
  2760. if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
  2761. ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
  2762. }
  2763. ao2_unlock(me);
  2764. if (packet) {
  2765. if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
  2766. ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
  2767. }
  2768. ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
  2769. }
  2770. break;
  2771. default:
  2772. ast_log(LOG_ERROR, "Unknown tcptls thread alert '%u'\n", alert);
  2773. }
  2774. }
  2775. }
  2776. ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
  2777. cleanup:
  2778. if (tcptls_session && !tcptls_session->client && !authenticated) {
  2779. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  2780. }
  2781. if (me) {
  2782. ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
  2783. ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
  2784. }
  2785. deinit_req(&reqcpy);
  2786. deinit_req(&req);
  2787. /* if client, we own the parent session arguments and must decrement ref */
  2788. if (ca) {
  2789. ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
  2790. }
  2791. if (tcptls_session) {
  2792. ao2_lock(tcptls_session);
  2793. ast_tcptls_close_session_file(tcptls_session);
  2794. tcptls_session->parent = NULL;
  2795. ao2_unlock(tcptls_session);
  2796. ao2_ref(tcptls_session, -1);
  2797. tcptls_session = NULL;
  2798. }
  2799. return NULL;
  2800. }
  2801. #ifdef REF_DEBUG
  2802. struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
  2803. {
  2804. if (peer)
  2805. __ao2_ref_debug(peer, 1, tag, file, line, func);
  2806. else
  2807. ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
  2808. return peer;
  2809. }
  2810. void *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
  2811. {
  2812. if (peer)
  2813. __ao2_ref_debug(peer, -1, tag, file, line, func);
  2814. return NULL;
  2815. }
  2816. #else
  2817. /*!
  2818. * helper functions to unreference various types of objects.
  2819. * By handling them this way, we don't have to declare the
  2820. * destructor on each call, which removes the chance of errors.
  2821. */
  2822. void *sip_unref_peer(struct sip_peer *peer, char *tag)
  2823. {
  2824. ao2_t_ref(peer, -1, tag);
  2825. return NULL;
  2826. }
  2827. struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag)
  2828. {
  2829. ao2_t_ref(peer, 1, tag);
  2830. return peer;
  2831. }
  2832. #endif /* REF_DEBUG */
  2833. static void peer_sched_cleanup(struct sip_peer *peer)
  2834. {
  2835. if (peer->pokeexpire != -1) {
  2836. AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
  2837. sip_unref_peer(peer, "removing poke peer ref"));
  2838. }
  2839. if (peer->expire != -1) {
  2840. AST_SCHED_DEL_UNREF(sched, peer->expire,
  2841. sip_unref_peer(peer, "remove register expire ref"));
  2842. }
  2843. if (peer->keepalivesend != -1) {
  2844. AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
  2845. sip_unref_peer(peer, "remove keepalive peer ref"));
  2846. }
  2847. }
  2848. typedef enum {
  2849. SIP_PEERS_MARKED,
  2850. SIP_PEERS_ALL,
  2851. } peer_unlink_flag_t;
  2852. /* this func is used with ao2_callback to unlink/delete all marked or linked
  2853. peers, depending on arg */
  2854. static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
  2855. {
  2856. struct sip_peer *peer = peerobj;
  2857. peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
  2858. if (which == SIP_PEERS_ALL || peer->the_mark) {
  2859. peer_sched_cleanup(peer);
  2860. if (peer->dnsmgr) {
  2861. ast_dnsmgr_release(peer->dnsmgr);
  2862. peer->dnsmgr = NULL;
  2863. sip_unref_peer(peer, "Release peer from dnsmgr");
  2864. }
  2865. return CMP_MATCH;
  2866. }
  2867. return 0;
  2868. }
  2869. static void unlink_peers_from_tables(peer_unlink_flag_t flag)
  2870. {
  2871. ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
  2872. match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
  2873. ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
  2874. match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers_by_ip");
  2875. }
  2876. /* \brief Unlink all marked peers from ao2 containers */
  2877. static void unlink_marked_peers_from_tables(void)
  2878. {
  2879. unlink_peers_from_tables(SIP_PEERS_MARKED);
  2880. }
  2881. static void unlink_all_peers_from_tables(void)
  2882. {
  2883. unlink_peers_from_tables(SIP_PEERS_ALL);
  2884. }
  2885. /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
  2886. *
  2887. * This function sets pvt's outboundproxy pointer to the one referenced
  2888. * by the proxy parameter. Because proxy may be a refcounted object, and
  2889. * because pvt's old outboundproxy may also be a refcounted object, we need
  2890. * to maintain the proper refcounts.
  2891. *
  2892. * \param pvt The sip_pvt for which we wish to set the outboundproxy
  2893. * \param proxy The sip_proxy which we will point pvt towards.
  2894. * \return Returns void
  2895. */
  2896. static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
  2897. {
  2898. struct sip_proxy *old_obproxy = pvt->outboundproxy;
  2899. /* The sip_cfg.outboundproxy is statically allocated, and so
  2900. * we don't ever need to adjust refcounts for it
  2901. */
  2902. if (proxy && proxy != &sip_cfg.outboundproxy) {
  2903. ao2_ref(proxy, +1);
  2904. }
  2905. pvt->outboundproxy = proxy;
  2906. if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
  2907. ao2_ref(old_obproxy, -1);
  2908. }
  2909. }
  2910. /*!
  2911. * \brief Unlink a dialog from the dialogs container, as well as any other places
  2912. * that it may be currently stored.
  2913. *
  2914. * \note A reference to the dialog must be held before calling this function, and this
  2915. * function does not release that reference.
  2916. */
  2917. void dialog_unlink_all(struct sip_pvt *dialog)
  2918. {
  2919. struct sip_pkt *cp;
  2920. struct ast_channel *owner;
  2921. dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
  2922. ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
  2923. ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
  2924. ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
  2925. /* Unlink us from the owner (channel) if we have one */
  2926. owner = sip_pvt_lock_full(dialog);
  2927. if (owner) {
  2928. ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
  2929. ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
  2930. ast_channel_unlock(owner);
  2931. ast_channel_unref(owner);
  2932. sip_set_owner(dialog, NULL);
  2933. }
  2934. sip_pvt_unlock(dialog);
  2935. if (dialog->registry) {
  2936. if (dialog->registry->call == dialog) {
  2937. dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
  2938. }
  2939. ao2_t_replace(dialog->registry, NULL, "delete dialog->registry");
  2940. }
  2941. if (dialog->stateid != -1) {
  2942. ast_extension_state_del(dialog->stateid, cb_extensionstate);
  2943. dialog->stateid = -1;
  2944. }
  2945. /* Remove link from peer to subscription of MWI */
  2946. if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
  2947. dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
  2948. }
  2949. if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
  2950. dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
  2951. }
  2952. /* remove all current packets in this dialog */
  2953. while((cp = dialog->packets)) {
  2954. dialog->packets = dialog->packets->next;
  2955. AST_SCHED_DEL(sched, cp->retransid);
  2956. dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
  2957. if (cp->data) {
  2958. ast_free(cp->data);
  2959. }
  2960. ast_free(cp);
  2961. }
  2962. 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"));
  2963. 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"));
  2964. if (dialog->autokillid > -1) {
  2965. 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"));
  2966. }
  2967. if (dialog->request_queue_sched_id > -1) {
  2968. 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"));
  2969. }
  2970. 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"));
  2971. if (dialog->t38id > -1) {
  2972. 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"));
  2973. }
  2974. if (dialog->stimer) {
  2975. stop_session_timer(dialog);
  2976. }
  2977. dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
  2978. }
  2979. static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
  2980. __attribute__((format(printf, 2, 3)));
  2981. /*! \brief Convert transfer status to string */
  2982. static const char *referstatus2str(enum referstatus rstatus)
  2983. {
  2984. return map_x_s(referstatusstrings, rstatus, "");
  2985. }
  2986. static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
  2987. {
  2988. if (pvt->final_destruction_scheduled) {
  2989. return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
  2990. }
  2991. append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
  2992. if (!pvt->needdestroy) {
  2993. pvt->needdestroy = 1;
  2994. ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
  2995. }
  2996. }
  2997. /*! \brief Initialize the initital request packet in the pvt structure.
  2998. This packet is used for creating replies and future requests in
  2999. a dialog */
  3000. static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
  3001. {
  3002. if (p->initreq.headers) {
  3003. ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
  3004. } else {
  3005. ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  3006. }
  3007. /* Use this as the basis */
  3008. copy_request(&p->initreq, req);
  3009. parse_request(&p->initreq);
  3010. if (req->debug) {
  3011. ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  3012. }
  3013. }
  3014. /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
  3015. static void sip_alreadygone(struct sip_pvt *dialog)
  3016. {
  3017. ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
  3018. dialog->alreadygone = 1;
  3019. }
  3020. /*! Resolve DNS srv name or host name in a sip_proxy structure */
  3021. static int proxy_update(struct sip_proxy *proxy)
  3022. {
  3023. /* if it's actually an IP address and not a name,
  3024. there's no need for a managed lookup */
  3025. if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
  3026. /* Ok, not an IP address, then let's check if it's a domain or host */
  3027. /* XXX Todo - if we have proxy port, don't do SRV */
  3028. proxy->ip.ss.ss_family = get_address_family_filter(AST_TRANSPORT_UDP); /* Filter address family */
  3029. if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
  3030. ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
  3031. return FALSE;
  3032. }
  3033. }
  3034. ast_sockaddr_set_port(&proxy->ip, proxy->port);
  3035. proxy->last_dnsupdate = time(NULL);
  3036. return TRUE;
  3037. }
  3038. /*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is
  3039. * non-NULL, no allocation is performed and dest is used instead.
  3040. * On error NULL is returned. */
  3041. static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
  3042. {
  3043. char *mutable_proxy, *sep, *name;
  3044. int allocated = 0;
  3045. if (!dest) {
  3046. dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
  3047. if (!dest) {
  3048. ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
  3049. return NULL;
  3050. }
  3051. allocated = 1;
  3052. }
  3053. /* Format is: [transport://]name[:port][,force] */
  3054. mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
  3055. sep = strchr(mutable_proxy, ',');
  3056. if (sep) {
  3057. *sep++ = '\0';
  3058. dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
  3059. } else {
  3060. dest->force = FALSE;
  3061. }
  3062. sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
  3063. /* Check that there is a name at all */
  3064. if (ast_strlen_zero(name)) {
  3065. if (allocated) {
  3066. ao2_ref(dest, -1);
  3067. } else {
  3068. dest->name[0] = '\0';
  3069. }
  3070. return NULL;
  3071. }
  3072. ast_copy_string(dest->name, name, sizeof(dest->name));
  3073. /* Resolve host immediately */
  3074. proxy_update(dest);
  3075. return dest;
  3076. }
  3077. /*! \brief converts ascii port to int representation. If no
  3078. * pt buffer is provided or the pt has errors when being converted
  3079. * to an int value, the port provided as the standard is used.
  3080. */
  3081. unsigned int port_str2int(const char *pt, unsigned int standard)
  3082. {
  3083. int port = standard;
  3084. if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
  3085. port = standard;
  3086. }
  3087. return port;
  3088. }
  3089. /*! \brief Get default outbound proxy or global proxy */
  3090. static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
  3091. {
  3092. if (dialog && dialog->options && dialog->options->outboundproxy) {
  3093. if (sipdebug) {
  3094. ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
  3095. }
  3096. append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
  3097. return dialog->options->outboundproxy;
  3098. }
  3099. if (peer && peer->outboundproxy) {
  3100. if (sipdebug) {
  3101. ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
  3102. }
  3103. append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
  3104. return peer->outboundproxy;
  3105. }
  3106. if (sip_cfg.outboundproxy.name[0]) {
  3107. if (sipdebug) {
  3108. ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
  3109. }
  3110. append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
  3111. return &sip_cfg.outboundproxy;
  3112. }
  3113. if (sipdebug) {
  3114. ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
  3115. }
  3116. return NULL;
  3117. }
  3118. /*! \brief returns true if 'name' (with optional trailing whitespace)
  3119. * matches the sip method 'id'.
  3120. * Strictly speaking, SIP methods are case SENSITIVE, but we do
  3121. * a case-insensitive comparison to be more tolerant.
  3122. * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
  3123. */
  3124. static int method_match(enum sipmethod id, const char *name)
  3125. {
  3126. int len = strlen(sip_methods[id].text);
  3127. int l_name = name ? strlen(name) : 0;
  3128. /* true if the string is long enough, and ends with whitespace, and matches */
  3129. return (l_name >= len && name && name[len] < 33 &&
  3130. !strncasecmp(sip_methods[id].text, name, len));
  3131. }
  3132. /*! \brief find_sip_method: Find SIP method from header */
  3133. static int find_sip_method(const char *msg)
  3134. {
  3135. int i, res = 0;
  3136. if (ast_strlen_zero(msg)) {
  3137. return 0;
  3138. }
  3139. for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
  3140. if (method_match(i, msg)) {
  3141. res = sip_methods[i].id;
  3142. }
  3143. }
  3144. return res;
  3145. }
  3146. /*! \brief See if we pass debug IP filter */
  3147. static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
  3148. {
  3149. /* Can't debug if sipdebug is not enabled */
  3150. if (!sipdebug) {
  3151. return 0;
  3152. }
  3153. /* A null debug_addr means we'll debug any address */
  3154. if (ast_sockaddr_isnull(&debugaddr)) {
  3155. return 1;
  3156. }
  3157. /* If no port was specified for a debug address, just compare the
  3158. * addresses, otherwise compare the address and port
  3159. */
  3160. if (ast_sockaddr_port(&debugaddr)) {
  3161. return !ast_sockaddr_cmp(&debugaddr, addr);
  3162. } else {
  3163. return !ast_sockaddr_cmp_addr(&debugaddr, addr);
  3164. }
  3165. }
  3166. /*! \brief The real destination address for a write */
  3167. static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
  3168. {
  3169. if (p->outboundproxy) {
  3170. return &p->outboundproxy->ip;
  3171. }
  3172. 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;
  3173. }
  3174. /*! \brief Display SIP nat mode */
  3175. static const char *sip_nat_mode(const struct sip_pvt *p)
  3176. {
  3177. return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
  3178. }
  3179. /*! \brief Test PVT for debugging output */
  3180. static inline int sip_debug_test_pvt(struct sip_pvt *p)
  3181. {
  3182. if (!sipdebug) {
  3183. return 0;
  3184. }
  3185. return sip_debug_test_addr(sip_real_dst(p));
  3186. }
  3187. /*! \brief Return int representing a bit field of transport types found in const char *transport */
  3188. static int get_transport_str2enum(const char *transport)
  3189. {
  3190. int res = 0;
  3191. if (ast_strlen_zero(transport)) {
  3192. return res;
  3193. }
  3194. if (!strcasecmp(transport, "udp")) {
  3195. res |= AST_TRANSPORT_UDP;
  3196. }
  3197. if (!strcasecmp(transport, "tcp")) {
  3198. res |= AST_TRANSPORT_TCP;
  3199. }
  3200. if (!strcasecmp(transport, "tls")) {
  3201. res |= AST_TRANSPORT_TLS;
  3202. }
  3203. if (!strcasecmp(transport, "ws")) {
  3204. res |= AST_TRANSPORT_WS;
  3205. }
  3206. if (!strcasecmp(transport, "wss")) {
  3207. res |= AST_TRANSPORT_WSS;
  3208. }
  3209. return res;
  3210. }
  3211. /*! \brief Return configuration of transports for a device */
  3212. static inline const char *get_transport_list(unsigned int transports)
  3213. {
  3214. char *buf;
  3215. if (!transports) {
  3216. return "UNKNOWN";
  3217. }
  3218. if (!(buf = ast_threadstorage_get(&sip_transport_str_buf, SIP_TRANSPORT_STR_BUFSIZE))) {
  3219. return "";
  3220. }
  3221. memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
  3222. if (transports & AST_TRANSPORT_UDP) {
  3223. strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
  3224. }
  3225. if (transports & AST_TRANSPORT_TCP) {
  3226. strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
  3227. }
  3228. if (transports & AST_TRANSPORT_TLS) {
  3229. strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
  3230. }
  3231. if (transports & AST_TRANSPORT_WS) {
  3232. strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
  3233. }
  3234. if (transports & AST_TRANSPORT_WSS) {
  3235. strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
  3236. }
  3237. /* Remove the trailing ',' if present */
  3238. if (strlen(buf)) {
  3239. buf[strlen(buf) - 1] = 0;
  3240. }
  3241. return buf;
  3242. }
  3243. /*! \brief Return transport as string */
  3244. const char *sip_get_transport(enum ast_transport t)
  3245. {
  3246. switch (t) {
  3247. case AST_TRANSPORT_UDP:
  3248. return "UDP";
  3249. case AST_TRANSPORT_TCP:
  3250. return "TCP";
  3251. case AST_TRANSPORT_TLS:
  3252. return "TLS";
  3253. case AST_TRANSPORT_WS:
  3254. case AST_TRANSPORT_WSS:
  3255. return "WS";
  3256. }
  3257. return "UNKNOWN";
  3258. }
  3259. /*! \brief Return protocol string for srv dns query */
  3260. static inline const char *get_srv_protocol(enum ast_transport t)
  3261. {
  3262. switch (t) {
  3263. case AST_TRANSPORT_UDP:
  3264. return "udp";
  3265. case AST_TRANSPORT_WS:
  3266. return "ws";
  3267. case AST_TRANSPORT_TLS:
  3268. case AST_TRANSPORT_TCP:
  3269. return "tcp";
  3270. case AST_TRANSPORT_WSS:
  3271. return "wss";
  3272. }
  3273. return "udp";
  3274. }
  3275. /*! \brief Return service string for srv dns query */
  3276. static inline const char *get_srv_service(enum ast_transport t)
  3277. {
  3278. switch (t) {
  3279. case AST_TRANSPORT_TCP:
  3280. case AST_TRANSPORT_UDP:
  3281. case AST_TRANSPORT_WS:
  3282. return "sip";
  3283. case AST_TRANSPORT_TLS:
  3284. case AST_TRANSPORT_WSS:
  3285. return "sips";
  3286. }
  3287. return "sip";
  3288. }
  3289. /*! \brief Return transport of dialog.
  3290. \note this is based on a false assumption. We don't always use the
  3291. outbound proxy for all requests in a dialog. It depends on the
  3292. "force" parameter. The FIRST request is always sent to the ob proxy.
  3293. \todo Fix this function to work correctly
  3294. */
  3295. static inline const char *get_transport_pvt(struct sip_pvt *p)
  3296. {
  3297. if (p->outboundproxy && p->outboundproxy->transport) {
  3298. set_socket_transport(&p->socket, p->outboundproxy->transport);
  3299. }
  3300. return sip_get_transport(p->socket.type);
  3301. }
  3302. /*!
  3303. * \internal
  3304. * \brief Transmit SIP message
  3305. *
  3306. * \details
  3307. * Sends a SIP request or response on a given socket (in the pvt)
  3308. * \note
  3309. * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
  3310. *
  3311. * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
  3312. */
  3313. static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
  3314. {
  3315. int res = 0;
  3316. const struct ast_sockaddr *dst = sip_real_dst(p);
  3317. 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));
  3318. if (sip_prepare_socket(p) < 0) {
  3319. return XMIT_ERROR;
  3320. }
  3321. if (p->socket.type == AST_TRANSPORT_UDP) {
  3322. res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
  3323. } else if (p->socket.tcptls_session) {
  3324. res = sip_tcptls_write(p->socket.tcptls_session, ast_str_buffer(data), ast_str_strlen(data));
  3325. } else if (p->socket.ws_session) {
  3326. if (!(res = ast_websocket_write(p->socket.ws_session, AST_WEBSOCKET_OPCODE_TEXT, ast_str_buffer(data), ast_str_strlen(data)))) {
  3327. /* The WebSocket API just returns 0 on success and -1 on failure, while this code expects the payload length to be returned */
  3328. res = ast_str_strlen(data);
  3329. }
  3330. } else {
  3331. ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
  3332. return XMIT_ERROR;
  3333. }
  3334. if (res == -1) {
  3335. switch (errno) {
  3336. case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
  3337. case EHOSTUNREACH: /* Host can't be reached */
  3338. case ENETDOWN: /* Interface down */
  3339. case ENETUNREACH: /* Network failure */
  3340. case ECONNREFUSED: /* ICMP port unreachable */
  3341. res = XMIT_ERROR; /* Don't bother with trying to transmit again */
  3342. }
  3343. }
  3344. if (res != ast_str_strlen(data)) {
  3345. 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));
  3346. }
  3347. return res;
  3348. }
  3349. /*! \brief Build a Via header for a request */
  3350. static void build_via(struct sip_pvt *p)
  3351. {
  3352. /* Work around buggy UNIDEN UIP200 firmware */
  3353. const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
  3354. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  3355. snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
  3356. get_transport_pvt(p),
  3357. ast_sockaddr_stringify_remote(&p->ourip),
  3358. (unsigned)p->branch, rport);
  3359. }
  3360. /*! \brief NAT fix - decide which IP address to use for Asterisk server?
  3361. *
  3362. * Using the localaddr structure built up with localnet statements in sip.conf
  3363. * apply it to their address to see if we need to substitute our
  3364. * externaddr or can get away with our internal bindaddr
  3365. * 'us' is always overwritten.
  3366. */
  3367. static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
  3368. {
  3369. struct ast_sockaddr theirs;
  3370. /* Set want_remap to non-zero if we want to remap 'us' to an externally
  3371. * reachable IP address and port. This is done if:
  3372. * 1. we have a localaddr list (containing 'internal' addresses marked
  3373. * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
  3374. * and AST_SENSE_ALLOW on 'external' ones);
  3375. * 2. externaddr is set, so we know what to use as the
  3376. * externally visible address;
  3377. * 3. the remote address, 'them', is external;
  3378. * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
  3379. * when passed to ast_apply_ha() so it does need to be remapped.
  3380. * This fourth condition is checked later.
  3381. */
  3382. int want_remap = 0;
  3383. ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
  3384. /* now ask the system what would it use to talk to 'them' */
  3385. ast_ouraddrfor(them, us);
  3386. ast_sockaddr_copy(&theirs, them);
  3387. if (ast_sockaddr_is_ipv6(&theirs)) {
  3388. if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
  3389. ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
  3390. "but we're using IPv6, which doesn't need it. Please "
  3391. "remove \"localnet\" and/or \"externaddr\" settings.\n");
  3392. }
  3393. } else {
  3394. want_remap = localaddr &&
  3395. !ast_sockaddr_isnull(&externaddr) &&
  3396. ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
  3397. }
  3398. if (want_remap &&
  3399. (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
  3400. /* if we used externhost, see if it is time to refresh the info */
  3401. if (externexpire && time(NULL) >= externexpire) {
  3402. if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
  3403. ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
  3404. }
  3405. externexpire = time(NULL) + externrefresh;
  3406. }
  3407. if (!ast_sockaddr_isnull(&externaddr)) {
  3408. ast_sockaddr_copy(us, &externaddr);
  3409. switch (p->socket.type) {
  3410. case AST_TRANSPORT_TCP:
  3411. if (!externtcpport && ast_sockaddr_port(&externaddr)) {
  3412. /* for consistency, default to the externaddr port */
  3413. externtcpport = ast_sockaddr_port(&externaddr);
  3414. }
  3415. ast_sockaddr_set_port(us, externtcpport);
  3416. break;
  3417. case AST_TRANSPORT_TLS:
  3418. ast_sockaddr_set_port(us, externtlsport);
  3419. break;
  3420. case AST_TRANSPORT_UDP:
  3421. if (!ast_sockaddr_port(&externaddr)) {
  3422. ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
  3423. }
  3424. break;
  3425. default:
  3426. break;
  3427. }
  3428. }
  3429. ast_debug(1, "Target address %s is not local, substituting externaddr\n",
  3430. ast_sockaddr_stringify(them));
  3431. } else {
  3432. /* no remapping, but we bind to a specific address, so use it. */
  3433. switch (p->socket.type) {
  3434. case AST_TRANSPORT_TCP:
  3435. if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
  3436. ast_sockaddr_copy(us,
  3437. &sip_tcp_desc.local_address);
  3438. } else {
  3439. ast_sockaddr_set_port(us,
  3440. ast_sockaddr_port(&sip_tcp_desc.local_address));
  3441. }
  3442. break;
  3443. case AST_TRANSPORT_TLS:
  3444. if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
  3445. ast_sockaddr_copy(us,
  3446. &sip_tls_desc.local_address);
  3447. } else {
  3448. ast_sockaddr_set_port(us,
  3449. ast_sockaddr_port(&sip_tls_desc.local_address));
  3450. }
  3451. break;
  3452. case AST_TRANSPORT_UDP:
  3453. /* fall through on purpose */
  3454. default:
  3455. if (!ast_sockaddr_is_any(&bindaddr)) {
  3456. ast_sockaddr_copy(us, &bindaddr);
  3457. }
  3458. if (!ast_sockaddr_port(us)) {
  3459. ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
  3460. }
  3461. }
  3462. }
  3463. ast_debug(3, "Setting AST_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
  3464. }
  3465. /*! \brief Append to SIP dialog history with arg list */
  3466. static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
  3467. {
  3468. char buf[80], *c = buf; /* max history length */
  3469. struct sip_history *hist;
  3470. int l;
  3471. vsnprintf(buf, sizeof(buf), fmt, ap);
  3472. strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
  3473. l = strlen(buf) + 1;
  3474. if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
  3475. return;
  3476. }
  3477. if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
  3478. ast_free(hist);
  3479. return;
  3480. }
  3481. memcpy(hist->event, buf, l);
  3482. if (p->history_entries == MAX_HISTORY_ENTRIES) {
  3483. struct sip_history *oldest;
  3484. oldest = AST_LIST_REMOVE_HEAD(p->history, list);
  3485. p->history_entries--;
  3486. ast_free(oldest);
  3487. }
  3488. AST_LIST_INSERT_TAIL(p->history, hist, list);
  3489. p->history_entries++;
  3490. }
  3491. /*! \brief Append to SIP dialog history with arg list */
  3492. static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
  3493. {
  3494. va_list ap;
  3495. if (!p) {
  3496. return;
  3497. }
  3498. if (!p->do_history && !recordhistory && !dumphistory) {
  3499. return;
  3500. }
  3501. va_start(ap, fmt);
  3502. append_history_va(p, fmt, ap);
  3503. va_end(ap);
  3504. return;
  3505. }
  3506. /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
  3507. static int retrans_pkt(const void *data)
  3508. {
  3509. struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
  3510. int reschedule = DEFAULT_RETRANS;
  3511. int xmitres = 0;
  3512. /* how many ms until retrans timeout is reached */
  3513. int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
  3514. /* Do not retransmit if time out is reached. This will be negative if the time between
  3515. * the first transmission and now is larger than our timeout period. This is a fail safe
  3516. * check in case the scheduler gets behind or the clock is changed. */
  3517. if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
  3518. pkt->retrans_stop = 1;
  3519. }
  3520. /* Lock channel PVT */
  3521. sip_pvt_lock(pkt->owner);
  3522. if (!pkt->retrans_stop) {
  3523. pkt->retrans++;
  3524. if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
  3525. if (sipdebug) {
  3526. ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
  3527. pkt->retransid,
  3528. sip_methods[pkt->method].text,
  3529. pkt->method);
  3530. }
  3531. } else {
  3532. int siptimer_a;
  3533. if (sipdebug) {
  3534. ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
  3535. pkt->retransid,
  3536. pkt->retrans,
  3537. sip_methods[pkt->method].text,
  3538. pkt->method);
  3539. }
  3540. if (!pkt->timer_a) {
  3541. pkt->timer_a = 2 ;
  3542. } else {
  3543. pkt->timer_a = 2 * pkt->timer_a;
  3544. }
  3545. /* For non-invites, a maximum of 4 secs */
  3546. siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
  3547. if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
  3548. siptimer_a = 4000;
  3549. }
  3550. /* Reschedule re-transmit */
  3551. reschedule = siptimer_a;
  3552. ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
  3553. pkt->retrans + 1,
  3554. siptimer_a,
  3555. pkt->timer_t1,
  3556. pkt->retransid);
  3557. }
  3558. if (sip_debug_test_pvt(pkt->owner)) {
  3559. const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
  3560. ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
  3561. pkt->retrans, sip_nat_mode(pkt->owner),
  3562. ast_sockaddr_stringify(dst),
  3563. ast_str_buffer(pkt->data));
  3564. }
  3565. append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
  3566. xmitres = __sip_xmit(pkt->owner, pkt->data);
  3567. /* If there was no error during the network transmission, schedule the next retransmission,
  3568. * but if the next retransmission is going to be beyond our timeout period, mark the packet's
  3569. * stop_retrans value and set the next retransmit to be the exact time of timeout. This will
  3570. * allow any responses to the packet to be processed before the packet is destroyed on the next
  3571. * call to this function by the scheduler. */
  3572. if (xmitres != XMIT_ERROR) {
  3573. if (reschedule >= diff) {
  3574. pkt->retrans_stop = 1;
  3575. reschedule = diff;
  3576. }
  3577. sip_pvt_unlock(pkt->owner);
  3578. return reschedule;
  3579. }
  3580. }
  3581. /* At this point, either the packet's retransmission timed out, or there was a
  3582. * transmission error, either way destroy the scheduler item and this packet. */
  3583. pkt->retransid = -1; /* Kill this scheduler item */
  3584. if (pkt->method != SIP_OPTIONS && xmitres == 0) {
  3585. if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
  3586. 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"
  3587. "Packet timed out after %dms with no response\n",
  3588. pkt->owner->callid,
  3589. pkt->seqno,
  3590. pkt->is_fatal ? "Critical" : "Non-critical",
  3591. pkt->is_resp ? "Response" : "Request",
  3592. (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
  3593. }
  3594. } else if (pkt->method == SIP_OPTIONS && sipdebug) {
  3595. 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);
  3596. }
  3597. if (xmitres == XMIT_ERROR) {
  3598. ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
  3599. append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
  3600. } else {
  3601. append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
  3602. }
  3603. if (pkt->is_fatal) {
  3604. while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
  3605. sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
  3606. usleep(1);
  3607. sip_pvt_lock(pkt->owner);
  3608. }
  3609. if (pkt->owner->owner && !ast_channel_hangupcause(pkt->owner->owner)) {
  3610. ast_channel_hangupcause_set(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
  3611. }
  3612. if (pkt->owner->owner) {
  3613. 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);
  3614. if (pkt->is_resp &&
  3615. (pkt->response_code >= 200) &&
  3616. (pkt->response_code < 300) &&
  3617. pkt->owner->pendinginvite &&
  3618. ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  3619. /* This is a timeout of the 2XX response to a pending INVITE. In this case terminate the INVITE
  3620. * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
  3621. * will send the BYE as long as the dialog is not set as "alreadygone")
  3622. * RFC 3261 section 13.3.1.4.
  3623. * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
  3624. * an ACK, the dialog is confirmed, but the session SHOULD be terminated. This is
  3625. * accomplished with a BYE, as described in Section 15." */
  3626. pkt->owner->invitestate = INV_TERMINATED;
  3627. pkt->owner->pendinginvite = 0;
  3628. } else {
  3629. /* there is nothing left to do, mark the dialog as gone */
  3630. sip_alreadygone(pkt->owner);
  3631. }
  3632. ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
  3633. ast_channel_unlock(pkt->owner->owner);
  3634. } else {
  3635. /* If no channel owner, destroy now */
  3636. /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
  3637. if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
  3638. pvt_set_needdestroy(pkt->owner, "no response to critical packet");
  3639. sip_alreadygone(pkt->owner);
  3640. append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
  3641. }
  3642. }
  3643. } else if (pkt->owner->pendinginvite == pkt->seqno) {
  3644. ast_log(LOG_WARNING, "Timeout on %s on non-critical invite transaction.\n", pkt->owner->callid);
  3645. pkt->owner->invitestate = INV_TERMINATED;
  3646. pkt->owner->pendinginvite = 0;
  3647. check_pendings(pkt->owner);
  3648. }
  3649. if (pkt->method == SIP_BYE) {
  3650. /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
  3651. sip_alreadygone(pkt->owner);
  3652. if (pkt->owner->owner) {
  3653. ast_channel_unlock(pkt->owner->owner);
  3654. }
  3655. append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
  3656. pvt_set_needdestroy(pkt->owner, "no response to BYE");
  3657. }
  3658. /* Remove the packet */
  3659. for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
  3660. if (cur == pkt) {
  3661. UNLINK(cur, pkt->owner->packets, prev);
  3662. sip_pvt_unlock(pkt->owner);
  3663. if (pkt->owner) {
  3664. pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
  3665. }
  3666. if (pkt->data) {
  3667. ast_free(pkt->data);
  3668. }
  3669. pkt->data = NULL;
  3670. ast_free(pkt);
  3671. return 0;
  3672. }
  3673. }
  3674. /* error case */
  3675. ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
  3676. sip_pvt_unlock(pkt->owner);
  3677. return 0;
  3678. }
  3679. /*!
  3680. * \internal
  3681. * \brief Transmit packet with retransmits
  3682. * \return 0 on success, -1 on failure to allocate packet
  3683. */
  3684. static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
  3685. {
  3686. struct sip_pkt *pkt = NULL;
  3687. int siptimer_a = DEFAULT_RETRANS;
  3688. int xmitres = 0;
  3689. unsigned respid;
  3690. if (sipmethod == SIP_INVITE) {
  3691. /* Note this is a pending invite */
  3692. p->pendinginvite = seqno;
  3693. }
  3694. /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
  3695. /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
  3696. /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
  3697. if (!(p->socket.type & AST_TRANSPORT_UDP)) {
  3698. xmitres = __sip_xmit(p, data); /* Send packet */
  3699. if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
  3700. append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
  3701. return AST_FAILURE;
  3702. } else {
  3703. return AST_SUCCESS;
  3704. }
  3705. }
  3706. if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
  3707. return AST_FAILURE;
  3708. }
  3709. /* copy data, add a terminator and save length */
  3710. if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
  3711. ast_free(pkt);
  3712. return AST_FAILURE;
  3713. }
  3714. ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
  3715. /* copy other parameters from the caller */
  3716. pkt->method = sipmethod;
  3717. pkt->seqno = seqno;
  3718. pkt->is_resp = resp;
  3719. pkt->is_fatal = fatal;
  3720. pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
  3721. pkt->next = p->packets;
  3722. p->packets = pkt; /* Add it to the queue */
  3723. if (resp) {
  3724. /* Parse out the response code */
  3725. if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
  3726. pkt->response_code = respid;
  3727. }
  3728. }
  3729. pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
  3730. pkt->retransid = -1;
  3731. if (pkt->timer_t1) {
  3732. siptimer_a = pkt->timer_t1;
  3733. }
  3734. pkt->time_sent = ast_tvnow(); /* time packet was sent */
  3735. pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
  3736. /* Schedule retransmission */
  3737. AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
  3738. if (sipdebug) {
  3739. ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
  3740. }
  3741. xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
  3742. if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
  3743. append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
  3744. ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
  3745. AST_SCHED_DEL(sched, pkt->retransid);
  3746. p->packets = pkt->next;
  3747. pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
  3748. ast_free(pkt->data);
  3749. ast_free(pkt);
  3750. return AST_FAILURE;
  3751. } else {
  3752. /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
  3753. * only wakes up every 1000ms by default, we have to poke the thread here to make
  3754. * sure it successfully detects this must be retransmitted in less time than
  3755. * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
  3756. if (monitor_thread != AST_PTHREADT_NULL) {
  3757. pthread_kill(monitor_thread, SIGURG);
  3758. }
  3759. return AST_SUCCESS;
  3760. }
  3761. }
  3762. /*! \brief Kill a SIP dialog (called only by the scheduler)
  3763. * The scheduler has a reference to this dialog when p->autokillid != -1,
  3764. * and we are called using that reference. So if the event is not
  3765. * rescheduled, we need to call dialog_unref().
  3766. */
  3767. static int __sip_autodestruct(const void *data)
  3768. {
  3769. struct sip_pvt *p = (struct sip_pvt *)data;
  3770. struct ast_channel *owner;
  3771. /* If this is a subscription, tell the phone that we got a timeout */
  3772. if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
  3773. struct state_notify_data data = { 0, };
  3774. data.state = AST_EXTENSION_DEACTIVATED;
  3775. transmit_state_notify(p, &data, 1, TRUE); /* Send last notification */
  3776. p->subscribed = NONE;
  3777. append_history(p, "Subscribestatus", "timeout");
  3778. ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
  3779. return 10000; /* Reschedule this destruction so that we know that it's gone */
  3780. }
  3781. /* If there are packets still waiting for delivery, delay the destruction */
  3782. if (p->packets) {
  3783. if (!p->needdestroy) {
  3784. char method_str[31];
  3785. ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
  3786. append_history(p, "ReliableXmit", "timeout");
  3787. if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
  3788. if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
  3789. pvt_set_needdestroy(p, "autodestruct");
  3790. }
  3791. }
  3792. return 10000;
  3793. } else {
  3794. /* They've had their chance to respond. Time to bail */
  3795. __sip_pretend_ack(p);
  3796. }
  3797. }
  3798. /* Reset schedule ID */
  3799. p->autokillid = -1;
  3800. /*
  3801. * Lock both the pvt and the channel safely so that we can queue up a frame.
  3802. */
  3803. owner = sip_pvt_lock_full(p);
  3804. if (owner) {
  3805. 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);
  3806. ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
  3807. ast_channel_unlock(owner);
  3808. ast_channel_unref(owner);
  3809. sip_pvt_unlock(p);
  3810. return 10000;
  3811. } else if (p->refer && !p->alreadygone) {
  3812. ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
  3813. stop_media_flows(p);
  3814. transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
  3815. append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
  3816. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  3817. } else {
  3818. append_history(p, "AutoDestroy", "%s", p->callid);
  3819. ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
  3820. sip_pvt_unlock(p);
  3821. dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
  3822. sip_pvt_lock(p);
  3823. /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
  3824. /* sip_destroy(p); */ /* Go ahead and destroy dialog. All attempts to recover is done */
  3825. /* sip_destroy also absorbs the reference */
  3826. }
  3827. sip_pvt_unlock(p);
  3828. dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
  3829. return 0;
  3830. }
  3831. /*! \brief Schedule final destruction of SIP dialog. This can not be canceled.
  3832. * This function is used to keep a dialog around for a period of time in order
  3833. * to properly respond to any retransmits. */
  3834. void sip_scheddestroy_final(struct sip_pvt *p, int ms)
  3835. {
  3836. if (p->final_destruction_scheduled) {
  3837. return; /* already set final destruction */
  3838. }
  3839. sip_scheddestroy(p, ms);
  3840. if (p->autokillid != -1) {
  3841. p->final_destruction_scheduled = 1;
  3842. }
  3843. }
  3844. /*! \brief Schedule destruction of SIP dialog */
  3845. void sip_scheddestroy(struct sip_pvt *p, int ms)
  3846. {
  3847. if (p->final_destruction_scheduled) {
  3848. return; /* already set final destruction */
  3849. }
  3850. if (ms < 0) {
  3851. if (p->timer_t1 == 0) {
  3852. p->timer_t1 = global_t1; /* Set timer T1 if not set (RFC 3261) */
  3853. }
  3854. if (p->timer_b == 0) {
  3855. p->timer_b = global_timer_b; /* Set timer B if not set (RFC 3261) */
  3856. }
  3857. ms = p->timer_t1 * 64;
  3858. }
  3859. if (sip_debug_test_pvt(p)) {
  3860. ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
  3861. }
  3862. if (sip_cancel_destroy(p)) {
  3863. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  3864. }
  3865. if (p->do_history) {
  3866. append_history(p, "SchedDestroy", "%d ms", ms);
  3867. }
  3868. p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
  3869. if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
  3870. stop_session_timer(p);
  3871. }
  3872. }
  3873. /*! \brief Cancel destruction of SIP dialog.
  3874. * Be careful as this also absorbs the reference - if you call it
  3875. * from within the scheduler, this might be the last reference.
  3876. */
  3877. int sip_cancel_destroy(struct sip_pvt *p)
  3878. {
  3879. if (p->final_destruction_scheduled) {
  3880. return 0;
  3881. }
  3882. if (p->autokillid > -1) {
  3883. append_history(p, "CancelDestroy", "");
  3884. AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
  3885. }
  3886. return 0;
  3887. }
  3888. /*! \brief Acknowledges receipt of a packet and stops retransmission
  3889. * called with p locked*/
  3890. int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
  3891. {
  3892. struct sip_pkt *cur, *prev = NULL;
  3893. const char *msg = "Not Found"; /* used only for debugging */
  3894. int res = FALSE;
  3895. /* If we have an outbound proxy for this dialog, then delete it now since
  3896. the rest of the requests in this dialog needs to follow the routing.
  3897. If obforcing is set, we will keep the outbound proxy during the whole
  3898. dialog, regardless of what the SIP rfc says
  3899. */
  3900. if (p->outboundproxy && !p->outboundproxy->force) {
  3901. ref_proxy(p, NULL);
  3902. }
  3903. for (cur = p->packets; cur; prev = cur, cur = cur->next) {
  3904. if (cur->seqno != seqno || cur->is_resp != resp) {
  3905. continue;
  3906. }
  3907. if (cur->is_resp || cur->method == sipmethod) {
  3908. res = TRUE;
  3909. msg = "Found";
  3910. if (!resp && (seqno == p->pendinginvite)) {
  3911. ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
  3912. p->pendinginvite = 0;
  3913. }
  3914. if (cur->retransid > -1) {
  3915. if (sipdebug)
  3916. ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
  3917. }
  3918. /* This odd section is designed to thwart a
  3919. * race condition in the packet scheduler. There are
  3920. * two conditions under which deleting the packet from the
  3921. * scheduler can fail.
  3922. *
  3923. * 1. The packet has been removed from the scheduler because retransmission
  3924. * is being attempted. The problem is that if the packet is currently attempting
  3925. * retransmission and we are at this point in the code, then that MUST mean
  3926. * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
  3927. * lock temporarily to allow retransmission.
  3928. *
  3929. * 2. The packet has reached its maximum number of retransmissions and has
  3930. * been permanently removed from the packet scheduler. If this is the case, then
  3931. * the packet's retransid will be set to -1. The atomicity of the setting and checking
  3932. * of the retransid to -1 is ensured since in both cases p's lock is held.
  3933. */
  3934. while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
  3935. sip_pvt_unlock(p);
  3936. usleep(1);
  3937. sip_pvt_lock(p);
  3938. }
  3939. UNLINK(cur, p->packets, prev);
  3940. dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
  3941. if (cur->data) {
  3942. ast_free(cur->data);
  3943. }
  3944. ast_free(cur);
  3945. break;
  3946. }
  3947. }
  3948. ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
  3949. p->callid, resp ? "Response" : "Request", seqno, msg);
  3950. return res;
  3951. }
  3952. /*! \brief Pretend to ack all packets
  3953. * called with p locked */
  3954. void __sip_pretend_ack(struct sip_pvt *p)
  3955. {
  3956. struct sip_pkt *cur = NULL;
  3957. while (p->packets) {
  3958. int method;
  3959. if (cur == p->packets) {
  3960. ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
  3961. return;
  3962. }
  3963. cur = p->packets;
  3964. method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
  3965. __sip_ack(p, cur->seqno, cur->is_resp, method);
  3966. }
  3967. }
  3968. /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
  3969. int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
  3970. {
  3971. struct sip_pkt *cur;
  3972. int res = FALSE;
  3973. for (cur = p->packets; cur; cur = cur->next) {
  3974. if (cur->seqno == seqno && cur->is_resp == resp &&
  3975. (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
  3976. /* this is our baby */
  3977. if (cur->retransid > -1) {
  3978. if (sipdebug)
  3979. ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
  3980. }
  3981. AST_SCHED_DEL(sched, cur->retransid);
  3982. res = TRUE;
  3983. break;
  3984. }
  3985. }
  3986. 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");
  3987. return res;
  3988. }
  3989. /*! \brief Copy SIP request, parse it */
  3990. static void parse_copy(struct sip_request *dst, const struct sip_request *src)
  3991. {
  3992. copy_request(dst, src);
  3993. parse_request(dst);
  3994. }
  3995. /*! \brief add a blank line if no body */
  3996. static void add_blank(struct sip_request *req)
  3997. {
  3998. if (!req->lines) {
  3999. /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
  4000. ast_str_append(&req->data, 0, "\r\n");
  4001. }
  4002. }
  4003. static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
  4004. {
  4005. const char *msg = NULL;
  4006. struct ast_channel *chan;
  4007. int res = 0;
  4008. int old_sched_id = pvt->provisional_keepalive_sched_id;
  4009. chan = sip_pvt_lock_full(pvt);
  4010. /* Check that nothing has changed while we were waiting for the lock */
  4011. if (old_sched_id != pvt->provisional_keepalive_sched_id) {
  4012. /* Keepalive has been cancelled or rescheduled, clean up and leave */
  4013. if (chan) {
  4014. ast_channel_unlock(chan);
  4015. chan = ast_channel_unref(chan);
  4016. }
  4017. sip_pvt_unlock(pvt);
  4018. dialog_unref(pvt, "dialog ref for provisional keepalive");
  4019. return 0;
  4020. }
  4021. if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
  4022. msg = "183 Session Progress";
  4023. }
  4024. if (pvt->invitestate < INV_COMPLETED) {
  4025. if (with_sdp) {
  4026. transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
  4027. } else {
  4028. transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
  4029. }
  4030. res = PROVIS_KEEPALIVE_TIMEOUT;
  4031. }
  4032. if (chan) {
  4033. ast_channel_unlock(chan);
  4034. chan = ast_channel_unref(chan);
  4035. }
  4036. if (!res) {
  4037. pvt->provisional_keepalive_sched_id = -1;
  4038. }
  4039. sip_pvt_unlock(pvt);
  4040. if (!res) {
  4041. dialog_unref(pvt, "dialog ref for provisional keepalive");
  4042. }
  4043. return res;
  4044. }
  4045. static int send_provisional_keepalive(const void *data)
  4046. {
  4047. struct sip_pvt *pvt = (struct sip_pvt *) data;
  4048. return send_provisional_keepalive_full(pvt, 0);
  4049. }
  4050. static int send_provisional_keepalive_with_sdp(const void *data)
  4051. {
  4052. struct sip_pvt *pvt = (void *) data;
  4053. return send_provisional_keepalive_full(pvt, 1);
  4054. }
  4055. static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
  4056. {
  4057. 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"));
  4058. pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
  4059. with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
  4060. }
  4061. static void add_required_respheader(struct sip_request *req)
  4062. {
  4063. struct ast_str *str;
  4064. int i;
  4065. if (!req->reqsipoptions) {
  4066. return;
  4067. }
  4068. str = ast_str_create(32);
  4069. for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
  4070. if (!(req->reqsipoptions & sip_options[i].id)) {
  4071. continue;
  4072. }
  4073. if (ast_str_strlen(str) > 0) {
  4074. ast_str_append(&str, 0, ", ");
  4075. }
  4076. ast_str_append(&str, 0, "%s", sip_options[i].text);
  4077. }
  4078. if (ast_str_strlen(str) > 0) {
  4079. add_header(req, "Require", ast_str_buffer(str));
  4080. }
  4081. ast_free(str);
  4082. }
  4083. /*! \brief Transmit response on SIP request*/
  4084. static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
  4085. {
  4086. int res;
  4087. finalize_content(req);
  4088. add_blank(req);
  4089. if (sip_debug_test_pvt(p)) {
  4090. const struct ast_sockaddr *dst = sip_real_dst(p);
  4091. ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
  4092. reliable ? "Reliably " : "", sip_nat_mode(p),
  4093. ast_sockaddr_stringify(dst),
  4094. ast_str_buffer(req->data));
  4095. }
  4096. if (p->do_history) {
  4097. struct sip_request tmp = { .rlpart1 = 0, };
  4098. parse_copy(&tmp, req);
  4099. append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"),
  4100. (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlpart2) : sip_methods[tmp.method].text);
  4101. deinit_req(&tmp);
  4102. }
  4103. /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
  4104. if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
  4105. 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"));
  4106. }
  4107. res = (reliable) ?
  4108. __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
  4109. __sip_xmit(p, req->data);
  4110. deinit_req(req);
  4111. if (res > 0) {
  4112. return 0;
  4113. }
  4114. return res;
  4115. }
  4116. /*!
  4117. * \internal
  4118. * \brief Send SIP Request to the other part of the dialogue
  4119. * \return see \ref __sip_xmit
  4120. */
  4121. static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
  4122. {
  4123. int res;
  4124. /* If we have an outbound proxy, reset peer address
  4125. Only do this once.
  4126. */
  4127. if (p->outboundproxy) {
  4128. p->sa = p->outboundproxy->ip;
  4129. }
  4130. finalize_content(req);
  4131. add_blank(req);
  4132. if (sip_debug_test_pvt(p)) {
  4133. if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
  4134. ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
  4135. } else {
  4136. ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
  4137. }
  4138. }
  4139. if (p->do_history) {
  4140. struct sip_request tmp = { .rlpart1 = 0, };
  4141. parse_copy(&tmp, req);
  4142. append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
  4143. deinit_req(&tmp);
  4144. }
  4145. res = (reliable) ?
  4146. __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
  4147. __sip_xmit(p, req->data);
  4148. deinit_req(req);
  4149. return res;
  4150. }
  4151. static void enable_dsp_detect(struct sip_pvt *p)
  4152. {
  4153. int features = 0;
  4154. if (p->dsp) {
  4155. return;
  4156. }
  4157. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  4158. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  4159. if (p->rtp) {
  4160. ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
  4161. }
  4162. features |= DSP_FEATURE_DIGIT_DETECT;
  4163. }
  4164. if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
  4165. features |= DSP_FEATURE_FAX_DETECT;
  4166. }
  4167. if (!features) {
  4168. return;
  4169. }
  4170. if (!(p->dsp = ast_dsp_new())) {
  4171. return;
  4172. }
  4173. ast_dsp_set_features(p->dsp, features);
  4174. if (global_relaxdtmf) {
  4175. ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
  4176. }
  4177. }
  4178. static void disable_dsp_detect(struct sip_pvt *p)
  4179. {
  4180. if (p->dsp) {
  4181. ast_dsp_free(p->dsp);
  4182. p->dsp = NULL;
  4183. }
  4184. }
  4185. /*! \brief Set an option on a SIP dialog */
  4186. static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
  4187. {
  4188. int res = -1;
  4189. struct sip_pvt *p = ast_channel_tech_pvt(chan);
  4190. if (!p) {
  4191. ast_log(LOG_ERROR, "Attempt to Ref a null pointer. sip private structure is gone!\n");
  4192. return -1;
  4193. }
  4194. sip_pvt_lock(p);
  4195. switch (option) {
  4196. case AST_OPTION_FORMAT_READ:
  4197. if (p->rtp) {
  4198. res = ast_rtp_instance_set_read_format(p->rtp, *(struct ast_format **) data);
  4199. }
  4200. break;
  4201. case AST_OPTION_FORMAT_WRITE:
  4202. if (p->rtp) {
  4203. res = ast_rtp_instance_set_write_format(p->rtp, *(struct ast_format **) data);
  4204. }
  4205. break;
  4206. case AST_OPTION_DIGIT_DETECT:
  4207. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  4208. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  4209. char *cp = (char *) data;
  4210. ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", ast_channel_name(chan));
  4211. if (*cp) {
  4212. enable_dsp_detect(p);
  4213. } else {
  4214. disable_dsp_detect(p);
  4215. }
  4216. res = 0;
  4217. }
  4218. break;
  4219. case AST_OPTION_SECURE_SIGNALING:
  4220. p->req_secure_signaling = *(unsigned int *) data;
  4221. res = 0;
  4222. break;
  4223. case AST_OPTION_SECURE_MEDIA:
  4224. ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
  4225. res = 0;
  4226. break;
  4227. default:
  4228. break;
  4229. }
  4230. sip_pvt_unlock(p);
  4231. return res;
  4232. }
  4233. /*! \brief Query an option on a SIP dialog */
  4234. static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
  4235. {
  4236. int res = -1;
  4237. enum ast_t38_state state = T38_STATE_UNAVAILABLE;
  4238. struct sip_pvt *p = (struct sip_pvt *) ast_channel_tech_pvt(chan);
  4239. char *cp;
  4240. sip_pvt_lock(p);
  4241. switch (option) {
  4242. case AST_OPTION_T38_STATE:
  4243. /* Make sure we got an ast_t38_state enum passed in */
  4244. if (*datalen != sizeof(enum ast_t38_state)) {
  4245. ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
  4246. break;
  4247. }
  4248. /* 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 */
  4249. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
  4250. switch (p->t38.state) {
  4251. case T38_LOCAL_REINVITE:
  4252. case T38_PEER_REINVITE:
  4253. state = T38_STATE_NEGOTIATING;
  4254. break;
  4255. case T38_ENABLED:
  4256. state = T38_STATE_NEGOTIATED;
  4257. break;
  4258. case T38_REJECTED:
  4259. state = T38_STATE_REJECTED;
  4260. break;
  4261. default:
  4262. state = T38_STATE_UNKNOWN;
  4263. }
  4264. }
  4265. *((enum ast_t38_state *) data) = state;
  4266. res = 0;
  4267. break;
  4268. case AST_OPTION_DIGIT_DETECT:
  4269. cp = (char *) data;
  4270. *cp = p->dsp ? 1 : 0;
  4271. ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", ast_channel_name(chan));
  4272. break;
  4273. case AST_OPTION_SECURE_SIGNALING:
  4274. *((unsigned int *) data) = p->req_secure_signaling;
  4275. res = 0;
  4276. break;
  4277. case AST_OPTION_SECURE_MEDIA:
  4278. *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
  4279. res = 0;
  4280. break;
  4281. case AST_OPTION_DEVICE_NAME:
  4282. if (p && p->outgoing_call) {
  4283. cp = (char *) data;
  4284. ast_copy_string(cp, p->dialstring, *datalen);
  4285. res = 0;
  4286. }
  4287. /* We purposely break with a return of -1 in the
  4288. * implied else case here
  4289. */
  4290. break;
  4291. default:
  4292. break;
  4293. }
  4294. sip_pvt_unlock(p);
  4295. return res;
  4296. }
  4297. /*! \brief Locate closing quote in a string, skipping escaped quotes.
  4298. * optionally with a limit on the search.
  4299. * start must be past the first quote.
  4300. */
  4301. const char *find_closing_quote(const char *start, const char *lim)
  4302. {
  4303. char last_char = '\0';
  4304. const char *s;
  4305. for (s = start; *s && s != lim; last_char = *s++) {
  4306. if (*s == '"' && last_char != '\\')
  4307. break;
  4308. }
  4309. return s;
  4310. }
  4311. /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
  4312. static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
  4313. {
  4314. struct sip_pvt *p = ast_channel_tech_pvt(chan);
  4315. if (subclass != AST_HTML_URL)
  4316. return -1;
  4317. ast_string_field_build(p, url, "<%s>;mode=active", data);
  4318. if (sip_debug_test_pvt(p))
  4319. ast_debug(1, "Send URL %s, state = %u!\n", data, ast_channel_state(chan));
  4320. switch (ast_channel_state(chan)) {
  4321. case AST_STATE_RING:
  4322. transmit_response(p, "100 Trying", &p->initreq);
  4323. break;
  4324. case AST_STATE_RINGING:
  4325. transmit_response(p, "180 Ringing", &p->initreq);
  4326. break;
  4327. case AST_STATE_UP:
  4328. if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
  4329. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  4330. } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  4331. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  4332. }
  4333. break;
  4334. default:
  4335. ast_log(LOG_WARNING, "Don't know how to send URI when state is %u!\n", ast_channel_state(chan));
  4336. }
  4337. return 0;
  4338. }
  4339. /*! \brief Deliver SIP call ID for the call */
  4340. static const char *sip_get_callid(struct ast_channel *chan)
  4341. {
  4342. return ast_channel_tech_pvt(chan) ? ((struct sip_pvt *) ast_channel_tech_pvt(chan))->callid : "";
  4343. }
  4344. /*!
  4345. * \internal
  4346. * \brief Send SIP MESSAGE text within a call
  4347. * \note Called from PBX core sendtext() application
  4348. */
  4349. static int sip_sendtext(struct ast_channel *ast, const char *text)
  4350. {
  4351. struct sip_pvt *dialog = ast_channel_tech_pvt(ast);
  4352. int debug;
  4353. if (!dialog) {
  4354. return -1;
  4355. }
  4356. /* NOT ast_strlen_zero, because a zero-length message is specifically
  4357. * allowed by RFC 3428 (See section 10, Examples) */
  4358. if (!text) {
  4359. return 0;
  4360. }
  4361. if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
  4362. ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
  4363. return 0;
  4364. }
  4365. debug = sip_debug_test_pvt(dialog);
  4366. if (debug) {
  4367. ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
  4368. }
  4369. /* Setup to send text message */
  4370. sip_pvt_lock(dialog);
  4371. destroy_msg_headers(dialog);
  4372. ast_string_field_set(dialog, msg_body, text);
  4373. transmit_message(dialog, 0, 0);
  4374. sip_pvt_unlock(dialog);
  4375. return 0;
  4376. }
  4377. /*! \brief Update peer object in realtime storage
  4378. If the Asterisk system name is set in asterisk.conf, we will use
  4379. that name and store that in the "regserver" field in the sippeers
  4380. table to facilitate multi-server setups.
  4381. */
  4382. 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)
  4383. {
  4384. char port[10];
  4385. char ipaddr[INET6_ADDRSTRLEN];
  4386. char regseconds[20];
  4387. char *tablename = NULL;
  4388. char str_lastms[20];
  4389. const char *sysname = ast_config_AST_SYSTEM_NAME;
  4390. char *syslabel = NULL;
  4391. time_t nowtime = time(NULL) + expirey;
  4392. const char *fc = fullcontact ? "fullcontact" : NULL;
  4393. int realtimeregs = ast_check_realtime("sipregs");
  4394. tablename = realtimeregs ? "sipregs" : "sippeers";
  4395. snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
  4396. snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
  4397. ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
  4398. ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
  4399. if (ast_strlen_zero(sysname)) { /* No system name, disable this */
  4400. sysname = NULL;
  4401. } else if (sip_cfg.rtsave_sysname) {
  4402. syslabel = "regserver";
  4403. }
  4404. /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
  4405. * must also add it to contrib/scripts/asterisk.ldap-schema,
  4406. * contrib/scripts/asterisk.ldif,
  4407. * and to configs/res_ldap.conf.sample as described in
  4408. * bugs 15156 and 15895
  4409. */
  4410. /* This is ugly, we need something better ;-) */
  4411. if (sip_cfg.rtsave_path) {
  4412. if (fc) {
  4413. ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
  4414. "port", port, "regseconds", regseconds,
  4415. deprecated_username ? "username" : "defaultuser", defaultuser,
  4416. "useragent", useragent, "lastms", str_lastms,
  4417. "path", path, /* Path data can be NULL */
  4418. fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
  4419. } else {
  4420. ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
  4421. "port", port, "regseconds", regseconds,
  4422. "useragent", useragent, "lastms", str_lastms,
  4423. deprecated_username ? "username" : "defaultuser", defaultuser,
  4424. "path", path, /* Path data can be NULL */
  4425. syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
  4426. }
  4427. } else {
  4428. if (fc) {
  4429. ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
  4430. "port", port, "regseconds", regseconds,
  4431. deprecated_username ? "username" : "defaultuser", defaultuser,
  4432. "useragent", useragent, "lastms", str_lastms,
  4433. fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
  4434. } else {
  4435. ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
  4436. "port", port, "regseconds", regseconds,
  4437. "useragent", useragent, "lastms", str_lastms,
  4438. deprecated_username ? "username" : "defaultuser", defaultuser,
  4439. syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
  4440. }
  4441. }
  4442. }
  4443. /*! \brief Automatically add peer extension to dial plan */
  4444. static void register_peer_exten(struct sip_peer *peer, int onoff)
  4445. {
  4446. char multi[256];
  4447. char *stringp, *ext, *context;
  4448. struct pbx_find_info q = { .stacklen = 0 };
  4449. /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
  4450. * the name of the global regexten context, if not specified
  4451. * individually.
  4452. */
  4453. if (ast_strlen_zero(sip_cfg.regcontext))
  4454. return;
  4455. ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
  4456. stringp = multi;
  4457. while ((ext = strsep(&stringp, "&"))) {
  4458. if ((context = strchr(ext, '@'))) {
  4459. *context++ = '\0'; /* split ext@context */
  4460. if (!ast_context_find(context)) {
  4461. ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
  4462. continue;
  4463. }
  4464. } else {
  4465. context = sip_cfg.regcontext;
  4466. }
  4467. if (onoff) {
  4468. if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
  4469. ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
  4470. ast_strdup(peer->name), ast_free_ptr, "SIP");
  4471. }
  4472. } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
  4473. ast_context_remove_extension(context, ext, 1, NULL);
  4474. }
  4475. }
  4476. }
  4477. /*! Destroy mailbox subscriptions */
  4478. static void destroy_mailbox(struct sip_mailbox *mailbox)
  4479. {
  4480. if (mailbox->event_sub) {
  4481. mailbox->event_sub = stasis_unsubscribe(mailbox->event_sub);
  4482. }
  4483. ast_free(mailbox);
  4484. }
  4485. /*! Destroy all peer-related mailbox subscriptions */
  4486. static void clear_peer_mailboxes(struct sip_peer *peer)
  4487. {
  4488. struct sip_mailbox *mailbox;
  4489. while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
  4490. destroy_mailbox(mailbox);
  4491. }
  4492. static void sip_destroy_peer_fn(void *peer)
  4493. {
  4494. sip_destroy_peer(peer);
  4495. }
  4496. /*! \brief Destroy peer object from memory */
  4497. static void sip_destroy_peer(struct sip_peer *peer)
  4498. {
  4499. ast_debug(3, "Destroying SIP peer %s\n", peer->name);
  4500. /*
  4501. * Remove any mailbox event subscriptions for this peer before
  4502. * we destroy anything. An event subscription callback may be
  4503. * happening right now.
  4504. */
  4505. clear_peer_mailboxes(peer);
  4506. if (peer->outboundproxy) {
  4507. ao2_ref(peer->outboundproxy, -1);
  4508. peer->outboundproxy = NULL;
  4509. }
  4510. /* Delete it, it needs to disappear */
  4511. if (peer->call) {
  4512. dialog_unlink_all(peer->call);
  4513. peer->call = dialog_unref(peer->call, "peer->call is being unset");
  4514. }
  4515. if (peer->mwipvt) { /* We have an active subscription, delete it */
  4516. dialog_unlink_all(peer->mwipvt);
  4517. peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
  4518. }
  4519. if (peer->chanvars) {
  4520. ast_variables_destroy(peer->chanvars);
  4521. peer->chanvars = NULL;
  4522. }
  4523. sip_route_clear(&peer->path);
  4524. register_peer_exten(peer, FALSE);
  4525. ast_free_acl_list(peer->acl);
  4526. ast_free_acl_list(peer->directmediaacl);
  4527. if (peer->selfdestruct)
  4528. ast_atomic_fetchadd_int(&apeerobjs, -1);
  4529. else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
  4530. ast_atomic_fetchadd_int(&rpeerobjs, -1);
  4531. ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
  4532. } else
  4533. ast_atomic_fetchadd_int(&speerobjs, -1);
  4534. if (peer->auth) {
  4535. ao2_t_ref(peer->auth, -1, "Removing peer authentication");
  4536. peer->auth = NULL;
  4537. }
  4538. if (peer->socket.tcptls_session) {
  4539. ao2_ref(peer->socket.tcptls_session, -1);
  4540. peer->socket.tcptls_session = NULL;
  4541. } else if (peer->socket.ws_session) {
  4542. ast_websocket_unref(peer->socket.ws_session);
  4543. peer->socket.ws_session = NULL;
  4544. }
  4545. peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
  4546. peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
  4547. ast_cc_config_params_destroy(peer->cc_params);
  4548. ast_string_field_free_memory(peer);
  4549. ao2_cleanup(peer->caps);
  4550. ast_rtp_dtls_cfg_free(&peer->dtls_cfg);
  4551. ast_endpoint_shutdown(peer->endpoint);
  4552. peer->endpoint = NULL;
  4553. }
  4554. /*! \brief Update peer data in database (if used) */
  4555. static void update_peer(struct sip_peer *p, int expire)
  4556. {
  4557. int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
  4558. if (sip_cfg.peer_rtupdate && (p->is_realtime || rtcachefriends)) {
  4559. struct ast_str *r = sip_route_list(&p->path, 0, 0);
  4560. if (r) {
  4561. realtime_update_peer(p->name, &p->addr, p->username,
  4562. p->fullcontact, p->useragent, expire, p->deprecated_username,
  4563. p->lastms, ast_str_buffer(r));
  4564. ast_free(r);
  4565. }
  4566. }
  4567. }
  4568. static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
  4569. {
  4570. struct ast_variable *var = NULL;
  4571. struct ast_flags flags = {0};
  4572. char *cat = NULL;
  4573. const char *insecure;
  4574. while ((cat = ast_category_browse(cfg, cat))) {
  4575. insecure = ast_variable_retrieve(cfg, cat, "insecure");
  4576. set_insecure_flags(&flags, insecure, -1);
  4577. if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
  4578. var = ast_category_root(cfg, cat);
  4579. break;
  4580. }
  4581. }
  4582. return var;
  4583. }
  4584. static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
  4585. {
  4586. struct ast_config *peerlist;
  4587. struct ast_variable *var = NULL;
  4588. if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
  4589. if ((var = get_insecure_variable_from_config(peerlist))) {
  4590. /* Must clone, because var will get freed along with
  4591. * peerlist. */
  4592. var = ast_variables_dup(var);
  4593. }
  4594. ast_config_destroy(peerlist);
  4595. }
  4596. return var;
  4597. }
  4598. /* Yes.. the only column that makes sense to pass is "ipaddr", but for
  4599. * consistency's sake, we require the column name to be passed. As extra
  4600. * argument, we take a pointer to var. We already got the info, so we better
  4601. * return it and save the caller a query. If return value is nonzero, then *var
  4602. * is nonzero too (and the other way around). */
  4603. static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
  4604. {
  4605. struct ast_variable *varregs = NULL;
  4606. struct ast_config *regs, *peers;
  4607. char *regscat;
  4608. const char *regname;
  4609. if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
  4610. return NULL;
  4611. }
  4612. /* Load *all* peers that are probably insecure=port */
  4613. if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
  4614. ast_config_destroy(regs);
  4615. return NULL;
  4616. }
  4617. /* Loop over the sipregs that match IP address and attempt to find an
  4618. * insecure=port match to it in sippeers. */
  4619. regscat = NULL;
  4620. while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
  4621. char *peerscat;
  4622. const char *peername;
  4623. peerscat = NULL;
  4624. while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
  4625. if (!strcasecmp(regname, peername)) {
  4626. /* Ensure that it really is insecure=port and
  4627. * not something else. */
  4628. const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
  4629. struct ast_flags flags = {0};
  4630. set_insecure_flags(&flags, insecure, -1);
  4631. if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
  4632. /* ENOMEM checks till the bitter end. */
  4633. if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
  4634. if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
  4635. ast_variables_destroy(varregs);
  4636. varregs = NULL;
  4637. }
  4638. }
  4639. goto done;
  4640. }
  4641. }
  4642. }
  4643. }
  4644. done:
  4645. ast_config_destroy(regs);
  4646. ast_config_destroy(peers);
  4647. return varregs;
  4648. }
  4649. static const char *get_name_from_variable(const struct ast_variable *var)
  4650. {
  4651. /* Don't expect this to return non-NULL. Both NULL and empty
  4652. * values can cause the option to get removed from the variable
  4653. * list. This is called on ast_variables gotten from both
  4654. * ast_load_realtime and ast_load_realtime_multientry.
  4655. * - ast_load_realtime removes options with empty values
  4656. * - ast_load_realtime_multientry does not!
  4657. * For consistent behaviour, we check for the empty name and
  4658. * return NULL instead. */
  4659. const struct ast_variable *tmp;
  4660. for (tmp = var; tmp; tmp = tmp->next) {
  4661. if (!strcasecmp(tmp->name, "name")) {
  4662. if (!ast_strlen_zero(tmp->value)) {
  4663. return tmp->value;
  4664. }
  4665. break;
  4666. }
  4667. }
  4668. return NULL;
  4669. }
  4670. /* If varregs is NULL, we don't use sipregs.
  4671. * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
  4672. 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)
  4673. {
  4674. /* Peer by name and host=dynamic */
  4675. if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
  4676. ;
  4677. /* Peer by name and host=IP */
  4678. } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
  4679. ;
  4680. /* Peer by name and host=HOSTNAME */
  4681. } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
  4682. /*!\note
  4683. * If this one loaded something, then we need to ensure that the host
  4684. * field matched. The only reason why we can't have this as a criteria
  4685. * is because we only have the IP address and the host field might be
  4686. * set as a name (and the reverse PTR might not match).
  4687. */
  4688. if (addr) {
  4689. struct ast_variable *tmp;
  4690. for (tmp = *var; tmp; tmp = tmp->next) {
  4691. if (!strcasecmp(tmp->name, "host")) {
  4692. struct ast_sockaddr *addrs = NULL;
  4693. if (ast_sockaddr_resolve(&addrs,
  4694. tmp->value,
  4695. PARSE_PORT_FORBID,
  4696. get_address_family_filter(AST_TRANSPORT_UDP)) <= 0 ||
  4697. ast_sockaddr_cmp(&addrs[0], addr)) {
  4698. /* No match */
  4699. ast_variables_destroy(*var);
  4700. *var = NULL;
  4701. }
  4702. ast_free(addrs);
  4703. break;
  4704. }
  4705. }
  4706. }
  4707. }
  4708. /* Did we find anything? */
  4709. if (*var) {
  4710. if (varregs) {
  4711. *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
  4712. }
  4713. return 1;
  4714. }
  4715. return 0;
  4716. }
  4717. /* Another little helper function for backwards compatibility: this
  4718. * checks/fetches the sippeer that belongs to the sipreg. If none is
  4719. * found, we free the sipreg and return false. This way we can do the
  4720. * check inside the if-condition below. In the old code, not finding
  4721. * the sippeer also had it continue look for another match, so we do
  4722. * the same. */
  4723. static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
  4724. struct ast_variable *var = NULL;
  4725. const char *old_name = *name;
  4726. *name = get_name_from_variable(*varregs);
  4727. if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
  4728. if (!*name) {
  4729. ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
  4730. }
  4731. ast_variables_destroy(*varregs);
  4732. *varregs = NULL;
  4733. *name = old_name;
  4734. }
  4735. return var;
  4736. }
  4737. /* If varregs is NULL, we don't use sipregs. If we return true, then *name is
  4738. * set. Using empty if-bodies instead of goto's while avoiding unnecessary
  4739. * indents. */
  4740. 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)
  4741. {
  4742. char portstring[6]; /* up to 5 digits plus null terminator */
  4743. ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
  4744. /* We're not finding this peer by this name anymore. Reset it. */
  4745. *name = NULL;
  4746. /* First check for fixed IP hosts with matching callbackextensions, if specified */
  4747. if (!ast_strlen_zero(callbackexten) && (*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, "callbackextension", callbackexten, SENTINEL))) {
  4748. ;
  4749. /* Check for fixed IP hosts */
  4750. } else if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
  4751. ;
  4752. /* Check for registered hosts (in sipregs) */
  4753. } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
  4754. (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
  4755. ;
  4756. /* Check for registered hosts (in sippeers) */
  4757. } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
  4758. ;
  4759. /* We couldn't match on ipaddress and port, so we need to check if port is insecure */
  4760. } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
  4761. ;
  4762. /* Same as above, but try the IP address field (in sipregs)
  4763. * Observe that it fetches the name/var at the same time, without the
  4764. * realtime_peer_get_sippeer_helper. Also note that it is quite inefficient.
  4765. * Avoid sipregs if possible. */
  4766. } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
  4767. ;
  4768. /* Same as above, but try the IP address field (in sippeers) */
  4769. } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
  4770. ;
  4771. }
  4772. /* Nothing found? */
  4773. if (!*var) {
  4774. return 0;
  4775. }
  4776. /* Check peer name. It must not be empty. There may exist a
  4777. * different match that does have a name, but it's too late for
  4778. * that now. */
  4779. if (!*name && !(*name = get_name_from_variable(*var))) {
  4780. ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
  4781. ast_variables_destroy(*var);
  4782. *var = NULL;
  4783. if (varregs && *varregs) {
  4784. ast_variables_destroy(*varregs);
  4785. *varregs = NULL;
  4786. }
  4787. return 0;
  4788. }
  4789. /* Make sure varregs is populated if var is. The inverse,
  4790. * ensuring that var is set when varregs is, is taken
  4791. * care of by realtime_peer_get_sippeer_helper(). */
  4792. if (varregs && !*varregs) {
  4793. *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
  4794. }
  4795. return 1;
  4796. }
  4797. static int register_realtime_peers_with_callbackextens(void)
  4798. {
  4799. struct ast_config *cfg;
  4800. char *cat = NULL;
  4801. if (!(ast_check_realtime("sippeers"))) {
  4802. return 0;
  4803. }
  4804. /* This is hacky. We want name to be the cat, so it is the first property */
  4805. if (!(cfg = ast_load_realtime_multientry("sippeers", "name LIKE", "%", "callbackextension LIKE", "%", SENTINEL))) {
  4806. return -1;
  4807. }
  4808. while ((cat = ast_category_browse(cfg, cat))) {
  4809. struct sip_peer *peer;
  4810. struct ast_variable *var = ast_category_root(cfg, cat);
  4811. if (!(peer = build_peer(cat, var, NULL, TRUE, FALSE))) {
  4812. continue;
  4813. }
  4814. ast_log(LOG_NOTICE, "Created realtime peer '%s' for registration\n", peer->name);
  4815. peer->is_realtime = 1;
  4816. sip_unref_peer(peer, "register_realtime_peers: Done registering releasing");
  4817. }
  4818. ast_config_destroy(cfg);
  4819. return 0;
  4820. }
  4821. /*! \brief realtime_peer: Get peer from realtime storage
  4822. * Checks the "sippeers" realtime family from extconfig.conf
  4823. * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
  4824. * This returns a pointer to a peer and because we use build_peer, we can rest
  4825. * assured that the refcount is bumped.
  4826. *
  4827. * \note This is never called with both newpeername and addr at the same time.
  4828. * If you do, be prepared to get a peer with a different name than newpeername.
  4829. */
  4830. static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, char *callbackexten, int devstate_only, int which_objects)
  4831. {
  4832. struct sip_peer *peer = NULL;
  4833. struct ast_variable *var = NULL;
  4834. struct ast_variable *varregs = NULL;
  4835. char ipaddr[INET6_ADDRSTRLEN];
  4836. int realtimeregs = ast_check_realtime("sipregs");
  4837. if (addr) {
  4838. ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
  4839. } else {
  4840. ipaddr[0] = '\0';
  4841. }
  4842. if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
  4843. ;
  4844. } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, callbackexten, &var, realtimeregs ? &varregs : NULL)) {
  4845. ;
  4846. } else {
  4847. return NULL;
  4848. }
  4849. /* If we're looking for users, don't return peers (although this check
  4850. * should probably be done in realtime_peer_by_* instead...) */
  4851. if (which_objects == FINDUSERS) {
  4852. struct ast_variable *tmp;
  4853. for (tmp = var; tmp; tmp = tmp->next) {
  4854. if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
  4855. goto cleanup;
  4856. }
  4857. }
  4858. }
  4859. /* Peer found in realtime, now build it in memory */
  4860. peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
  4861. if (!peer) {
  4862. goto cleanup;
  4863. }
  4864. /* Previous versions of Asterisk did not require the type field to be
  4865. * set for real time peers. This statement preserves that behavior. */
  4866. if (peer->type == 0) {
  4867. if (which_objects == FINDUSERS) {
  4868. peer->type = SIP_TYPE_USER;
  4869. } else if (which_objects == FINDPEERS) {
  4870. peer->type = SIP_TYPE_PEER;
  4871. } else {
  4872. peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
  4873. }
  4874. }
  4875. ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
  4876. if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
  4877. /* Cache peer */
  4878. ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
  4879. if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
  4880. AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
  4881. sip_unref_peer(_data, "remove registration ref"),
  4882. sip_unref_peer(peer, "remove registration ref"),
  4883. sip_ref_peer(peer, "add registration ref"));
  4884. }
  4885. ao2_t_link(peers, peer, "link peer into peers table");
  4886. if (!ast_sockaddr_isnull(&peer->addr)) {
  4887. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  4888. }
  4889. }
  4890. peer->is_realtime = 1;
  4891. cleanup:
  4892. ast_variables_destroy(var);
  4893. ast_variables_destroy(varregs);
  4894. return peer;
  4895. }
  4896. /* Function to assist finding peers by name only */
  4897. static int find_by_name(void *obj, void *arg, void *data, int flags)
  4898. {
  4899. struct sip_peer *search = obj, *match = arg;
  4900. int *which_objects = data;
  4901. /* Usernames in SIP uri's are case sensitive. Domains are not */
  4902. if (strcmp(search->name, match->name)) {
  4903. return 0;
  4904. }
  4905. switch (*which_objects) {
  4906. case FINDUSERS:
  4907. if (!(search->type & SIP_TYPE_USER)) {
  4908. return 0;
  4909. }
  4910. break;
  4911. case FINDPEERS:
  4912. if (!(search->type & SIP_TYPE_PEER)) {
  4913. return 0;
  4914. }
  4915. break;
  4916. case FINDALLDEVICES:
  4917. break;
  4918. }
  4919. return CMP_MATCH | CMP_STOP;
  4920. }
  4921. 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)
  4922. {
  4923. struct sip_peer *p = NULL;
  4924. struct sip_peer tmp_peer;
  4925. if (peer) {
  4926. ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
  4927. p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
  4928. } else if (addr) { /* search by addr? */
  4929. ast_sockaddr_copy(&tmp_peer.addr, addr);
  4930. tmp_peer.flags[0].flags = 0;
  4931. tmp_peer.transports = transport;
  4932. p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table");
  4933. if (!p) {
  4934. ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
  4935. 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");
  4936. if (p) {
  4937. return p;
  4938. }
  4939. }
  4940. }
  4941. if (!p && (realtime || devstate_only)) {
  4942. /* realtime_peer will return a peer with matching callbackexten if possible, otherwise one matching
  4943. * without the callbackexten */
  4944. p = realtime_peer(peer, addr, callbackexten, devstate_only, which_objects);
  4945. if (p) {
  4946. switch (which_objects) {
  4947. case FINDUSERS:
  4948. if (!(p->type & SIP_TYPE_USER)) {
  4949. sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
  4950. return NULL;
  4951. }
  4952. break;
  4953. case FINDPEERS:
  4954. if (!(p->type & SIP_TYPE_PEER)) {
  4955. sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
  4956. return NULL;
  4957. }
  4958. break;
  4959. case FINDALLDEVICES:
  4960. break;
  4961. }
  4962. }
  4963. }
  4964. return p;
  4965. }
  4966. /*!
  4967. * \brief Locate device by name or ip address
  4968. * \param peer, addr, realtime, devstate_only, transport
  4969. * \param which_objects Define which objects should be matched when doing a lookup
  4970. * by name. Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
  4971. * Note that this option is not used at all when doing a lookup by IP.
  4972. *
  4973. * This is used on find matching device on name or ip/port.
  4974. * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
  4975. *
  4976. * \note Avoid using this function in new functions if there is a way to avoid it,
  4977. * since it might cause a database lookup.
  4978. */
  4979. struct sip_peer *sip_find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
  4980. {
  4981. return sip_find_peer_full(peer, addr, NULL, realtime, which_objects, devstate_only, transport);
  4982. }
  4983. static struct sip_peer *sip_find_peer_by_ip_and_exten(struct ast_sockaddr *addr, char *callbackexten, int transport)
  4984. {
  4985. return sip_find_peer_full(NULL, addr, callbackexten, TRUE, FINDPEERS, FALSE, transport);
  4986. }
  4987. /*! \brief Set nat mode on the various data sockets */
  4988. static void do_setnat(struct sip_pvt *p)
  4989. {
  4990. const char *mode;
  4991. int natflags;
  4992. natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
  4993. mode = natflags ? "On" : "Off";
  4994. if (p->rtp) {
  4995. ast_debug(1, "Setting NAT on RTP to %s\n", mode);
  4996. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
  4997. }
  4998. if (p->vrtp) {
  4999. ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
  5000. ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
  5001. }
  5002. if (p->udptl) {
  5003. ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
  5004. ast_udptl_setnat(p->udptl, natflags);
  5005. }
  5006. if (p->trtp) {
  5007. ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
  5008. ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
  5009. }
  5010. }
  5011. /*! \brief Change the T38 state on a SIP dialog */
  5012. static void change_t38_state(struct sip_pvt *p, int state)
  5013. {
  5014. int old = p->t38.state;
  5015. struct ast_channel *chan = p->owner;
  5016. struct ast_control_t38_parameters parameters = { .request_response = 0 };
  5017. /* Don't bother changing if we are already in the state wanted */
  5018. if (old == state)
  5019. return;
  5020. p->t38.state = state;
  5021. ast_debug(2, "T38 state changed to %u on channel %s\n", p->t38.state, chan ? ast_channel_name(chan) : "<none>");
  5022. /* If no channel was provided we can't send off a control frame */
  5023. if (!chan)
  5024. return;
  5025. /* Given the state requested and old state determine what control frame we want to queue up */
  5026. switch (state) {
  5027. case T38_PEER_REINVITE:
  5028. parameters = p->t38.their_parms;
  5029. parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
  5030. parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
  5031. ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
  5032. break;
  5033. case T38_ENABLED:
  5034. parameters = p->t38.their_parms;
  5035. parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
  5036. parameters.request_response = AST_T38_NEGOTIATED;
  5037. ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
  5038. break;
  5039. case T38_REJECTED:
  5040. case T38_DISABLED:
  5041. if (old == T38_ENABLED) {
  5042. parameters.request_response = AST_T38_TERMINATED;
  5043. } else if (old == T38_LOCAL_REINVITE) {
  5044. parameters.request_response = AST_T38_REFUSED;
  5045. }
  5046. break;
  5047. case T38_LOCAL_REINVITE:
  5048. /* wait until we get a peer response before responding to local reinvite */
  5049. break;
  5050. }
  5051. /* Woot we got a message, create a control frame and send it on! */
  5052. if (parameters.request_response)
  5053. ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
  5054. }
  5055. /*! \brief Set the global T38 capabilities on a SIP dialog structure */
  5056. static void set_t38_capabilities(struct sip_pvt *p)
  5057. {
  5058. if (p->udptl) {
  5059. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
  5060. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
  5061. } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
  5062. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
  5063. } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
  5064. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
  5065. }
  5066. }
  5067. }
  5068. static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
  5069. {
  5070. if (to_sock->tcptls_session) {
  5071. ao2_ref(to_sock->tcptls_session, -1);
  5072. to_sock->tcptls_session = NULL;
  5073. } else if (to_sock->ws_session) {
  5074. ast_websocket_unref(to_sock->ws_session);
  5075. to_sock->ws_session = NULL;
  5076. }
  5077. if (from_sock->tcptls_session) {
  5078. ao2_ref(from_sock->tcptls_session, +1);
  5079. } else if (from_sock->ws_session) {
  5080. ast_websocket_ref(from_sock->ws_session);
  5081. }
  5082. *to_sock = *from_sock;
  5083. }
  5084. /*! \brief Initialize DTLS-SRTP support on an RTP instance */
  5085. static int dialog_initialize_dtls_srtp(const struct sip_pvt *dialog, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp)
  5086. {
  5087. struct ast_rtp_engine_dtls *dtls;
  5088. if (!dialog->dtls_cfg.enabled) {
  5089. return 0;
  5090. }
  5091. if (!ast_rtp_engine_srtp_is_registered()) {
  5092. ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
  5093. return -1;
  5094. }
  5095. if (!(dtls = ast_rtp_instance_get_dtls(rtp))) {
  5096. ast_log(LOG_ERROR, "No DTLS-SRTP support present on engine for RTP instance '%p', was it compiled with support for it?\n",
  5097. rtp);
  5098. return -1;
  5099. }
  5100. if (dtls->set_configuration(rtp, &dialog->dtls_cfg)) {
  5101. ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
  5102. rtp);
  5103. return -1;
  5104. }
  5105. if (!(*srtp = ast_sdp_srtp_alloc())) {
  5106. ast_log(LOG_ERROR, "Failed to create required SRTP structure on RTP instance '%p'\n",
  5107. rtp);
  5108. return -1;
  5109. }
  5110. return 0;
  5111. }
  5112. /*! \brief Initialize RTP portion of a dialog
  5113. * \return -1 on failure, 0 on success
  5114. */
  5115. static int dialog_initialize_rtp(struct sip_pvt *dialog)
  5116. {
  5117. struct ast_sockaddr bindaddr_tmp;
  5118. struct ast_rtp_engine_ice *ice;
  5119. if (!sip_methods[dialog->method].need_rtp) {
  5120. return 0;
  5121. }
  5122. ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
  5123. if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
  5124. return -1;
  5125. }
  5126. if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->rtp))) {
  5127. ice->stop(dialog->rtp);
  5128. }
  5129. if (dialog_initialize_dtls_srtp(dialog, dialog->rtp, &dialog->srtp)) {
  5130. return -1;
  5131. }
  5132. if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
  5133. (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (ast_format_cap_has_type(dialog->caps, AST_MEDIA_TYPE_VIDEO)))) {
  5134. if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
  5135. return -1;
  5136. }
  5137. if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->vrtp))) {
  5138. ice->stop(dialog->vrtp);
  5139. }
  5140. if (dialog_initialize_dtls_srtp(dialog, dialog->vrtp, &dialog->vsrtp)) {
  5141. return -1;
  5142. }
  5143. ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
  5144. ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
  5145. ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
  5146. ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
  5147. ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
  5148. }
  5149. if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
  5150. if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
  5151. return -1;
  5152. }
  5153. if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->trtp))) {
  5154. ice->stop(dialog->trtp);
  5155. }
  5156. if (dialog_initialize_dtls_srtp(dialog, dialog->trtp, &dialog->tsrtp)) {
  5157. return -1;
  5158. }
  5159. /* Do not timeout text as its not constant*/
  5160. ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
  5161. ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
  5162. }
  5163. ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
  5164. ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
  5165. ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
  5166. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
  5167. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  5168. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  5169. ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
  5170. do_setnat(dialog);
  5171. return 0;
  5172. }
  5173. static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp);
  5174. /*! \brief Create address structure from peer reference.
  5175. * This function copies data from peer to the dialog, so we don't have to look up the peer
  5176. * again from memory or database during the life time of the dialog.
  5177. *
  5178. * \return -1 on error, 0 on success.
  5179. *
  5180. */
  5181. static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
  5182. {
  5183. struct sip_auth_container *credentials;
  5184. /* this checks that the dialog is contacting the peer on a valid
  5185. * transport type based on the peers transport configuration,
  5186. * otherwise, this function bails out */
  5187. if (dialog->socket.type && check_request_transport(peer, dialog))
  5188. return -1;
  5189. copy_socket_data(&dialog->socket, &peer->socket);
  5190. if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
  5191. (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
  5192. dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
  5193. dialog->recv = dialog->sa;
  5194. } else
  5195. return -1;
  5196. /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
  5197. ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
  5198. ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  5199. ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  5200. /* Take the peer's caps */
  5201. if (peer->caps) {
  5202. ast_format_cap_remove_by_type(dialog->caps, AST_MEDIA_TYPE_UNKNOWN);
  5203. ast_format_cap_append_from_cap(dialog->caps, peer->caps, AST_MEDIA_TYPE_UNKNOWN);
  5204. }
  5205. dialog->amaflags = peer->amaflags;
  5206. ast_string_field_set(dialog, engine, peer->engine);
  5207. ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &dialog->dtls_cfg);
  5208. dialog->rtptimeout = peer->rtptimeout;
  5209. dialog->rtpholdtimeout = peer->rtpholdtimeout;
  5210. dialog->rtpkeepalive = peer->rtpkeepalive;
  5211. sip_route_copy(&dialog->route, &peer->path);
  5212. if (!sip_route_empty(&dialog->route)) {
  5213. /* Parse SIP URI of first route-set hop and use it as target address */
  5214. __set_address_from_contact(sip_route_first_uri(&dialog->route), &dialog->sa, dialog->socket.type == AST_TRANSPORT_TLS ? 1 : 0);
  5215. }
  5216. if (dialog_initialize_rtp(dialog)) {
  5217. return -1;
  5218. }
  5219. if (dialog->rtp) { /* Audio */
  5220. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  5221. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  5222. /* Set Frame packetization */
  5223. dialog->autoframing = peer->autoframing;
  5224. ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(dialog->rtp), ast_format_cap_get_framing(dialog->caps));
  5225. }
  5226. /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
  5227. ast_string_field_set(dialog, peername, peer->name);
  5228. ast_string_field_set(dialog, authname, peer->username);
  5229. ast_string_field_set(dialog, username, peer->username);
  5230. ast_string_field_set(dialog, peersecret, peer->secret);
  5231. ast_string_field_set(dialog, peermd5secret, peer->md5secret);
  5232. ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
  5233. ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
  5234. ast_string_field_set(dialog, tohost, peer->tohost);
  5235. ast_string_field_set(dialog, fullcontact, peer->fullcontact);
  5236. ast_string_field_set(dialog, accountcode, peer->accountcode);
  5237. ast_string_field_set(dialog, context, peer->context);
  5238. ast_string_field_set(dialog, cid_num, peer->cid_num);
  5239. ast_string_field_set(dialog, cid_name, peer->cid_name);
  5240. ast_string_field_set(dialog, cid_tag, peer->cid_tag);
  5241. ast_string_field_set(dialog, mwi_from, peer->mwi_from);
  5242. if (!ast_strlen_zero(peer->parkinglot)) {
  5243. ast_string_field_set(dialog, parkinglot, peer->parkinglot);
  5244. }
  5245. ast_string_field_set(dialog, engine, peer->engine);
  5246. ref_proxy(dialog, obproxy_get(dialog, peer));
  5247. dialog->callgroup = peer->callgroup;
  5248. dialog->pickupgroup = peer->pickupgroup;
  5249. ast_unref_namedgroups(dialog->named_callgroups);
  5250. dialog->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);
  5251. ast_unref_namedgroups(dialog->named_pickupgroups);
  5252. dialog->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
  5253. ast_copy_string(dialog->zone, peer->zone, sizeof(dialog->zone));
  5254. dialog->allowtransfer = peer->allowtransfer;
  5255. dialog->jointnoncodeccapability = dialog->noncodeccapability;
  5256. /* Update dialog authorization credentials */
  5257. ao2_lock(peer);
  5258. credentials = peer->auth;
  5259. if (credentials) {
  5260. ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
  5261. }
  5262. ao2_unlock(peer);
  5263. ao2_lock(dialog);
  5264. if (dialog->peerauth) {
  5265. ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
  5266. }
  5267. dialog->peerauth = credentials;
  5268. ao2_unlock(dialog);
  5269. dialog->maxcallbitrate = peer->maxcallbitrate;
  5270. dialog->disallowed_methods = peer->disallowed_methods;
  5271. ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
  5272. if (ast_strlen_zero(dialog->tohost))
  5273. ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
  5274. if (!ast_strlen_zero(peer->fromdomain)) {
  5275. ast_string_field_set(dialog, fromdomain, peer->fromdomain);
  5276. if (!dialog->initreq.headers) {
  5277. char *new_callid;
  5278. char *tmpcall = ast_strdupa(dialog->callid);
  5279. /* this sure looks to me like we are going to change the callid on this dialog!! */
  5280. new_callid = strchr(tmpcall, '@');
  5281. if (new_callid) {
  5282. int callid_size;
  5283. *new_callid = '\0';
  5284. /* Change the dialog callid. */
  5285. callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
  5286. new_callid = ast_alloca(callid_size);
  5287. snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
  5288. change_callid_pvt(dialog, new_callid);
  5289. }
  5290. }
  5291. }
  5292. if (!ast_strlen_zero(peer->fromuser)) {
  5293. ast_string_field_set(dialog, fromuser, peer->fromuser);
  5294. }
  5295. if (!ast_strlen_zero(peer->language)) {
  5296. ast_string_field_set(dialog, language, peer->language);
  5297. }
  5298. /* Set timer T1 to RTT for this peer (if known by qualify=) */
  5299. /* Minimum is settable or default to 100 ms */
  5300. /* If there is a maxms and lastms from a qualify use that over a manual T1
  5301. value. Otherwise, use the peer's T1 value. */
  5302. if (peer->maxms && peer->lastms) {
  5303. dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
  5304. } else {
  5305. dialog->timer_t1 = peer->timer_t1;
  5306. }
  5307. /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
  5308. the known timer */
  5309. if (peer->timer_b) {
  5310. dialog->timer_b = peer->timer_b;
  5311. } else {
  5312. dialog->timer_b = 64 * dialog->timer_t1;
  5313. }
  5314. if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
  5315. (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  5316. dialog->noncodeccapability |= AST_RTP_DTMF;
  5317. } else {
  5318. dialog->noncodeccapability &= ~AST_RTP_DTMF;
  5319. }
  5320. dialog->directmediaacl = ast_duplicate_acl_list(peer->directmediaacl);
  5321. if (peer->call_limit) {
  5322. ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
  5323. }
  5324. if (!dialog->portinuri) {
  5325. dialog->portinuri = peer->portinuri;
  5326. }
  5327. dialog->chanvars = copy_vars(peer->chanvars);
  5328. if (peer->fromdomainport) {
  5329. dialog->fromdomainport = peer->fromdomainport;
  5330. }
  5331. dialog->callingpres = peer->callingpres;
  5332. return 0;
  5333. }
  5334. /*! \brief The default sip port for the given transport */
  5335. static inline int default_sip_port(enum ast_transport type)
  5336. {
  5337. return type == AST_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
  5338. }
  5339. /*! \brief create address structure from device name
  5340. * Or, if peer not found, find it in the global DNS
  5341. * returns TRUE (-1) on failure, FALSE on success */
  5342. static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
  5343. {
  5344. struct sip_peer *peer;
  5345. char *peername, *peername2, *hostn;
  5346. char host[MAXHOSTNAMELEN];
  5347. char service[MAXHOSTNAMELEN];
  5348. int srv_ret = 0;
  5349. int tportno;
  5350. AST_DECLARE_APP_ARGS(hostport,
  5351. AST_APP_ARG(host);
  5352. AST_APP_ARG(port);
  5353. );
  5354. peername = ast_strdupa(opeer);
  5355. peername2 = ast_strdupa(opeer);
  5356. AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
  5357. if (hostport.port)
  5358. dialog->portinuri = 1;
  5359. dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
  5360. dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
  5361. peer = sip_find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
  5362. if (peer) {
  5363. int res;
  5364. if (newdialog) {
  5365. set_socket_transport(&dialog->socket, 0);
  5366. }
  5367. res = create_addr_from_peer(dialog, peer);
  5368. dialog->relatedpeer = sip_ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
  5369. sip_unref_peer(peer, "create_addr: unref peer from sip_find_peer hashtab lookup");
  5370. return res;
  5371. } else if (ast_check_digits(peername)) {
  5372. /* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
  5373. * it makes dialing SIP/${EXTEN} for a peer that isn't defined resolve to an IP that is
  5374. * almost certainly not intended. It is much better to just reject purely numeric hostnames */
  5375. ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
  5376. return -1;
  5377. } else {
  5378. dialog->rtptimeout = global_rtptimeout;
  5379. dialog->rtpholdtimeout = global_rtpholdtimeout;
  5380. dialog->rtpkeepalive = global_rtpkeepalive;
  5381. if (dialog_initialize_rtp(dialog)) {
  5382. return -1;
  5383. }
  5384. }
  5385. ast_string_field_set(dialog, tohost, hostport.host);
  5386. dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
  5387. /* Get the outbound proxy information */
  5388. ref_proxy(dialog, obproxy_get(dialog, NULL));
  5389. if (addr) {
  5390. /* This address should be updated using dnsmgr */
  5391. ast_sockaddr_copy(&dialog->sa, addr);
  5392. } else {
  5393. /* Let's see if we can find the host in DNS. First try DNS SRV records,
  5394. then hostname lookup */
  5395. /*! \todo Fix this function. When we ask for SRV, we should check all transports
  5396. In the future, we should first check NAPTR to find out transport preference
  5397. */
  5398. hostn = peername;
  5399. /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
  5400. * an A record lookup should be used instead of SRV.
  5401. */
  5402. if (!hostport.port && sip_cfg.srvlookup) {
  5403. snprintf(service, sizeof(service), "_%s._%s.%s",
  5404. get_srv_service(dialog->socket.type),
  5405. get_srv_protocol(dialog->socket.type), peername);
  5406. if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
  5407. service)) > 0) {
  5408. hostn = host;
  5409. }
  5410. }
  5411. if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : AST_TRANSPORT_UDP)) {
  5412. ast_log(LOG_WARNING, "No such host: %s\n", peername);
  5413. return -1;
  5414. }
  5415. if (srv_ret > 0) {
  5416. ast_sockaddr_set_port(&dialog->sa, tportno);
  5417. }
  5418. }
  5419. if (!dialog->socket.type)
  5420. set_socket_transport(&dialog->socket, AST_TRANSPORT_UDP);
  5421. if (!dialog->socket.port) {
  5422. dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
  5423. }
  5424. if (!ast_sockaddr_port(&dialog->sa)) {
  5425. ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
  5426. }
  5427. ast_sockaddr_copy(&dialog->recv, &dialog->sa);
  5428. return 0;
  5429. }
  5430. /*! \brief Scheduled congestion on a call.
  5431. * Only called by the scheduler, must return the reference when done.
  5432. */
  5433. static int auto_congest(const void *arg)
  5434. {
  5435. struct sip_pvt *p = (struct sip_pvt *)arg;
  5436. sip_pvt_lock(p);
  5437. p->initid = -1; /* event gone, will not be rescheduled */
  5438. if (p->owner) {
  5439. /* XXX fails on possible deadlock */
  5440. if (!ast_channel_trylock(p->owner)) {
  5441. append_history(p, "Cong", "Auto-congesting (timer)");
  5442. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  5443. ast_channel_unlock(p->owner);
  5444. }
  5445. /* Give the channel a chance to act before we proceed with destruction */
  5446. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  5447. }
  5448. sip_pvt_unlock(p);
  5449. dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
  5450. return 0;
  5451. }
  5452. /*! \brief Initiate SIP call from PBX
  5453. * used from the dial() application */
  5454. static int sip_call(struct ast_channel *ast, const char *dest, int timeout)
  5455. {
  5456. int res;
  5457. struct sip_pvt *p = ast_channel_tech_pvt(ast); /* chan is locked, so the reference cannot go away */
  5458. struct varshead *headp;
  5459. struct ast_var_t *current;
  5460. const char *referer = NULL; /* SIP referrer */
  5461. int cc_core_id;
  5462. char uri[SIPBUFSIZE] = "";
  5463. if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
  5464. ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
  5465. return -1;
  5466. }
  5467. if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
  5468. char device_name[AST_CHANNEL_NAME];
  5469. struct ast_cc_monitor *recall_monitor;
  5470. struct sip_monitor_instance *monitor_instance;
  5471. ast_channel_get_device_name(ast, device_name, sizeof(device_name));
  5472. if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
  5473. monitor_instance = recall_monitor->private_data;
  5474. ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
  5475. ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
  5476. }
  5477. }
  5478. /* Check whether there is vxml_url, distinctive ring variables */
  5479. headp = ast_channel_varshead(ast);
  5480. AST_LIST_TRAVERSE(headp, current, entries) {
  5481. /* Check whether there is a VXML_URL variable */
  5482. if (!p->options->vxml_url && !strcmp(ast_var_name(current), "VXML_URL")) {
  5483. p->options->vxml_url = ast_var_value(current);
  5484. } else if (!p->options->uri_options && !strcmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
  5485. p->options->uri_options = ast_var_value(current);
  5486. } else if (!p->options->addsipheaders && !strncmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
  5487. /* Check whether there is a variable with a name starting with SIPADDHEADER */
  5488. p->options->addsipheaders = 1;
  5489. } else if (!strcmp(ast_var_name(current), "SIPFROMDOMAIN")) {
  5490. ast_string_field_set(p, fromdomain, ast_var_value(current));
  5491. } else if (!strcmp(ast_var_name(current), "SIPTRANSFER")) {
  5492. /* This is a transferred call */
  5493. p->options->transfer = 1;
  5494. } else if (!strcmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
  5495. /* This is the referrer */
  5496. referer = ast_var_value(current);
  5497. } else if (!strcmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
  5498. /* We're replacing a call. */
  5499. p->options->replaces = ast_var_value(current);
  5500. } else if (!strcmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
  5501. if (sscanf(ast_var_value(current), "%30d", &(p->maxforwards)) != 1) {
  5502. ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
  5503. }
  5504. }
  5505. }
  5506. /* Check to see if we should try to force encryption */
  5507. if (p->req_secure_signaling && p->socket.type != AST_TRANSPORT_TLS) {
  5508. ast_log(LOG_WARNING, "Encrypted signaling is required\n");
  5509. ast_channel_hangupcause_set(ast, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  5510. return -1;
  5511. }
  5512. if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
  5513. if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
  5514. ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
  5515. ast_clear_flag(&p->flags[0], SIP_REINVITE);
  5516. }
  5517. if (p->rtp && !p->srtp && !(p->srtp = ast_sdp_srtp_alloc())) {
  5518. ast_log(LOG_WARNING, "SRTP audio setup failed\n");
  5519. return -1;
  5520. }
  5521. if (p->vrtp && !p->vsrtp && !(p->vsrtp = ast_sdp_srtp_alloc())) {
  5522. ast_log(LOG_WARNING, "SRTP video setup failed\n");
  5523. return -1;
  5524. }
  5525. if (p->trtp && !p->tsrtp && !(p->tsrtp = ast_sdp_srtp_alloc())) {
  5526. ast_log(LOG_WARNING, "SRTP text setup failed\n");
  5527. return -1;
  5528. }
  5529. }
  5530. res = 0;
  5531. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  5532. /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
  5533. * so ensure it is disabled.
  5534. */
  5535. ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
  5536. if (p->options->transfer) {
  5537. char buf[SIPBUFSIZE / 2];
  5538. if (referer) {
  5539. if (sipdebug)
  5540. ast_debug(3, "Call for %s transferred by %s\n", p->username, referer);
  5541. snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
  5542. } else
  5543. snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
  5544. ast_string_field_set(p, cid_name, buf);
  5545. }
  5546. ast_debug(1, "Outgoing Call for %s\n", p->username);
  5547. res = update_call_counter(p, INC_CALL_RINGING);
  5548. if (res == -1) {
  5549. ast_channel_hangupcause_set(ast, AST_CAUSE_USER_BUSY);
  5550. return res;
  5551. }
  5552. p->callingpres = ast_party_id_presentation(&ast_channel_caller(ast)->id);
  5553. ast_rtp_instance_available_formats(p->rtp, p->caps, p->prefcaps, p->jointcaps);
  5554. p->jointnoncodeccapability = p->noncodeccapability;
  5555. /* If there are no audio formats left to offer, punt */
  5556. if (!(ast_format_cap_has_type(p->jointcaps, AST_MEDIA_TYPE_AUDIO))) {
  5557. ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
  5558. res = -1;
  5559. } else {
  5560. int xmitres;
  5561. struct ast_party_connected_line connected;
  5562. struct ast_set_party_connected_line update_connected;
  5563. sip_pvt_lock(p);
  5564. /* Supply initial connected line information if available. */
  5565. memset(&update_connected, 0, sizeof(update_connected));
  5566. ast_party_connected_line_init(&connected);
  5567. if (!ast_strlen_zero(p->cid_num)
  5568. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  5569. update_connected.id.number = 1;
  5570. connected.id.number.valid = 1;
  5571. connected.id.number.str = (char *) p->cid_num;
  5572. connected.id.number.presentation = p->callingpres;
  5573. }
  5574. if (!ast_strlen_zero(p->cid_name)
  5575. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  5576. update_connected.id.name = 1;
  5577. connected.id.name.valid = 1;
  5578. connected.id.name.str = (char *) p->cid_name;
  5579. connected.id.name.presentation = p->callingpres;
  5580. }
  5581. if (update_connected.id.number || update_connected.id.name) {
  5582. /* Invalidate any earlier private connected id representation */
  5583. ast_set_party_id_all(&update_connected.priv);
  5584. connected.id.tag = (char *) p->cid_tag;
  5585. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  5586. ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
  5587. }
  5588. xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
  5589. if (xmitres == XMIT_ERROR) {
  5590. sip_pvt_unlock(p);
  5591. return -1;
  5592. }
  5593. p->invitestate = INV_CALLING;
  5594. /* Initialize auto-congest time */
  5595. AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
  5596. dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
  5597. dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
  5598. dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
  5599. sip_pvt_unlock(p);
  5600. }
  5601. return res;
  5602. }
  5603. /*! \brief Destroy registry object
  5604. Objects created with the register= statement in static configuration */
  5605. static void sip_registry_destroy(void *obj)
  5606. {
  5607. struct sip_registry *reg = obj;
  5608. /* Really delete */
  5609. ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
  5610. if (reg->call) {
  5611. /* Clear registry before destroying to ensure
  5612. we don't get reentered trying to grab the registry lock */
  5613. ao2_t_replace(reg->call->registry, NULL, "destroy reg->call->registry");
  5614. ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
  5615. dialog_unlink_all(reg->call);
  5616. reg->call = dialog_unref(reg->call, "unref reg->call");
  5617. /* reg->call = sip_destroy(reg->call); */
  5618. }
  5619. AST_SCHED_DEL(sched, reg->expire);
  5620. AST_SCHED_DEL(sched, reg->timeout);
  5621. ast_string_field_free_memory(reg);
  5622. }
  5623. /*! \brief Destroy MWI subscription object */
  5624. static void sip_subscribe_mwi_destroy(void *data)
  5625. {
  5626. struct sip_subscription_mwi *mwi = data;
  5627. if (mwi->call) {
  5628. mwi->call->mwi = NULL;
  5629. mwi->call = dialog_unref(mwi->call, "sip_subscription_mwi destruction");
  5630. }
  5631. AST_SCHED_DEL(sched, mwi->resub);
  5632. ast_string_field_free_memory(mwi);
  5633. }
  5634. /*! \brief Destroy SDP media offer list */
  5635. static void offered_media_list_destroy(struct sip_pvt *p)
  5636. {
  5637. struct offered_media *offer;
  5638. while ((offer = AST_LIST_REMOVE_HEAD(&p->offered_media, next))) {
  5639. ast_free(offer->decline_m_line);
  5640. ast_free(offer);
  5641. }
  5642. }
  5643. /*! \brief Execute destruction of SIP dialog structure, release memory */
  5644. void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
  5645. {
  5646. struct sip_request *req;
  5647. /* Destroy Session-Timers if allocated */
  5648. if (p->stimer) {
  5649. p->stimer->quit_flag = 1;
  5650. stop_session_timer(p);
  5651. ast_free(p->stimer);
  5652. p->stimer = NULL;
  5653. }
  5654. if (sip_debug_test_pvt(p))
  5655. ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
  5656. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  5657. update_call_counter(p, DEC_CALL_LIMIT);
  5658. ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
  5659. }
  5660. /* Unlink us from the owner if we have one */
  5661. if (p->owner) {
  5662. if (lockowner)
  5663. ast_channel_lock(p->owner);
  5664. ast_debug(1, "Detaching from %s\n", ast_channel_name(p->owner));
  5665. ast_channel_tech_pvt_set(p->owner, NULL);
  5666. /* Make sure that the channel knows its backend is going away */
  5667. ast_channel_softhangup_internal_flag_add(p->owner, AST_SOFTHANGUP_DEV);
  5668. if (lockowner)
  5669. ast_channel_unlock(p->owner);
  5670. /* Give the channel a chance to react before deallocation */
  5671. usleep(1);
  5672. }
  5673. /* Remove link from peer to subscription of MWI */
  5674. if (p->relatedpeer && p->relatedpeer->mwipvt == p)
  5675. p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
  5676. if (p->relatedpeer && p->relatedpeer->call == p)
  5677. p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
  5678. if (p->relatedpeer)
  5679. p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
  5680. if (p->registry) {
  5681. if (p->registry->call == p)
  5682. p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
  5683. ao2_t_replace(p->registry, NULL, "delete p->registry");
  5684. }
  5685. if (p->mwi) {
  5686. p->mwi->call = NULL;
  5687. p->mwi = NULL;
  5688. }
  5689. if (dumphistory)
  5690. sip_dump_history(p);
  5691. if (p->options) {
  5692. if (p->options->outboundproxy) {
  5693. ao2_ref(p->options->outboundproxy, -1);
  5694. }
  5695. ast_free(p->options);
  5696. p->options = NULL;
  5697. }
  5698. if (p->outboundproxy) {
  5699. ref_proxy(p, NULL);
  5700. }
  5701. if (p->notify) {
  5702. ast_variables_destroy(p->notify->headers);
  5703. ast_free(p->notify->content);
  5704. ast_free(p->notify);
  5705. p->notify = NULL;
  5706. }
  5707. if (p->rtp) {
  5708. ast_rtp_instance_destroy(p->rtp);
  5709. p->rtp = NULL;
  5710. }
  5711. if (p->vrtp) {
  5712. ast_rtp_instance_destroy(p->vrtp);
  5713. p->vrtp = NULL;
  5714. }
  5715. if (p->trtp) {
  5716. ast_rtp_instance_destroy(p->trtp);
  5717. p->trtp = NULL;
  5718. }
  5719. if (p->udptl) {
  5720. ast_udptl_destroy(p->udptl);
  5721. p->udptl = NULL;
  5722. }
  5723. if (p->refer) {
  5724. ast_string_field_free_memory(p->refer);
  5725. ast_free(p->refer);
  5726. p->refer = NULL;
  5727. }
  5728. sip_route_clear(&p->route);
  5729. deinit_req(&p->initreq);
  5730. /* Clear history */
  5731. if (p->history) {
  5732. struct sip_history *hist;
  5733. while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
  5734. ast_free(hist);
  5735. p->history_entries--;
  5736. }
  5737. ast_free(p->history);
  5738. p->history = NULL;
  5739. }
  5740. while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
  5741. ast_free(req);
  5742. }
  5743. offered_media_list_destroy(p);
  5744. if (p->chanvars) {
  5745. ast_variables_destroy(p->chanvars);
  5746. p->chanvars = NULL;
  5747. }
  5748. destroy_msg_headers(p);
  5749. if (p->srtp) {
  5750. ast_sdp_srtp_destroy(p->srtp);
  5751. p->srtp = NULL;
  5752. }
  5753. if (p->vsrtp) {
  5754. ast_sdp_srtp_destroy(p->vsrtp);
  5755. p->vsrtp = NULL;
  5756. }
  5757. if (p->tsrtp) {
  5758. ast_sdp_srtp_destroy(p->tsrtp);
  5759. p->tsrtp = NULL;
  5760. }
  5761. if (p->directmediaacl) {
  5762. p->directmediaacl = ast_free_acl_list(p->directmediaacl);
  5763. }
  5764. ast_string_field_free_memory(p);
  5765. ast_cc_config_params_destroy(p->cc_params);
  5766. p->cc_params = NULL;
  5767. if (p->epa_entry) {
  5768. ao2_ref(p->epa_entry, -1);
  5769. p->epa_entry = NULL;
  5770. }
  5771. if (p->socket.tcptls_session) {
  5772. ao2_ref(p->socket.tcptls_session, -1);
  5773. p->socket.tcptls_session = NULL;
  5774. } else if (p->socket.ws_session) {
  5775. ast_websocket_unref(p->socket.ws_session);
  5776. p->socket.ws_session = NULL;
  5777. }
  5778. if (p->peerauth) {
  5779. ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
  5780. p->peerauth = NULL;
  5781. }
  5782. p->named_callgroups = ast_unref_namedgroups(p->named_callgroups);
  5783. p->named_pickupgroups = ast_unref_namedgroups(p->named_pickupgroups);
  5784. ao2_cleanup(p->caps);
  5785. ao2_cleanup(p->jointcaps);
  5786. ao2_cleanup(p->peercaps);
  5787. ao2_cleanup(p->redircaps);
  5788. ao2_cleanup(p->prefcaps);
  5789. ast_rtp_dtls_cfg_free(&p->dtls_cfg);
  5790. if (p->last_device_state_info) {
  5791. ao2_ref(p->last_device_state_info, -1);
  5792. p->last_device_state_info = NULL;
  5793. }
  5794. /* Lastly, kill the callid associated with the pvt */
  5795. if (p->logger_callid) {
  5796. ast_callid_unref(p->logger_callid);
  5797. }
  5798. }
  5799. /*! \brief update_call_counter: Handle call_limit for SIP devices
  5800. * Setting a call-limit will cause calls above the limit not to be accepted.
  5801. *
  5802. * Remember that for a type=friend, there's one limit for the user and
  5803. * another for the peer, not a combined call limit.
  5804. * This will cause unexpected behaviour in subscriptions, since a "friend"
  5805. * is *two* devices in Asterisk, not one.
  5806. *
  5807. * Thought: For realtime, we should probably update storage with inuse counter...
  5808. *
  5809. * \return 0 if call is ok (no call limit, below threshold)
  5810. * -1 on rejection of call
  5811. *
  5812. */
  5813. static int update_call_counter(struct sip_pvt *fup, int event)
  5814. {
  5815. char name[256];
  5816. int *inuse = NULL, *call_limit = NULL, *ringing = NULL;
  5817. int outgoing = fup->outgoing_call;
  5818. struct sip_peer *p = NULL;
  5819. ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
  5820. /* Test if we need to check call limits, in order to avoid
  5821. realtime lookups if we do not need it */
  5822. if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
  5823. return 0;
  5824. ast_copy_string(name, fup->username, sizeof(name));
  5825. /* Check the list of devices */
  5826. if (fup->relatedpeer) {
  5827. p = sip_ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
  5828. inuse = &p->inuse;
  5829. call_limit = &p->call_limit;
  5830. ringing = &p->ringing;
  5831. ast_copy_string(name, fup->peername, sizeof(name));
  5832. }
  5833. if (!p) {
  5834. ast_debug(2, "%s is not a local device, no call limit\n", name);
  5835. return 0;
  5836. }
  5837. switch(event) {
  5838. /* incoming and outgoing affects the inuse counter */
  5839. case DEC_CALL_LIMIT:
  5840. /* Decrement inuse count if applicable */
  5841. if (inuse) {
  5842. sip_pvt_lock(fup);
  5843. ao2_lock(p);
  5844. if (*inuse > 0) {
  5845. if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
  5846. (*inuse)--;
  5847. ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
  5848. }
  5849. } else {
  5850. *inuse = 0;
  5851. }
  5852. ao2_unlock(p);
  5853. sip_pvt_unlock(fup);
  5854. }
  5855. /* Decrement ringing count if applicable */
  5856. if (ringing) {
  5857. sip_pvt_lock(fup);
  5858. ao2_lock(p);
  5859. if (*ringing > 0) {
  5860. if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
  5861. (*ringing)--;
  5862. ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
  5863. }
  5864. } else {
  5865. *ringing = 0;
  5866. }
  5867. ao2_unlock(p);
  5868. sip_pvt_unlock(fup);
  5869. }
  5870. /* Decrement onhold count if applicable */
  5871. sip_pvt_lock(fup);
  5872. ao2_lock(p);
  5873. if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
  5874. ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
  5875. ao2_unlock(p);
  5876. sip_pvt_unlock(fup);
  5877. sip_peer_hold(fup, FALSE);
  5878. } else {
  5879. ao2_unlock(p);
  5880. sip_pvt_unlock(fup);
  5881. }
  5882. if (sipdebug)
  5883. ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
  5884. break;
  5885. case INC_CALL_RINGING:
  5886. case INC_CALL_LIMIT:
  5887. /* If call limit is active and we have reached the limit, reject the call */
  5888. if (*call_limit > 0 ) {
  5889. if (*inuse >= *call_limit) {
  5890. ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
  5891. sip_unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
  5892. return -1;
  5893. }
  5894. }
  5895. if (ringing && (event == INC_CALL_RINGING)) {
  5896. sip_pvt_lock(fup);
  5897. ao2_lock(p);
  5898. if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
  5899. (*ringing)++;
  5900. ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
  5901. }
  5902. ao2_unlock(p);
  5903. sip_pvt_unlock(fup);
  5904. }
  5905. if (inuse) {
  5906. sip_pvt_lock(fup);
  5907. ao2_lock(p);
  5908. if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
  5909. (*inuse)++;
  5910. ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
  5911. }
  5912. ao2_unlock(p);
  5913. sip_pvt_unlock(fup);
  5914. }
  5915. if (sipdebug) {
  5916. ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
  5917. }
  5918. break;
  5919. case DEC_CALL_RINGING:
  5920. if (ringing) {
  5921. sip_pvt_lock(fup);
  5922. ao2_lock(p);
  5923. if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
  5924. if (*ringing > 0) {
  5925. (*ringing)--;
  5926. }
  5927. ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
  5928. }
  5929. ao2_unlock(p);
  5930. sip_pvt_unlock(fup);
  5931. }
  5932. break;
  5933. default:
  5934. ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
  5935. }
  5936. if (p) {
  5937. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", p->name);
  5938. sip_unref_peer(p, "update_call_counter: sip_unref_peer from call counter");
  5939. }
  5940. return 0;
  5941. }
  5942. static void sip_destroy_fn(void *p)
  5943. {
  5944. sip_destroy(p);
  5945. }
  5946. /*! \brief Destroy SIP call structure.
  5947. * Make it return NULL so the caller can do things like
  5948. * foo = sip_destroy(foo);
  5949. * and reduce the chance of bugs due to dangling pointers.
  5950. */
  5951. struct sip_pvt *sip_destroy(struct sip_pvt *p)
  5952. {
  5953. ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
  5954. __sip_destroy(p, TRUE, TRUE);
  5955. return NULL;
  5956. }
  5957. /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
  5958. int hangup_sip2cause(int cause)
  5959. {
  5960. /* Possible values taken from causes.h */
  5961. switch(cause) {
  5962. case 401: /* Unauthorized */
  5963. return AST_CAUSE_CALL_REJECTED;
  5964. case 403: /* Not found */
  5965. return AST_CAUSE_CALL_REJECTED;
  5966. case 404: /* Not found */
  5967. return AST_CAUSE_UNALLOCATED;
  5968. case 405: /* Method not allowed */
  5969. return AST_CAUSE_INTERWORKING;
  5970. case 407: /* Proxy authentication required */
  5971. return AST_CAUSE_CALL_REJECTED;
  5972. case 408: /* No reaction */
  5973. return AST_CAUSE_NO_USER_RESPONSE;
  5974. case 409: /* Conflict */
  5975. return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
  5976. case 410: /* Gone */
  5977. return AST_CAUSE_NUMBER_CHANGED;
  5978. case 411: /* Length required */
  5979. return AST_CAUSE_INTERWORKING;
  5980. case 413: /* Request entity too large */
  5981. return AST_CAUSE_INTERWORKING;
  5982. case 414: /* Request URI too large */
  5983. return AST_CAUSE_INTERWORKING;
  5984. case 415: /* Unsupported media type */
  5985. return AST_CAUSE_INTERWORKING;
  5986. case 420: /* Bad extension */
  5987. return AST_CAUSE_NO_ROUTE_DESTINATION;
  5988. case 480: /* No answer */
  5989. return AST_CAUSE_NO_ANSWER;
  5990. case 481: /* No answer */
  5991. return AST_CAUSE_INTERWORKING;
  5992. case 482: /* Loop detected */
  5993. return AST_CAUSE_INTERWORKING;
  5994. case 483: /* Too many hops */
  5995. return AST_CAUSE_NO_ANSWER;
  5996. case 484: /* Address incomplete */
  5997. return AST_CAUSE_INVALID_NUMBER_FORMAT;
  5998. case 485: /* Ambiguous */
  5999. return AST_CAUSE_UNALLOCATED;
  6000. case 486: /* Busy everywhere */
  6001. return AST_CAUSE_BUSY;
  6002. case 487: /* Request terminated */
  6003. return AST_CAUSE_INTERWORKING;
  6004. case 488: /* No codecs approved */
  6005. return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  6006. case 491: /* Request pending */
  6007. return AST_CAUSE_INTERWORKING;
  6008. case 493: /* Undecipherable */
  6009. return AST_CAUSE_INTERWORKING;
  6010. case 500: /* Server internal failure */
  6011. return AST_CAUSE_FAILURE;
  6012. case 501: /* Call rejected */
  6013. return AST_CAUSE_FACILITY_REJECTED;
  6014. case 502:
  6015. return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
  6016. case 503: /* Service unavailable */
  6017. return AST_CAUSE_CONGESTION;
  6018. case 504: /* Gateway timeout */
  6019. return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
  6020. case 505: /* SIP version not supported */
  6021. return AST_CAUSE_INTERWORKING;
  6022. case 600: /* Busy everywhere */
  6023. return AST_CAUSE_USER_BUSY;
  6024. case 603: /* Decline */
  6025. return AST_CAUSE_CALL_REJECTED;
  6026. case 604: /* Does not exist anywhere */
  6027. return AST_CAUSE_UNALLOCATED;
  6028. case 606: /* Not acceptable */
  6029. return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  6030. default:
  6031. if (cause < 500 && cause >= 400) {
  6032. /* 4xx class error that is unknown - someting wrong with our request */
  6033. return AST_CAUSE_INTERWORKING;
  6034. } else if (cause < 600 && cause >= 500) {
  6035. /* 5xx class error - problem in the remote end */
  6036. return AST_CAUSE_CONGESTION;
  6037. } else if (cause < 700 && cause >= 600) {
  6038. /* 6xx - global errors in the 4xx class */
  6039. return AST_CAUSE_INTERWORKING;
  6040. }
  6041. return AST_CAUSE_NORMAL;
  6042. }
  6043. /* Never reached */
  6044. return 0;
  6045. }
  6046. /*! \brief Convert Asterisk hangup causes to SIP codes
  6047. \verbatim
  6048. Possible values from causes.h
  6049. AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
  6050. AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
  6051. In addition to these, a lot of PRI codes is defined in causes.h
  6052. ...should we take care of them too ?
  6053. Quote RFC 3398
  6054. ISUP Cause value SIP response
  6055. ---------------- ------------
  6056. 1 unallocated number 404 Not Found
  6057. 2 no route to network 404 Not found
  6058. 3 no route to destination 404 Not found
  6059. 16 normal call clearing --- (*)
  6060. 17 user busy 486 Busy here
  6061. 18 no user responding 408 Request Timeout
  6062. 19 no answer from the user 480 Temporarily unavailable
  6063. 20 subscriber absent 480 Temporarily unavailable
  6064. 21 call rejected 403 Forbidden (+)
  6065. 22 number changed (w/o diagnostic) 410 Gone
  6066. 22 number changed (w/ diagnostic) 301 Moved Permanently
  6067. 23 redirection to new destination 410 Gone
  6068. 26 non-selected user clearing 404 Not Found (=)
  6069. 27 destination out of order 502 Bad Gateway
  6070. 28 address incomplete 484 Address incomplete
  6071. 29 facility rejected 501 Not implemented
  6072. 31 normal unspecified 480 Temporarily unavailable
  6073. \endverbatim
  6074. */
  6075. const char *hangup_cause2sip(int cause)
  6076. {
  6077. switch (cause) {
  6078. case AST_CAUSE_UNALLOCATED: /* 1 */
  6079. case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
  6080. case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
  6081. return "404 Not Found";
  6082. case AST_CAUSE_CONGESTION: /* 34 */
  6083. case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
  6084. return "503 Service Unavailable";
  6085. case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
  6086. return "408 Request Timeout";
  6087. case AST_CAUSE_NO_ANSWER: /* 19 */
  6088. case AST_CAUSE_UNREGISTERED: /* 20 */
  6089. return "480 Temporarily unavailable";
  6090. case AST_CAUSE_CALL_REJECTED: /* 21 */
  6091. return "403 Forbidden";
  6092. case AST_CAUSE_NUMBER_CHANGED: /* 22 */
  6093. return "410 Gone";
  6094. case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
  6095. return "480 Temporarily unavailable";
  6096. case AST_CAUSE_INVALID_NUMBER_FORMAT:
  6097. return "484 Address incomplete";
  6098. case AST_CAUSE_USER_BUSY:
  6099. return "486 Busy here";
  6100. case AST_CAUSE_FAILURE:
  6101. return "500 Server internal failure";
  6102. case AST_CAUSE_FACILITY_REJECTED: /* 29 */
  6103. return "501 Not Implemented";
  6104. case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
  6105. return "503 Service Unavailable";
  6106. /* Used in chan_iax2 */
  6107. case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
  6108. return "502 Bad Gateway";
  6109. case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
  6110. return "488 Not Acceptable Here";
  6111. case AST_CAUSE_INTERWORKING: /* Unspecified Interworking issues */
  6112. return "500 Network error";
  6113. case AST_CAUSE_NOTDEFINED:
  6114. default:
  6115. ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
  6116. return NULL;
  6117. }
  6118. /* Never reached */
  6119. return 0;
  6120. }
  6121. static int reinvite_timeout(const void *data)
  6122. {
  6123. struct sip_pvt *dialog = (struct sip_pvt *) data;
  6124. struct ast_channel *owner = sip_pvt_lock_full(dialog);
  6125. dialog->reinviteid = -1;
  6126. check_pendings(dialog);
  6127. if (owner) {
  6128. ast_channel_unlock(owner);
  6129. ast_channel_unref(owner);
  6130. }
  6131. ao2_unlock(dialog);
  6132. dialog_unref(dialog, "unref for reinvite timeout");
  6133. return 0;
  6134. }
  6135. /*! \brief sip_hangup: Hangup SIP call
  6136. * Part of PBX interface, called from ast_hangup */
  6137. static int sip_hangup(struct ast_channel *ast)
  6138. {
  6139. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6140. int needcancel = FALSE;
  6141. int needdestroy = 0;
  6142. struct ast_channel *oldowner = ast;
  6143. if (!p) {
  6144. ast_debug(1, "Asked to hangup channel that was not connected\n");
  6145. return 0;
  6146. }
  6147. if (ast_channel_hangupcause(ast) == AST_CAUSE_ANSWERED_ELSEWHERE) {
  6148. ast_debug(1, "This call was answered elsewhere\n");
  6149. append_history(p, "Cancel", "Call answered elsewhere");
  6150. p->answered_elsewhere = TRUE;
  6151. }
  6152. /* Store hangupcause locally in PVT so we still have it before disconnect */
  6153. if (p->owner)
  6154. p->hangupcause = ast_channel_hangupcause(p->owner);
  6155. if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
  6156. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  6157. if (sipdebug)
  6158. ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
  6159. update_call_counter(p, DEC_CALL_LIMIT);
  6160. }
  6161. ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
  6162. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  6163. ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
  6164. if (p->owner) {
  6165. sip_pvt_lock(p);
  6166. oldowner = p->owner;
  6167. sip_set_owner(p, NULL); /* Owner will be gone after we return, so take it away */
  6168. sip_pvt_unlock(p);
  6169. ast_channel_tech_pvt_set(oldowner, dialog_unref(ast_channel_tech_pvt(oldowner), "unref oldowner->tech_pvt"));
  6170. }
  6171. ast_module_unref(ast_module_info->self);
  6172. return 0;
  6173. }
  6174. ast_debug(1, "Hangup call %s, SIP callid %s\n", ast_channel_name(ast), p->callid);
  6175. sip_pvt_lock(p);
  6176. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  6177. if (sipdebug)
  6178. ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
  6179. update_call_counter(p, DEC_CALL_LIMIT);
  6180. }
  6181. /* Determine how to disconnect */
  6182. if (p->owner != ast) {
  6183. ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
  6184. sip_pvt_unlock(p);
  6185. return 0;
  6186. }
  6187. /* If the call is not UP, we need to send CANCEL instead of BYE */
  6188. /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
  6189. if (p->invitestate < INV_COMPLETED && ast_channel_state(p->owner) != AST_STATE_UP) {
  6190. needcancel = TRUE;
  6191. ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast_channel_state(ast)));
  6192. }
  6193. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  6194. append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", ast_cause2str(p->hangupcause));
  6195. /* Disconnect */
  6196. disable_dsp_detect(p);
  6197. sip_set_owner(p, NULL);
  6198. ast_channel_tech_pvt_set(ast, NULL);
  6199. ast_module_unref(ast_module_info->self);
  6200. /* Do not destroy this pvt until we have timeout or
  6201. get an answer to the BYE or INVITE/CANCEL
  6202. If we get no answer during retransmit period, drop the call anyway.
  6203. (Sorry, mother-in-law, you can't deny a hangup by sending
  6204. 603 declined to BYE...)
  6205. */
  6206. if (p->alreadygone)
  6207. needdestroy = 1; /* Set destroy flag at end of this function */
  6208. else if (p->invitestate != INV_CALLING)
  6209. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  6210. /* Start the process if it's not already started */
  6211. if (!p->alreadygone && p->initreq.data && ast_str_strlen(p->initreq.data)) {
  6212. if (needcancel) { /* Outgoing call, not up */
  6213. if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6214. /* if we can't send right now, mark it pending */
  6215. if (p->invitestate == INV_CALLING) {
  6216. /* We can't send anything in CALLING state */
  6217. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  6218. /* 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. */
  6219. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  6220. append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
  6221. } else {
  6222. struct sip_pkt *cur;
  6223. for (cur = p->packets; cur; cur = cur->next) {
  6224. __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(ast_str_buffer(cur->data)));
  6225. }
  6226. p->invitestate = INV_CANCELLED;
  6227. /* Send a new request: CANCEL */
  6228. transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
  6229. /* Actually don't destroy us yet, wait for the 487 on our original
  6230. INVITE, but do set an autodestruct just in case we never get it. */
  6231. needdestroy = 0;
  6232. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  6233. }
  6234. } else { /* Incoming call, not up */
  6235. const char *res;
  6236. 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"));
  6237. if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
  6238. transmit_response_reliable(p, res, &p->initreq);
  6239. else
  6240. transmit_response_reliable(p, "603 Declined", &p->initreq);
  6241. p->invitestate = INV_TERMINATED;
  6242. }
  6243. } else { /* Call is in UP state, send BYE */
  6244. if (p->stimer->st_active == TRUE) {
  6245. stop_session_timer(p);
  6246. }
  6247. if (!p->pendinginvite) {
  6248. char *quality;
  6249. char quality_buf[AST_MAX_USER_FIELD];
  6250. if (p->rtp) {
  6251. struct ast_rtp_instance *p_rtp;
  6252. p_rtp = p->rtp;
  6253. ao2_ref(p_rtp, +1);
  6254. ast_channel_unlock(oldowner);
  6255. sip_pvt_unlock(p);
  6256. ast_rtp_instance_set_stats_vars(oldowner, p_rtp);
  6257. ao2_ref(p_rtp, -1);
  6258. ast_channel_lock(oldowner);
  6259. sip_pvt_lock(p);
  6260. }
  6261. /*
  6262. * The channel variables are set below just to get the AMI
  6263. * VarSet event because the channel is being hungup.
  6264. */
  6265. if (p->rtp || p->vrtp || p->trtp) {
  6266. ast_channel_stage_snapshot(oldowner);
  6267. }
  6268. if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  6269. if (p->do_history) {
  6270. append_history(p, "RTCPaudio", "Quality:%s", quality);
  6271. }
  6272. pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
  6273. }
  6274. if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  6275. if (p->do_history) {
  6276. append_history(p, "RTCPvideo", "Quality:%s", quality);
  6277. }
  6278. pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
  6279. }
  6280. if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  6281. if (p->do_history) {
  6282. append_history(p, "RTCPtext", "Quality:%s", quality);
  6283. }
  6284. pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
  6285. }
  6286. if (p->rtp || p->vrtp || p->trtp) {
  6287. ast_channel_stage_snapshot_done(oldowner);
  6288. }
  6289. /* Send a hangup */
  6290. if (ast_channel_state(oldowner) == AST_STATE_UP) {
  6291. transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
  6292. }
  6293. } else {
  6294. /* Note we will need a BYE when this all settles out
  6295. but we can't send one while we have "INVITE" outstanding. */
  6296. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  6297. ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
  6298. 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"));
  6299. if (sip_cancel_destroy(p)) {
  6300. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  6301. }
  6302. /* If we have an ongoing reinvite, there is a chance that we have gotten a provisional
  6303. * response, but something weird has happened and we will never receive a final response.
  6304. * So, just in case, check for pending actions after a bit of time to trigger the pending
  6305. * bye that we are setting above */
  6306. if (p->ongoing_reinvite && p->reinviteid < 0) {
  6307. p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));
  6308. }
  6309. }
  6310. }
  6311. }
  6312. if (needdestroy) {
  6313. pvt_set_needdestroy(p, "hangup");
  6314. }
  6315. sip_pvt_unlock(p);
  6316. dialog_unref(p, "unref ast->tech_pvt");
  6317. return 0;
  6318. }
  6319. /*! \brief Try setting the codecs suggested by the SIP_CODEC channel variable */
  6320. static void try_suggested_sip_codec(struct sip_pvt *p)
  6321. {
  6322. const char *codec_list;
  6323. char *codec_list_copy;
  6324. struct ast_format_cap *original_jointcaps;
  6325. char *codec;
  6326. int first_codec = 1;
  6327. char *strtok_ptr;
  6328. if (p->outgoing_call) {
  6329. codec_list = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
  6330. } else if (!(codec_list = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
  6331. codec_list = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
  6332. }
  6333. if (ast_strlen_zero(codec_list)) {
  6334. return;
  6335. }
  6336. codec_list_copy = ast_strdupa(codec_list);
  6337. original_jointcaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  6338. if (!original_jointcaps) {
  6339. return;
  6340. }
  6341. ast_format_cap_append_from_cap(original_jointcaps, p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  6342. for (codec = strtok_r(codec_list_copy, ",", &strtok_ptr); codec; codec = strtok_r(NULL, ",", &strtok_ptr)) {
  6343. struct ast_format *fmt;
  6344. codec = ast_strip(codec);
  6345. fmt = ast_format_cache_get(codec);
  6346. if (!fmt) {
  6347. ast_log(AST_LOG_NOTICE, "Ignoring ${SIP_CODEC*} variable because of unrecognized/not configured codec %s (check allow/disallow in sip.conf)\n", codec);
  6348. continue;
  6349. }
  6350. if (ast_format_cap_iscompatible_format(original_jointcaps, fmt) != AST_FORMAT_CMP_NOT_EQUAL) {
  6351. if (first_codec) {
  6352. ast_verb(4, "Set codec to '%s' for this call because of ${SIP_CODEC*} variable\n", codec);
  6353. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  6354. ast_format_cap_append(p->jointcaps, fmt, 0);
  6355. ast_format_cap_remove_by_type(p->caps, AST_MEDIA_TYPE_UNKNOWN);
  6356. ast_format_cap_append(p->caps, fmt, 0);
  6357. first_codec = 0;
  6358. } else {
  6359. ast_verb(4, "Add codec to '%s' for this call because of ${SIP_CODEC*} variable\n", codec);
  6360. /* Add the format to the capabilities structure */
  6361. ast_format_cap_append(p->jointcaps, fmt, 0);
  6362. ast_format_cap_append(p->caps, fmt, 0);
  6363. }
  6364. } else {
  6365. ast_log(AST_LOG_NOTICE, "Ignoring ${SIP_CODEC*} variable because it is not shared by both ends: %s\n", codec);
  6366. }
  6367. ao2_ref(fmt, -1);
  6368. }
  6369. ao2_ref(original_jointcaps, -1);
  6370. return;
  6371. }
  6372. /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
  6373. * Part of PBX interface */
  6374. static int sip_answer(struct ast_channel *ast)
  6375. {
  6376. int res = 0;
  6377. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6378. int oldsdp = FALSE;
  6379. if (!p) {
  6380. ast_debug(1, "Asked to answer channel %s without tech pvt; ignoring\n",
  6381. ast_channel_name(ast));
  6382. return res;
  6383. }
  6384. sip_pvt_lock(p);
  6385. if (ast_channel_state(ast) != AST_STATE_UP) {
  6386. try_suggested_sip_codec(p);
  6387. if (ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
  6388. oldsdp = TRUE;
  6389. }
  6390. ast_setstate(ast, AST_STATE_UP);
  6391. ast_debug(1, "SIP answering channel: %s\n", ast_channel_name(ast));
  6392. ast_rtp_instance_update_source(p->rtp);
  6393. res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, oldsdp, TRUE);
  6394. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  6395. /* RFC says the session timer starts counting on 200,
  6396. * not on INVITE. */
  6397. if (p->stimer->st_active == TRUE) {
  6398. start_session_timer(p);
  6399. }
  6400. }
  6401. sip_pvt_unlock(p);
  6402. return res;
  6403. }
  6404. /*! \brief Send frame to media channel (rtp) */
  6405. static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
  6406. {
  6407. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6408. int res = 0;
  6409. switch (frame->frametype) {
  6410. case AST_FRAME_VOICE:
  6411. if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
  6412. struct ast_str *codec_buf = ast_str_alloca(64);
  6413. ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
  6414. ast_format_get_name(frame->subclass.format),
  6415. ast_format_cap_get_names(ast_channel_nativeformats(ast), &codec_buf),
  6416. ast_format_get_name(ast_channel_readformat(ast)),
  6417. ast_format_get_name(ast_channel_writeformat(ast)));
  6418. return 0;
  6419. }
  6420. if (p) {
  6421. sip_pvt_lock(p);
  6422. if (p->t38.state == T38_ENABLED) {
  6423. /* drop frame, can't sent VOICE frames while in T.38 mode */
  6424. sip_pvt_unlock(p);
  6425. break;
  6426. } else if (p->rtp) {
  6427. /* If channel is not up, activate early media session */
  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. ast_rtp_instance_update_source(p->rtp);
  6432. if (!global_prematuremediafilter) {
  6433. p->invitestate = INV_EARLY_MEDIA;
  6434. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6435. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6436. }
  6437. }
  6438. if (p->invitestate > INV_EARLY_MEDIA || (p->invitestate == INV_EARLY_MEDIA &&
  6439. ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT))) {
  6440. p->lastrtptx = time(NULL);
  6441. res = ast_rtp_instance_write(p->rtp, frame);
  6442. }
  6443. }
  6444. sip_pvt_unlock(p);
  6445. }
  6446. break;
  6447. case AST_FRAME_VIDEO:
  6448. if (p) {
  6449. sip_pvt_lock(p);
  6450. if (p->vrtp) {
  6451. /* Activate video early media */
  6452. if ((ast_channel_state(ast) != AST_STATE_UP) &&
  6453. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6454. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6455. p->invitestate = INV_EARLY_MEDIA;
  6456. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6457. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6458. }
  6459. if (p->invitestate > INV_EARLY_MEDIA || (p->invitestate == INV_EARLY_MEDIA &&
  6460. ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT))) {
  6461. p->lastrtptx = time(NULL);
  6462. res = ast_rtp_instance_write(p->vrtp, frame);
  6463. }
  6464. }
  6465. sip_pvt_unlock(p);
  6466. }
  6467. break;
  6468. case AST_FRAME_TEXT:
  6469. if (p) {
  6470. sip_pvt_lock(p);
  6471. if (p->red) {
  6472. ast_rtp_red_buffer(p->trtp, frame);
  6473. } else {
  6474. if (p->trtp) {
  6475. /* Activate text early media */
  6476. if ((ast_channel_state(ast) != AST_STATE_UP) &&
  6477. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6478. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6479. p->invitestate = INV_EARLY_MEDIA;
  6480. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6481. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6482. }
  6483. if (p->invitestate > INV_EARLY_MEDIA || (p->invitestate == INV_EARLY_MEDIA &&
  6484. ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT))) {
  6485. p->lastrtptx = time(NULL);
  6486. res = ast_rtp_instance_write(p->trtp, frame);
  6487. }
  6488. }
  6489. }
  6490. sip_pvt_unlock(p);
  6491. }
  6492. break;
  6493. case AST_FRAME_IMAGE:
  6494. return 0;
  6495. break;
  6496. case AST_FRAME_MODEM:
  6497. if (p) {
  6498. sip_pvt_lock(p);
  6499. /* UDPTL requires two-way communication, so early media is not needed here.
  6500. we simply forget the frames if we get modem frames before the bridge is up.
  6501. Fax will re-transmit.
  6502. */
  6503. if ((ast_channel_state(ast) == AST_STATE_UP) &&
  6504. p->udptl &&
  6505. (p->t38.state == T38_ENABLED)) {
  6506. res = ast_udptl_write(p->udptl, frame);
  6507. }
  6508. sip_pvt_unlock(p);
  6509. }
  6510. break;
  6511. default:
  6512. ast_log(LOG_WARNING, "Can't send %u type frames with SIP write\n", frame->frametype);
  6513. return 0;
  6514. }
  6515. return res;
  6516. }
  6517. /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
  6518. Basically update any ->owner links */
  6519. static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
  6520. {
  6521. int ret = -1;
  6522. struct sip_pvt *p;
  6523. if (newchan && ast_test_flag(ast_channel_flags(newchan), AST_FLAG_ZOMBIE))
  6524. ast_debug(1, "New channel is zombie\n");
  6525. if (oldchan && ast_test_flag(ast_channel_flags(oldchan), AST_FLAG_ZOMBIE))
  6526. ast_debug(1, "Old channel is zombie\n");
  6527. if (!newchan || !ast_channel_tech_pvt(newchan)) {
  6528. if (!newchan)
  6529. ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", ast_channel_name(oldchan));
  6530. else
  6531. ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", ast_channel_name(oldchan));
  6532. return -1;
  6533. }
  6534. p = ast_channel_tech_pvt(newchan);
  6535. sip_pvt_lock(p);
  6536. append_history(p, "Masq", "Old channel: %s\n", ast_channel_name(oldchan));
  6537. append_history(p, "Masq (cont)", "...new owner: %s\n", ast_channel_name(newchan));
  6538. if (p->owner != oldchan)
  6539. ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
  6540. else {
  6541. sip_set_owner(p, newchan);
  6542. /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
  6543. RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
  6544. able to do this if the masquerade happens before the bridge breaks (e.g., AMI
  6545. redirect of both channels). Note that a channel can not be masqueraded *into*
  6546. a native bridge. So there is no danger that this breaks a native bridge that
  6547. should stay up. */
  6548. sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
  6549. ret = 0;
  6550. }
  6551. 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));
  6552. sip_pvt_unlock(p);
  6553. return ret;
  6554. }
  6555. static int sip_senddigit_begin(struct ast_channel *ast, char digit)
  6556. {
  6557. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6558. int res = 0;
  6559. if (!p) {
  6560. ast_debug(1, "Asked to begin DTMF digit on channel %s with no pvt; ignoring\n",
  6561. ast_channel_name(ast));
  6562. return res;
  6563. }
  6564. sip_pvt_lock(p);
  6565. switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
  6566. case SIP_DTMF_INBAND:
  6567. res = -1; /* Tell Asterisk to generate inband indications */
  6568. break;
  6569. case SIP_DTMF_RFC2833:
  6570. if (p->rtp)
  6571. ast_rtp_instance_dtmf_begin(p->rtp, digit);
  6572. break;
  6573. default:
  6574. break;
  6575. }
  6576. sip_pvt_unlock(p);
  6577. return res;
  6578. }
  6579. /*! \brief Send DTMF character on SIP channel
  6580. within one call, we're able to transmit in many methods simultaneously */
  6581. static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
  6582. {
  6583. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6584. int res = 0;
  6585. if (!p) {
  6586. ast_debug(1, "Asked to end DTMF digit on channel %s with no pvt; ignoring\n",
  6587. ast_channel_name(ast));
  6588. return res;
  6589. }
  6590. sip_pvt_lock(p);
  6591. switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
  6592. case SIP_DTMF_INFO:
  6593. case SIP_DTMF_SHORTINFO:
  6594. transmit_info_with_digit(p, digit, duration);
  6595. break;
  6596. case SIP_DTMF_RFC2833:
  6597. if (p->rtp)
  6598. ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
  6599. break;
  6600. case SIP_DTMF_INBAND:
  6601. res = -1; /* Tell Asterisk to stop inband indications */
  6602. break;
  6603. }
  6604. sip_pvt_unlock(p);
  6605. return res;
  6606. }
  6607. /*! \brief Transfer SIP call */
  6608. static int sip_transfer(struct ast_channel *ast, const char *dest)
  6609. {
  6610. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6611. int res;
  6612. if (!p) {
  6613. ast_debug(1, "Asked to transfer channel %s with no pvt; ignoring\n",
  6614. ast_channel_name(ast));
  6615. return -1;
  6616. }
  6617. if (dest == NULL) /* functions below do not take a NULL */
  6618. dest = "";
  6619. sip_pvt_lock(p);
  6620. if (ast_channel_state(ast) == AST_STATE_RING)
  6621. res = sip_sipredirect(p, dest);
  6622. else
  6623. res = transmit_refer(p, dest);
  6624. sip_pvt_unlock(p);
  6625. return res;
  6626. }
  6627. /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
  6628. static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
  6629. {
  6630. int res = 0;
  6631. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
  6632. return -1;
  6633. }
  6634. switch (parameters->request_response) {
  6635. case AST_T38_NEGOTIATED:
  6636. case AST_T38_REQUEST_NEGOTIATE: /* Request T38 */
  6637. /* Negotiation can not take place without a valid max_ifp value. */
  6638. if (!parameters->max_ifp) {
  6639. if (p->t38.state == T38_PEER_REINVITE) {
  6640. 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"));
  6641. transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
  6642. }
  6643. change_t38_state(p, T38_REJECTED);
  6644. break;
  6645. } else if (p->t38.state == T38_PEER_REINVITE) {
  6646. 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"));
  6647. p->t38.our_parms = *parameters;
  6648. /* modify our parameters to conform to the peer's parameters,
  6649. * based on the rules in the ITU T.38 recommendation
  6650. */
  6651. if (!p->t38.their_parms.fill_bit_removal) {
  6652. p->t38.our_parms.fill_bit_removal = FALSE;
  6653. }
  6654. if (!p->t38.their_parms.transcoding_mmr) {
  6655. p->t38.our_parms.transcoding_mmr = FALSE;
  6656. }
  6657. if (!p->t38.their_parms.transcoding_jbig) {
  6658. p->t38.our_parms.transcoding_jbig = FALSE;
  6659. }
  6660. p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
  6661. p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
  6662. ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
  6663. change_t38_state(p, T38_ENABLED);
  6664. transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
  6665. } else if (p->t38.state != T38_ENABLED) {
  6666. p->t38.our_parms = *parameters;
  6667. ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
  6668. change_t38_state(p, T38_LOCAL_REINVITE);
  6669. if (!p->pendinginvite) {
  6670. transmit_reinvite_with_sdp(p, TRUE, FALSE);
  6671. } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  6672. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  6673. }
  6674. }
  6675. break;
  6676. case AST_T38_TERMINATED:
  6677. case AST_T38_REFUSED:
  6678. case AST_T38_REQUEST_TERMINATE: /* Shutdown T38 */
  6679. if (p->t38.state == T38_PEER_REINVITE) {
  6680. 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"));
  6681. change_t38_state(p, T38_REJECTED);
  6682. transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
  6683. } else if (p->t38.state == T38_ENABLED)
  6684. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  6685. break;
  6686. case AST_T38_REQUEST_PARMS: { /* Application wants remote's parameters re-sent */
  6687. struct ast_control_t38_parameters parameters = p->t38.their_parms;
  6688. if (p->t38.state == T38_PEER_REINVITE) {
  6689. 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"));
  6690. parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
  6691. parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
  6692. if (p->owner) {
  6693. ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
  6694. }
  6695. /* we need to return a positive value here, so that applications that
  6696. * send this request can determine conclusively whether it was accepted or not...
  6697. * older versions of chan_sip would just silently accept it and return zero.
  6698. */
  6699. res = AST_T38_REQUEST_PARMS;
  6700. }
  6701. break;
  6702. }
  6703. default:
  6704. res = -1;
  6705. break;
  6706. }
  6707. return res;
  6708. }
  6709. /*!
  6710. * \internal
  6711. * \brief Create and initialize UDPTL for the specified dialog
  6712. *
  6713. * \param p SIP private structure to create UDPTL object for
  6714. * \pre p is locked
  6715. * \pre p->owner is locked
  6716. *
  6717. * \note In the case of failure, SIP_PAGE2_T38SUPPORT is cleared on p
  6718. *
  6719. * \return 0 on success, any other value on failure
  6720. */
  6721. static int initialize_udptl(struct sip_pvt *p)
  6722. {
  6723. int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
  6724. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
  6725. return 1;
  6726. }
  6727. /* If we've already initialized T38, don't take any further action */
  6728. if (p->udptl) {
  6729. return 0;
  6730. }
  6731. /* T38 can be supported by this dialog, create it and set the derived properties */
  6732. if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
  6733. if (p->owner) {
  6734. ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
  6735. }
  6736. ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
  6737. p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
  6738. set_t38_capabilities(p);
  6739. ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
  6740. ast_udptl_setnat(p->udptl, natflags);
  6741. } else {
  6742. ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
  6743. ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
  6744. return 1;
  6745. }
  6746. return 0;
  6747. }
  6748. static int sipinfo_send(
  6749. struct ast_channel *chan,
  6750. struct ast_variable *headers,
  6751. const char *content_type,
  6752. const char *content,
  6753. const char *useragent_filter)
  6754. {
  6755. struct sip_pvt *p;
  6756. struct ast_variable *var;
  6757. struct sip_request req;
  6758. int res = -1;
  6759. ast_channel_lock(chan);
  6760. if (ast_channel_tech(chan) != &sip_tech) {
  6761. ast_log(LOG_WARNING, "Attempted to send a custom INFO on a non-SIP channel %s\n", ast_channel_name(chan));
  6762. ast_channel_unlock(chan);
  6763. return res;
  6764. }
  6765. p = ast_channel_tech_pvt(chan);
  6766. sip_pvt_lock(p);
  6767. if (!(ast_strlen_zero(useragent_filter))) {
  6768. int match = (strstr(p->useragent, useragent_filter)) ? 1 : 0;
  6769. if (!match) {
  6770. goto cleanup;
  6771. }
  6772. }
  6773. reqprep(&req, p, SIP_INFO, 0, 1);
  6774. for (var = headers; var; var = var->next) {
  6775. add_header(&req, var->name, var->value);
  6776. }
  6777. if (!ast_strlen_zero(content) && !ast_strlen_zero(content_type)) {
  6778. add_header(&req, "Content-Type", content_type);
  6779. add_content(&req, content);
  6780. }
  6781. res = send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  6782. cleanup:
  6783. sip_pvt_unlock(p);
  6784. ast_channel_unlock(chan);
  6785. return res;
  6786. }
  6787. /*! \brief Play indication to user
  6788. * With SIP a lot of indications is sent as messages, letting the device play
  6789. the indication - busy signal, congestion etc
  6790. \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
  6791. */
  6792. static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
  6793. {
  6794. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  6795. int res = 0;
  6796. if (!p) {
  6797. ast_debug(1, "Asked to indicate condition on channel %s with no pvt; ignoring\n",
  6798. ast_channel_name(ast));
  6799. return res;
  6800. }
  6801. sip_pvt_lock(p);
  6802. switch(condition) {
  6803. case AST_CONTROL_RINGING:
  6804. if (ast_channel_state(ast) == AST_STATE_RING) {
  6805. p->invitestate = INV_EARLY_MEDIA;
  6806. if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
  6807. (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
  6808. /* Send 180 ringing if out-of-band seems reasonable */
  6809. transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
  6810. ast_set_flag(&p->flags[0], SIP_RINGING);
  6811. if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
  6812. break;
  6813. } else {
  6814. /* Well, if it's not reasonable, just send in-band */
  6815. }
  6816. }
  6817. res = -1;
  6818. break;
  6819. case AST_CONTROL_BUSY:
  6820. if (ast_channel_state(ast) != AST_STATE_UP) {
  6821. transmit_response_reliable(p, "486 Busy Here", &p->initreq);
  6822. p->invitestate = INV_COMPLETED;
  6823. sip_alreadygone(p);
  6824. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6825. break;
  6826. }
  6827. res = -1;
  6828. break;
  6829. case AST_CONTROL_CONGESTION:
  6830. if (ast_channel_state(ast) != AST_STATE_UP) {
  6831. transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
  6832. p->invitestate = INV_COMPLETED;
  6833. sip_alreadygone(p);
  6834. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6835. break;
  6836. }
  6837. res = -1;
  6838. break;
  6839. case AST_CONTROL_INCOMPLETE:
  6840. if (ast_channel_state(ast) != AST_STATE_UP) {
  6841. switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
  6842. case SIP_PAGE2_ALLOWOVERLAP_YES:
  6843. transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
  6844. p->invitestate = INV_COMPLETED;
  6845. sip_alreadygone(p);
  6846. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6847. break;
  6848. case SIP_PAGE2_ALLOWOVERLAP_DTMF:
  6849. /* Just wait for inband DTMF digits */
  6850. break;
  6851. default:
  6852. /* it actually means no support for overlap */
  6853. transmit_response_reliable(p, "404 Not Found", &p->initreq);
  6854. p->invitestate = INV_COMPLETED;
  6855. sip_alreadygone(p);
  6856. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6857. break;
  6858. }
  6859. }
  6860. break;
  6861. case AST_CONTROL_PROCEEDING:
  6862. if ((ast_channel_state(ast) != AST_STATE_UP) &&
  6863. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6864. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6865. transmit_response(p, "100 Trying", &p->initreq);
  6866. p->invitestate = INV_PROCEEDING;
  6867. break;
  6868. }
  6869. res = -1;
  6870. break;
  6871. case AST_CONTROL_PROGRESS:
  6872. if ((ast_channel_state(ast) != AST_STATE_UP) &&
  6873. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6874. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6875. p->invitestate = INV_EARLY_MEDIA;
  6876. /* SIP_PROG_INBAND_NEVER means sending 180 ringing in place of a 183 */
  6877. if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_NEVER) {
  6878. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6879. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6880. } else if (ast_channel_state(ast) == AST_STATE_RING && !ast_test_flag(&p->flags[0], SIP_RINGING)) {
  6881. transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
  6882. ast_set_flag(&p->flags[0], SIP_RINGING);
  6883. }
  6884. break;
  6885. }
  6886. res = -1;
  6887. break;
  6888. case AST_CONTROL_HOLD:
  6889. ast_rtp_instance_update_source(p->rtp);
  6890. ast_moh_start(ast, data, p->mohinterpret);
  6891. break;
  6892. case AST_CONTROL_UNHOLD:
  6893. ast_rtp_instance_update_source(p->rtp);
  6894. ast_moh_stop(ast);
  6895. break;
  6896. case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
  6897. if (p->vrtp && !p->novideo) {
  6898. /* FIXME: Only use this for VP8. Additional work would have to be done to
  6899. * fully support other video codecs */
  6900. if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL) {
  6901. /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
  6902. * RTP engine would provide a way to externally write/schedule RTCP
  6903. * packets */
  6904. struct ast_frame fr;
  6905. fr.frametype = AST_FRAME_CONTROL;
  6906. fr.subclass.integer = AST_CONTROL_VIDUPDATE;
  6907. res = ast_rtp_instance_write(p->vrtp, &fr);
  6908. } else {
  6909. transmit_info_with_vidupdate(p);
  6910. }
  6911. } else {
  6912. res = -1;
  6913. }
  6914. break;
  6915. case AST_CONTROL_T38_PARAMETERS:
  6916. res = -1;
  6917. if (datalen != sizeof(struct ast_control_t38_parameters)) {
  6918. 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);
  6919. } else {
  6920. const struct ast_control_t38_parameters *parameters = data;
  6921. if (!initialize_udptl(p)) {
  6922. res = interpret_t38_parameters(p, parameters);
  6923. }
  6924. }
  6925. break;
  6926. case AST_CONTROL_SRCUPDATE:
  6927. ast_rtp_instance_update_source(p->rtp);
  6928. break;
  6929. case AST_CONTROL_SRCCHANGE:
  6930. ast_rtp_instance_change_source(p->rtp);
  6931. break;
  6932. case AST_CONTROL_CONNECTED_LINE:
  6933. update_connectedline(p, data, datalen);
  6934. break;
  6935. case AST_CONTROL_REDIRECTING:
  6936. update_redirecting(p, data, datalen);
  6937. break;
  6938. case AST_CONTROL_AOC:
  6939. {
  6940. struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
  6941. if (!decoded) {
  6942. ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
  6943. res = -1;
  6944. break;
  6945. }
  6946. switch (ast_aoc_get_msg_type(decoded)) {
  6947. case AST_AOC_REQUEST:
  6948. if (ast_aoc_get_termination_request(decoded)) {
  6949. /* TODO, once there is a way to get AOC-E on hangup, attempt that here
  6950. * before hanging up the channel.*/
  6951. /* The other side has already initiated the hangup. This frame
  6952. * just says they are waiting to get AOC-E before completely tearing
  6953. * the call down. Since SIP does not support this at the moment go
  6954. * ahead and terminate the call here to avoid an unnecessary timeout. */
  6955. 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));
  6956. ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
  6957. }
  6958. break;
  6959. case AST_AOC_D:
  6960. case AST_AOC_E:
  6961. if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
  6962. transmit_info_with_aoc(p, decoded);
  6963. }
  6964. break;
  6965. case AST_AOC_S: /* S not supported yet */
  6966. default:
  6967. break;
  6968. }
  6969. ast_aoc_destroy_decoded(decoded);
  6970. }
  6971. break;
  6972. case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
  6973. break;
  6974. 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. */
  6975. res = -1;
  6976. break;
  6977. case AST_CONTROL_PVT_CAUSE_CODE: /* these should be handled by the code in channel.c */
  6978. case AST_CONTROL_MASQUERADE_NOTIFY:
  6979. case -1:
  6980. res = -1;
  6981. break;
  6982. default:
  6983. ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
  6984. res = -1;
  6985. break;
  6986. }
  6987. sip_pvt_unlock(p);
  6988. return res;
  6989. }
  6990. /*!
  6991. * \brief Initiate a call in the SIP channel
  6992. *
  6993. * \note called from sip_request_call (calls from the pbx ) for
  6994. * outbound channels and from handle_request_invite for inbound
  6995. * channels
  6996. *
  6997. * \pre i is locked
  6998. *
  6999. * \return New ast_channel locked.
  7000. */
  7001. 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, struct ast_callid *callid)
  7002. {
  7003. struct ast_format_cap *caps;
  7004. struct ast_channel *tmp;
  7005. struct ast_variable *v = NULL;
  7006. struct ast_format *fmt;
  7007. struct ast_format_cap *what = NULL; /* SHALLOW COPY DO NOT DESTROY! */
  7008. struct ast_str *codec_buf = ast_str_alloca(64);
  7009. int needvideo = 0;
  7010. int needtext = 0;
  7011. char *exten;
  7012. caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7013. if (!caps) {
  7014. return NULL;
  7015. }
  7016. {
  7017. const char *my_name; /* pick a good name */
  7018. if (title) {
  7019. my_name = title;
  7020. } else {
  7021. my_name = ast_strdupa(i->fromdomain);
  7022. }
  7023. /* Don't hold a sip pvt lock while we allocate a channel */
  7024. sip_pvt_unlock(i);
  7025. if (i->relatedpeer && i->relatedpeer->endpoint) {
  7026. 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));
  7027. } else {
  7028. 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));
  7029. }
  7030. }
  7031. if (!tmp) {
  7032. ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
  7033. ao2_ref(caps, -1);
  7034. sip_pvt_lock(i);
  7035. return NULL;
  7036. }
  7037. ast_channel_stage_snapshot(tmp);
  7038. /* If we sent in a callid, bind it to the channel. */
  7039. if (callid) {
  7040. ast_channel_callid_set(tmp, callid);
  7041. }
  7042. sip_pvt_lock(i);
  7043. ast_channel_cc_params_init(tmp, i->cc_params);
  7044. ast_channel_caller(tmp)->id.tag = ast_strdup(i->cid_tag);
  7045. 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);
  7046. /* Select our native format based on codec preference until we receive
  7047. something from another device to the contrary. */
  7048. if (ast_format_cap_count(i->jointcaps)) { /* The joint capabilities of us and peer */
  7049. what = i->jointcaps;
  7050. } else if (ast_format_cap_count(i->caps)) { /* Our configured capability for this peer */
  7051. what = i->caps;
  7052. } else {
  7053. what = sip_cfg.caps;
  7054. }
  7055. /* Set the native formats */
  7056. ast_format_cap_append_from_cap(caps, what, AST_MEDIA_TYPE_UNKNOWN);
  7057. /* Use only the preferred audio format, which is stored at the '0' index */
  7058. fmt = ast_format_cap_get_best_by_type(what, AST_MEDIA_TYPE_AUDIO); /* get the best audio format */
  7059. if (fmt) {
  7060. ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_AUDIO); /* remove only the other audio formats */
  7061. ast_format_cap_append(caps, fmt, 0); /* add our best choice back */
  7062. } else {
  7063. /* If we don't have an audio format, try to get something */
  7064. fmt = ast_format_cap_get_format(caps, 0);
  7065. if (!fmt) {
  7066. ast_log(LOG_WARNING, "No compatible formats could be found for %s\n", ast_channel_name(tmp));
  7067. ao2_ref(caps, -1);
  7068. tmp = ast_channel_unref(tmp);
  7069. return NULL;
  7070. }
  7071. }
  7072. ast_channel_nativeformats_set(tmp, caps);
  7073. ao2_ref(caps, -1);
  7074. ast_debug(3, "*** Our native formats are %s \n", ast_format_cap_get_names(ast_channel_nativeformats(tmp), &codec_buf));
  7075. ast_debug(3, "*** Joint capabilities are %s \n", ast_format_cap_get_names(i->jointcaps, &codec_buf));
  7076. ast_debug(3, "*** Our capabilities are %s \n", ast_format_cap_get_names(i->caps, &codec_buf));
  7077. ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_format_get_name(fmt));
  7078. if (ast_format_cap_count(i->prefcaps)) {
  7079. ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_format_cap_get_names(i->prefcaps, &codec_buf));
  7080. }
  7081. /* If we have a prefcodec setting, we have an inbound channel that set a
  7082. preferred format for this call. Otherwise, we check the jointcapability
  7083. We also check for vrtp. If it's not there, we are not allowed do any video anyway.
  7084. */
  7085. if (i->vrtp) {
  7086. if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
  7087. needvideo = 1;
  7088. else if (ast_format_cap_count(i->prefcaps))
  7089. needvideo = ast_format_cap_has_type(i->prefcaps, AST_MEDIA_TYPE_VIDEO); /* Outbound call */
  7090. else
  7091. needvideo = ast_format_cap_has_type(i->jointcaps, AST_MEDIA_TYPE_VIDEO); /* Inbound call */
  7092. }
  7093. if (i->trtp) {
  7094. if (ast_format_cap_count(i->prefcaps))
  7095. needtext = ast_format_cap_has_type(i->prefcaps, AST_MEDIA_TYPE_TEXT); /* Outbound call */
  7096. else
  7097. needtext = ast_format_cap_has_type(i->jointcaps, AST_MEDIA_TYPE_TEXT); /* Inbound call */
  7098. }
  7099. if (needvideo) {
  7100. ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
  7101. } else {
  7102. ast_debug(3, "This channel will not be able to handle video.\n");
  7103. }
  7104. enable_dsp_detect(i);
  7105. if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  7106. (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  7107. if (i->rtp) {
  7108. ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
  7109. }
  7110. } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
  7111. if (i->rtp) {
  7112. ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
  7113. }
  7114. }
  7115. /* Set file descriptors for audio, video, and realtime text. Since
  7116. * UDPTL is created as needed in the lifetime of a dialog, its file
  7117. * descriptor is set in initialize_udptl */
  7118. if (i->rtp) {
  7119. ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
  7120. ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
  7121. ast_rtp_instance_set_write_format(i->rtp, fmt);
  7122. ast_rtp_instance_set_read_format(i->rtp, fmt);
  7123. }
  7124. if (needvideo && i->vrtp) {
  7125. ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
  7126. ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
  7127. }
  7128. if (needtext && i->trtp) {
  7129. ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
  7130. }
  7131. if (i->udptl) {
  7132. ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
  7133. }
  7134. if (state == AST_STATE_RING) {
  7135. ast_channel_rings_set(tmp, 1);
  7136. }
  7137. ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
  7138. ast_channel_set_writeformat(tmp, fmt);
  7139. ast_channel_set_rawwriteformat(tmp, fmt);
  7140. ast_channel_set_readformat(tmp, fmt);
  7141. ast_channel_set_rawreadformat(tmp, fmt);
  7142. ao2_ref(fmt, -1);
  7143. ast_channel_tech_pvt_set(tmp, dialog_ref(i, "sip_new: set chan->tech_pvt to i"));
  7144. ast_channel_callgroup_set(tmp, i->callgroup);
  7145. ast_channel_pickupgroup_set(tmp, i->pickupgroup);
  7146. ast_channel_named_callgroups_set(tmp, i->named_callgroups);
  7147. ast_channel_named_pickupgroups_set(tmp, i->named_pickupgroups);
  7148. ast_channel_caller(tmp)->id.name.presentation = i->callingpres;
  7149. ast_channel_caller(tmp)->id.number.presentation = i->callingpres;
  7150. if (!ast_strlen_zero(i->parkinglot)) {
  7151. ast_channel_parkinglot_set(tmp, i->parkinglot);
  7152. }
  7153. if (!ast_strlen_zero(i->accountcode)) {
  7154. ast_channel_accountcode_set(tmp, i->accountcode);
  7155. }
  7156. if (i->amaflags) {
  7157. ast_channel_amaflags_set(tmp, i->amaflags);
  7158. }
  7159. if (!ast_strlen_zero(i->language)) {
  7160. ast_channel_language_set(tmp, i->language);
  7161. }
  7162. if (!ast_strlen_zero(i->zone)) {
  7163. struct ast_tone_zone *zone;
  7164. if (!(zone = ast_get_indication_zone(i->zone))) {
  7165. ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", i->zone);
  7166. }
  7167. ast_channel_zone_set(tmp, zone);
  7168. }
  7169. sip_set_owner(i, tmp);
  7170. ast_module_ref(ast_module_info->self);
  7171. ast_channel_context_set(tmp, i->context);
  7172. /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
  7173. * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
  7174. * structure so that there aren't issues when forming URI's
  7175. */
  7176. exten = ast_strdupa(i->exten);
  7177. sip_pvt_unlock(i);
  7178. ast_channel_unlock(tmp);
  7179. if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
  7180. ast_uri_decode(exten, ast_uri_sip_user);
  7181. }
  7182. ast_channel_lock(tmp);
  7183. sip_pvt_lock(i);
  7184. ast_channel_exten_set(tmp, exten);
  7185. /* Don't use ast_set_callerid() here because it will
  7186. * generate an unnecessary NewCallerID event */
  7187. if (!ast_strlen_zero(i->cid_num)) {
  7188. ast_channel_caller(tmp)->ani.number.valid = 1;
  7189. ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
  7190. }
  7191. if (!ast_strlen_zero(i->rdnis)) {
  7192. ast_channel_redirecting(tmp)->from.number.valid = 1;
  7193. ast_channel_redirecting(tmp)->from.number.str = ast_strdup(i->rdnis);
  7194. }
  7195. if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
  7196. ast_channel_dialed(tmp)->number.str = ast_strdup(i->exten);
  7197. }
  7198. ast_channel_priority_set(tmp, 1);
  7199. if (!ast_strlen_zero(i->uri)) {
  7200. pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
  7201. }
  7202. if (!ast_strlen_zero(i->domain)) {
  7203. pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
  7204. }
  7205. if (!ast_strlen_zero(i->tel_phone_context)) {
  7206. pbx_builtin_setvar_helper(tmp, "SIPURIPHONECONTEXT", i->tel_phone_context);
  7207. }
  7208. if (!ast_strlen_zero(i->callid)) {
  7209. pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
  7210. }
  7211. if (i->rtp) {
  7212. ast_jb_configure(tmp, &global_jbconf);
  7213. }
  7214. if (!i->relatedpeer) {
  7215. ast_set_flag(ast_channel_flags(tmp), AST_FLAG_DISABLE_DEVSTATE_CACHE);
  7216. }
  7217. /* Set channel variables for this call from configuration */
  7218. for (v = i->chanvars ; v ; v = v->next) {
  7219. char valuebuf[1024];
  7220. pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
  7221. }
  7222. if (i->do_history) {
  7223. append_history(i, "NewChan", "Channel %s - from %s", ast_channel_name(tmp), i->callid);
  7224. }
  7225. ast_channel_stage_snapshot_done(tmp);
  7226. return tmp;
  7227. }
  7228. /*! \brief Lookup 'name' in the SDP starting
  7229. * at the 'start' line. Returns the matching line, and 'start'
  7230. * is updated with the next line number.
  7231. */
  7232. static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
  7233. {
  7234. int len = strlen(name);
  7235. const char *line;
  7236. while (*start < (req->sdp_start + req->sdp_count)) {
  7237. line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
  7238. if (!strncasecmp(line, name, len) && line[len] == '=') {
  7239. return ast_skip_blanks(line + len + 1);
  7240. }
  7241. }
  7242. /* if the line was not found, ensure that *start points past the SDP */
  7243. (*start)++;
  7244. return "";
  7245. }
  7246. /*! \brief Fetches the next valid SDP line between the 'start' line
  7247. * (inclusive) and the 'stop' line (exclusive). Returns the type
  7248. * ('a', 'c', ...) and matching line in reference 'start' is updated
  7249. * with the next line number.
  7250. */
  7251. static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
  7252. {
  7253. char type = '\0';
  7254. const char *line = NULL;
  7255. if (stop > (req->sdp_start + req->sdp_count)) {
  7256. stop = req->sdp_start + req->sdp_count;
  7257. }
  7258. while (*start < stop) {
  7259. line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
  7260. if (line[1] == '=') {
  7261. type = line[0];
  7262. *value = ast_skip_blanks(line + 2);
  7263. break;
  7264. }
  7265. }
  7266. return type;
  7267. }
  7268. /*! \brief Get a specific line from the message content */
  7269. static char *get_content_line(struct sip_request *req, char *name, char delimiter)
  7270. {
  7271. int i;
  7272. int len = strlen(name);
  7273. const char *line;
  7274. for (i = 0; i < req->lines; i++) {
  7275. line = REQ_OFFSET_TO_STR(req, line[i]);
  7276. if (!strncasecmp(line, name, len) && line[len] == delimiter) {
  7277. return ast_skip_blanks(line + len + 1);
  7278. }
  7279. }
  7280. return "";
  7281. }
  7282. /*! \brief Structure for conversion between compressed SIP and "normal" SIP headers */
  7283. struct cfalias {
  7284. const char *fullname;
  7285. const char *shortname;
  7286. };
  7287. static const struct cfalias aliases[] = {
  7288. { "Content-Type", "c" },
  7289. { "Content-Encoding", "e" },
  7290. { "From", "f" },
  7291. { "Call-ID", "i" },
  7292. { "Contact", "m" },
  7293. { "Content-Length", "l" },
  7294. { "Subject", "s" },
  7295. { "To", "t" },
  7296. { "Supported", "k" },
  7297. { "Refer-To", "r" },
  7298. { "Referred-By", "b" },
  7299. { "Allow-Events", "u" },
  7300. { "Event", "o" },
  7301. { "Via", "v" },
  7302. { "Accept-Contact", "a" },
  7303. { "Reject-Contact", "j" },
  7304. { "Request-Disposition", "d" },
  7305. { "Session-Expires", "x" },
  7306. { "Identity", "y" },
  7307. { "Identity-Info", "n" },
  7308. };
  7309. /*! \brief Find compressed SIP alias */
  7310. static const char *find_alias(const char *name, const char *_default)
  7311. {
  7312. int x;
  7313. for (x = 0; x < ARRAY_LEN(aliases); x++) {
  7314. if (!strcasecmp(aliases[x].fullname, name))
  7315. return aliases[x].shortname;
  7316. }
  7317. return _default;
  7318. }
  7319. /*! \brief Find full SIP alias */
  7320. static const char *find_full_alias(const char *name, const char *_default)
  7321. {
  7322. int x;
  7323. if (strlen(name) == 1) {
  7324. /* We have a short header name to convert. */
  7325. for (x = 0; x < ARRAY_LEN(aliases); ++x) {
  7326. if (!strcasecmp(aliases[x].shortname, name))
  7327. return aliases[x].fullname;
  7328. }
  7329. }
  7330. return _default;
  7331. }
  7332. static const char *__get_header(const struct sip_request *req, const char *name, int *start)
  7333. {
  7334. /*
  7335. * Technically you can place arbitrary whitespace both before and after the ':' in
  7336. * a header, although RFC3261 clearly says you shouldn't before, and place just
  7337. * one afterwards. If you shouldn't do it, what absolute idiot decided it was
  7338. * a good idea to say you can do it, and if you can do it, why in the hell would.
  7339. * you say you shouldn't.
  7340. * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
  7341. * and we always allow spaces after that for compatibility.
  7342. */
  7343. const char *sname = find_alias(name, NULL);
  7344. int x, len = strlen(name), slen = (sname ? 1 : 0);
  7345. for (x = *start; x < req->headers; x++) {
  7346. const char *header = REQ_OFFSET_TO_STR(req, header[x]);
  7347. int smatch = 0, match = !strncasecmp(header, name, len);
  7348. if (slen) {
  7349. smatch = !strncasecmp(header, sname, slen);
  7350. }
  7351. if (match || smatch) {
  7352. /* skip name */
  7353. const char *r = header + (match ? len : slen );
  7354. if (sip_cfg.pedanticsipchecking) {
  7355. r = ast_skip_blanks(r);
  7356. }
  7357. if (*r == ':') {
  7358. *start = x+1;
  7359. return ast_skip_blanks(r+1);
  7360. }
  7361. }
  7362. }
  7363. /* Don't return NULL, so sip_get_header is always a valid pointer */
  7364. return "";
  7365. }
  7366. /*! \brief Get header from SIP request
  7367. \return Always return something, so don't check for NULL because it won't happen :-)
  7368. */
  7369. const char *sip_get_header(const struct sip_request *req, const char *name)
  7370. {
  7371. int start = 0;
  7372. return __get_header(req, name, &start);
  7373. }
  7374. AST_THREADSTORAGE(sip_content_buf);
  7375. /*! \brief Get message body content */
  7376. static char *get_content(struct sip_request *req)
  7377. {
  7378. struct ast_str *str;
  7379. int i;
  7380. if (!(str = ast_str_thread_get(&sip_content_buf, 128))) {
  7381. return NULL;
  7382. }
  7383. ast_str_reset(str);
  7384. for (i = 0; i < req->lines; i++) {
  7385. if (ast_str_append(&str, 0, "%s\n", REQ_OFFSET_TO_STR(req, line[i])) < 0) {
  7386. return NULL;
  7387. }
  7388. }
  7389. return ast_str_buffer(str);
  7390. }
  7391. /*! \brief Read RTP from network */
  7392. static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
  7393. {
  7394. /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
  7395. struct ast_frame *f;
  7396. if (!p->rtp) {
  7397. /* We have no RTP allocated for this channel */
  7398. return &ast_null_frame;
  7399. }
  7400. switch(ast_channel_fdno(ast)) {
  7401. case 0:
  7402. f = ast_rtp_instance_read(p->rtp, 0); /* RTP Audio */
  7403. break;
  7404. case 1:
  7405. f = ast_rtp_instance_read(p->rtp, 1); /* RTCP Control Channel */
  7406. break;
  7407. case 2:
  7408. f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
  7409. break;
  7410. case 3:
  7411. f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
  7412. break;
  7413. case 4:
  7414. f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
  7415. if (sipdebug_text) {
  7416. struct ast_str *out = ast_str_create(f->datalen * 4 + 6);
  7417. int i;
  7418. unsigned char* arr = f->data.ptr;
  7419. do {
  7420. if (!out) {
  7421. break;
  7422. }
  7423. for (i = 0; i < f->datalen; i++) {
  7424. ast_str_append(&out, 0, "%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
  7425. }
  7426. ast_str_append(&out, 0, " -> ");
  7427. for (i = 0; i < f->datalen; i++) {
  7428. ast_str_append(&out, 0, "%02X ", (unsigned)arr[i]);
  7429. }
  7430. ast_verb(0, "%s\n", ast_str_buffer(out));
  7431. ast_free(out);
  7432. } while (0);
  7433. }
  7434. break;
  7435. case 5:
  7436. f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
  7437. break;
  7438. default:
  7439. f = &ast_null_frame;
  7440. }
  7441. /* Don't forward RFC2833 if we're not supposed to */
  7442. if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
  7443. (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
  7444. ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
  7445. ast_frfree(f);
  7446. return &ast_null_frame;
  7447. }
  7448. /* We already hold the channel lock */
  7449. if (!p->owner || (f && f->frametype != AST_FRAME_VOICE)) {
  7450. return f;
  7451. }
  7452. if (f && ast_format_cap_iscompatible_format(ast_channel_nativeformats(p->owner), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
  7453. struct ast_format_cap *caps;
  7454. if (ast_format_cap_iscompatible_format(p->jointcaps, f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
  7455. ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
  7456. ast_format_get_name(f->subclass.format), ast_channel_name(p->owner));
  7457. ast_frfree(f);
  7458. return &ast_null_frame;
  7459. }
  7460. ast_debug(1, "Oooh, format changed to %s\n",
  7461. ast_format_get_name(f->subclass.format));
  7462. caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7463. if (caps) {
  7464. ast_format_cap_append_from_cap(caps, ast_channel_nativeformats(p->owner), AST_MEDIA_TYPE_UNKNOWN);
  7465. ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_AUDIO);
  7466. ast_format_cap_append(caps, f->subclass.format, 0);
  7467. ast_channel_nativeformats_set(p->owner, caps);
  7468. ao2_ref(caps, -1);
  7469. }
  7470. ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
  7471. ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
  7472. }
  7473. if (f && p->dsp) {
  7474. f = ast_dsp_process(p->owner, p->dsp, f);
  7475. if (f && f->frametype == AST_FRAME_DTMF) {
  7476. if (f->subclass.integer == 'f') {
  7477. ast_debug(1, "Fax CNG detected on %s\n", ast_channel_name(ast));
  7478. *faxdetect = 1;
  7479. /* If we only needed this DSP for fax detection purposes we can just drop it now */
  7480. if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
  7481. ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
  7482. } else {
  7483. ast_dsp_free(p->dsp);
  7484. p->dsp = NULL;
  7485. }
  7486. } else {
  7487. ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
  7488. }
  7489. }
  7490. }
  7491. return f;
  7492. }
  7493. /*! \brief Read SIP RTP from channel */
  7494. static struct ast_frame *sip_read(struct ast_channel *ast)
  7495. {
  7496. struct ast_frame *fr;
  7497. struct sip_pvt *p = ast_channel_tech_pvt(ast);
  7498. int faxdetected = FALSE;
  7499. sip_pvt_lock(p);
  7500. fr = sip_rtp_read(ast, p, &faxdetected);
  7501. p->lastrtprx = time(NULL);
  7502. /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
  7503. if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
  7504. if (strcmp(ast_channel_exten(ast), "fax")) {
  7505. const char *target_context = S_OR(ast_channel_macrocontext(ast), ast_channel_context(ast));
  7506. /* We need to unlock 'ast' here because
  7507. * ast_exists_extension has the potential to start and
  7508. * stop an autoservice on the channel. Such action is
  7509. * prone to deadlock if the channel is locked.
  7510. */
  7511. sip_pvt_unlock(p);
  7512. ast_channel_unlock(ast);
  7513. if (ast_exists_extension(ast, target_context, "fax", 1,
  7514. S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, NULL))) {
  7515. ast_channel_lock(ast);
  7516. sip_pvt_lock(p);
  7517. ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n", ast_channel_name(ast));
  7518. pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
  7519. if (ast_async_goto(ast, target_context, "fax", 1)) {
  7520. ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
  7521. }
  7522. ast_frfree(fr);
  7523. fr = &ast_null_frame;
  7524. } else {
  7525. ast_channel_lock(ast);
  7526. sip_pvt_lock(p);
  7527. ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
  7528. }
  7529. }
  7530. }
  7531. /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
  7532. if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast_channel_state(ast) != AST_STATE_UP) {
  7533. ast_frfree(fr);
  7534. fr = &ast_null_frame;
  7535. }
  7536. sip_pvt_unlock(p);
  7537. return fr;
  7538. }
  7539. /*! \brief Generate 32 byte random string for callid's etc */
  7540. static char *generate_random_string(char *buf, size_t size)
  7541. {
  7542. long val[4];
  7543. int x;
  7544. for (x=0; x<4; x++)
  7545. val[x] = ast_random();
  7546. snprintf(buf, size, "%08lx%08lx%08lx%08lx", (unsigned long)val[0], (unsigned long)val[1], (unsigned long)val[2], (unsigned long)val[3]);
  7547. return buf;
  7548. }
  7549. static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
  7550. {
  7551. struct ast_str *uri = ast_str_alloca(size);
  7552. ast_str_set(&uri, 0, "%s", pvt->socket.type == AST_TRANSPORT_TLS ? "sips:" : "sip:");
  7553. /* Here would be a great place to generate a UUID, but for now we'll
  7554. * use the handy random string generation function we already have
  7555. */
  7556. ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
  7557. ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
  7558. ast_copy_string(buf, ast_str_buffer(uri), size);
  7559. return buf;
  7560. }
  7561. /*!
  7562. * \brief Build SIP Call-ID value for a non-REGISTER transaction
  7563. *
  7564. * \note The passed in pvt must not be in a dialogs container
  7565. * since this function changes the hash key used by the
  7566. * container.
  7567. */
  7568. static void build_callid_pvt(struct sip_pvt *pvt)
  7569. {
  7570. char buf[33];
  7571. const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
  7572. ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
  7573. }
  7574. /*! \brief Unlink the given object from the container and return TRUE if it was in the container. */
  7575. #define CONTAINER_UNLINK(container, obj, tag) \
  7576. ({ \
  7577. int found = 0; \
  7578. typeof((obj)) __removed_obj; \
  7579. __removed_obj = ao2_t_callback((container), \
  7580. OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag)); \
  7581. if (__removed_obj) { \
  7582. ao2_ref(__removed_obj, -1); \
  7583. found = 1; \
  7584. } \
  7585. found; \
  7586. })
  7587. /*!
  7588. * \internal
  7589. * \brief Safely change the callid of the given SIP dialog.
  7590. *
  7591. * \param pvt SIP private structure to change callid
  7592. * \param callid Specified new callid to use. NULL if generate new callid.
  7593. *
  7594. * \return Nothing
  7595. */
  7596. static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
  7597. {
  7598. int in_dialog_container;
  7599. int in_rtp_container;
  7600. char *oldid = ast_strdupa(pvt->callid);
  7601. ao2_lock(dialogs);
  7602. ao2_lock(dialogs_rtpcheck);
  7603. in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
  7604. "About to change the callid -- remove the old name");
  7605. in_rtp_container = CONTAINER_UNLINK(dialogs_rtpcheck, pvt,
  7606. "About to change the callid -- remove the old name");
  7607. if (callid) {
  7608. ast_string_field_set(pvt, callid, callid);
  7609. } else {
  7610. build_callid_pvt(pvt);
  7611. }
  7612. if (in_dialog_container) {
  7613. ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
  7614. }
  7615. if (in_rtp_container) {
  7616. ao2_t_link(dialogs_rtpcheck, pvt, "New dialog callid -- inserted back into table");
  7617. }
  7618. ao2_unlock(dialogs_rtpcheck);
  7619. ao2_unlock(dialogs);
  7620. if (strcmp(oldid, pvt->callid)) {
  7621. ast_debug(1, "SIP call-id changed from '%s' to '%s'\n", oldid, pvt->callid);
  7622. }
  7623. }
  7624. /*! \brief Build SIP Call-ID value for a REGISTER transaction */
  7625. static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
  7626. {
  7627. char buf[33];
  7628. const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
  7629. ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
  7630. }
  7631. /*! \brief Build SIP From tag value for REGISTER */
  7632. static void build_localtag_registry(struct sip_registry *reg)
  7633. {
  7634. ast_string_field_build(reg, localtag, "as%08lx", (unsigned long)ast_random());
  7635. }
  7636. /*! \brief Make our SIP dialog tag */
  7637. static void make_our_tag(struct sip_pvt *pvt)
  7638. {
  7639. ast_string_field_build(pvt, tag, "as%08lx", (unsigned long)ast_random());
  7640. }
  7641. /*! \brief Allocate Session-Timers struct w/in dialog */
  7642. static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
  7643. {
  7644. struct sip_st_dlg *stp;
  7645. if (p->stimer) {
  7646. ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
  7647. return p->stimer;
  7648. }
  7649. if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
  7650. return NULL;
  7651. p->stimer = stp;
  7652. stp->st_schedid = -1; /* Session-Timers ast_sched scheduler id */
  7653. return p->stimer;
  7654. }
  7655. static void sip_pvt_callid_set(struct sip_pvt *pvt, struct ast_callid *callid)
  7656. {
  7657. if (pvt->logger_callid) {
  7658. ast_callid_unref(pvt->logger_callid);
  7659. }
  7660. ast_callid_ref(callid);
  7661. pvt->logger_callid = callid;
  7662. }
  7663. /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
  7664. * Returns a reference to the object so whoever uses it later must
  7665. * remember to release the reference.
  7666. */
  7667. struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
  7668. int useglobal_nat, const int intended_method, struct sip_request *req, struct ast_callid *logger_callid)
  7669. {
  7670. struct sip_pvt *p;
  7671. if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
  7672. return NULL;
  7673. if (ast_string_field_init(p, 512)) {
  7674. ao2_t_ref(p, -1, "failed to string_field_init, drop p");
  7675. return NULL;
  7676. }
  7677. if (!(p->cc_params = ast_cc_config_params_init())) {
  7678. ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
  7679. return NULL;
  7680. }
  7681. if (logger_callid) {
  7682. sip_pvt_callid_set(p, logger_callid);
  7683. }
  7684. p->caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7685. p->jointcaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7686. p->peercaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7687. p->redircaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7688. p->prefcaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  7689. if (!p->caps|| !p->jointcaps || !p->peercaps || !p->redircaps || !p->prefcaps) {
  7690. ao2_cleanup(p->caps);
  7691. ao2_cleanup(p->jointcaps);
  7692. ao2_cleanup(p->peercaps);
  7693. ao2_cleanup(p->redircaps);
  7694. ao2_cleanup(p->prefcaps);
  7695. ao2_t_ref(p, -1, "Yuck, couldn't allocate format capabilities. Get rid o' p");
  7696. return NULL;
  7697. }
  7698. /* If this dialog is created as a result of a request or response, lets store
  7699. * some information about it in the dialog. */
  7700. if (req) {
  7701. struct sip_via *via;
  7702. const char *cseq = sip_get_header(req, "Cseq");
  7703. uint32_t seqno;
  7704. /* get branch parameter from initial Request that started this dialog */
  7705. via = parse_via(sip_get_header(req, "Via"));
  7706. if (via) {
  7707. /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
  7708. * it is not useful to us to have it */
  7709. if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
  7710. ast_string_field_set(p, initviabranch, via->branch);
  7711. ast_string_field_set(p, initviasentby, via->sent_by);
  7712. }
  7713. free_via(via);
  7714. }
  7715. /* Store initial incoming cseq. An error in sscanf here is ignored. There is no approperiate
  7716. * except not storing the number. CSeq validation must take place before dialog creation in find_call */
  7717. if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
  7718. p->init_icseq = seqno;
  7719. }
  7720. /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
  7721. set_socket_transport(&p->socket, req->socket.type);
  7722. } else {
  7723. set_socket_transport(&p->socket, AST_TRANSPORT_UDP);
  7724. }
  7725. p->socket.fd = -1;
  7726. p->method = intended_method;
  7727. p->initid = -1;
  7728. p->waitid = -1;
  7729. p->reinviteid = -1;
  7730. p->autokillid = -1;
  7731. p->request_queue_sched_id = -1;
  7732. p->provisional_keepalive_sched_id = -1;
  7733. p->t38id = -1;
  7734. p->subscribed = NONE;
  7735. p->stateid = -1;
  7736. p->sessionversion_remote = -1;
  7737. p->session_modify = TRUE;
  7738. p->stimer = NULL;
  7739. ast_copy_string(p->zone, default_zone, sizeof(p->zone));
  7740. p->maxforwards = sip_cfg.default_max_forwards;
  7741. if (intended_method != SIP_OPTIONS) { /* Peerpoke has it's own system */
  7742. p->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
  7743. p->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
  7744. }
  7745. if (!addr) {
  7746. p->ourip = internip;
  7747. } else {
  7748. ast_sockaddr_copy(&p->sa, addr);
  7749. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  7750. }
  7751. /* Copy global flags to this PVT at setup. */
  7752. ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
  7753. ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  7754. ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  7755. p->do_history = recordhistory;
  7756. p->branch = ast_random();
  7757. make_our_tag(p);
  7758. p->ocseq = INITIAL_CSEQ;
  7759. p->allowed_methods = UINT_MAX;
  7760. if (sip_methods[intended_method].need_rtp) {
  7761. p->maxcallbitrate = default_maxcallbitrate;
  7762. p->autoframing = global_autoframing;
  7763. }
  7764. if (useglobal_nat && addr) {
  7765. /* Setup NAT structure according to global settings if we have an address */
  7766. ast_sockaddr_copy(&p->recv, addr);
  7767. check_via(p, req);
  7768. do_setnat(p);
  7769. }
  7770. if (p->method != SIP_REGISTER) {
  7771. ast_string_field_set(p, fromdomain, default_fromdomain);
  7772. p->fromdomainport = default_fromdomainport;
  7773. }
  7774. build_via(p);
  7775. if (!callid)
  7776. build_callid_pvt(p);
  7777. else
  7778. ast_string_field_set(p, callid, callid);
  7779. /* Assign default music on hold class */
  7780. ast_string_field_set(p, mohinterpret, default_mohinterpret);
  7781. ast_string_field_set(p, mohsuggest, default_mohsuggest);
  7782. ast_format_cap_append_from_cap(p->caps, sip_cfg.caps, AST_MEDIA_TYPE_UNKNOWN);
  7783. p->allowtransfer = sip_cfg.allowtransfer;
  7784. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
  7785. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  7786. p->noncodeccapability |= AST_RTP_DTMF;
  7787. }
  7788. ast_string_field_set(p, context, sip_cfg.default_context);
  7789. ast_string_field_set(p, parkinglot, default_parkinglot);
  7790. ast_string_field_set(p, engine, default_engine);
  7791. AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
  7792. AST_LIST_HEAD_INIT_NOLOCK(&p->offered_media);
  7793. /* Add to active dialog list */
  7794. ao2_t_link(dialogs, p, "link pvt into dialogs table");
  7795. 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");
  7796. return p;
  7797. }
  7798. /*!
  7799. * \brief Process the Via header according to RFC 3261 section 18.2.2.
  7800. * \param p a sip_pvt structure that will be modified according to the received
  7801. * header
  7802. * \param req a sip request with a Via header to process
  7803. *
  7804. * This function will update the destination of the response according to the
  7805. * Via header in the request and RFC 3261 section 18.2.2. We do not have a
  7806. * transport layer so we ignore certain values like the 'received' param (we
  7807. * set the destination address to the addres the request came from in the
  7808. * respprep() function).
  7809. *
  7810. * \retval -1 error
  7811. * \retval 0 success
  7812. */
  7813. static int process_via(struct sip_pvt *p, const struct sip_request *req)
  7814. {
  7815. struct sip_via *via = parse_via(sip_get_header(req, "Via"));
  7816. if (!via) {
  7817. ast_log(LOG_ERROR, "error processing via header\n");
  7818. return -1;
  7819. }
  7820. if (via->maddr) {
  7821. if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
  7822. ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
  7823. ast_log(LOG_ERROR, "error processing via header\n");
  7824. free_via(via);
  7825. return -1;
  7826. }
  7827. if (ast_sockaddr_is_ipv4_multicast(&p->sa)) {
  7828. setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
  7829. }
  7830. }
  7831. ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
  7832. free_via(via);
  7833. return 0;
  7834. }
  7835. /* \brief arguments used for Request/Response to matching */
  7836. struct match_req_args {
  7837. int method;
  7838. const char *callid;
  7839. const char *totag;
  7840. const char *fromtag;
  7841. uint32_t seqno;
  7842. /* Set if this method is a Response */
  7843. int respid;
  7844. /* Set if the method is a Request */
  7845. const char *ruri;
  7846. const char *viabranch;
  7847. const char *viasentby;
  7848. /* Set this if the Authentication header is present in the Request. */
  7849. int authentication_present;
  7850. };
  7851. enum match_req_res {
  7852. SIP_REQ_MATCH,
  7853. SIP_REQ_NOT_MATCH,
  7854. SIP_REQ_LOOP_DETECTED, /* multiple incoming requests with same call-id but different branch parameters have been detected */
  7855. SIP_REQ_FORKED, /* An outgoing request has been forked as result of receiving two differing 200ok responses. */
  7856. };
  7857. /*
  7858. * \brief Match a incoming Request/Response to a dialog
  7859. *
  7860. * \retval enum match_req_res indicating if the dialog matches the arg
  7861. */
  7862. static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
  7863. {
  7864. const char *init_ruri = NULL;
  7865. if (sip_pvt_ptr->initreq.headers) {
  7866. init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlpart2);
  7867. }
  7868. /*
  7869. * Match Tags and call-id to Dialog
  7870. */
  7871. if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
  7872. /* call-id does not match. */
  7873. return SIP_REQ_NOT_MATCH;
  7874. }
  7875. if (arg->method == SIP_RESPONSE) {
  7876. /* Verify fromtag of response matches the tag we gave them. */
  7877. if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
  7878. /* fromtag from response does not match our tag */
  7879. return SIP_REQ_NOT_MATCH;
  7880. }
  7881. /* Verify totag if we have one stored for this dialog, but never be strict about this for
  7882. * a response until the dialog is established */
  7883. if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  7884. if (ast_strlen_zero(arg->totag)) {
  7885. /* missing totag when they already gave us one earlier */
  7886. return SIP_REQ_NOT_MATCH;
  7887. }
  7888. /* compare the totag of response with the tag we have stored for them */
  7889. if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
  7890. /* totag did not match what we had stored for them. */
  7891. char invite_branch[32] = { 0, };
  7892. if (sip_pvt_ptr->invite_branch) {
  7893. snprintf(invite_branch, sizeof(invite_branch), "z9hG4bK%08x", (unsigned)sip_pvt_ptr->invite_branch);
  7894. }
  7895. /* Forked Request Detection
  7896. *
  7897. * If this is a 200ok response and the totags do not match, this
  7898. * might be a forked response to an outgoing Request. Detection of
  7899. * a forked response must meet the criteria below.
  7900. *
  7901. * 1. must be a 2xx Response
  7902. * 2. call-d equal to call-id of Request. this is done earlier
  7903. * 3. from-tag equal to from-tag of Request. this is done earlier
  7904. * 4. branch parameter equal to branch of inital Request
  7905. * 5. to-tag _NOT_ equal to previous 2xx response that already established the dialog.
  7906. */
  7907. if ((arg->respid == 200) &&
  7908. !ast_strlen_zero(invite_branch) &&
  7909. !ast_strlen_zero(arg->viabranch) &&
  7910. !strcmp(invite_branch, arg->viabranch)) {
  7911. return SIP_REQ_FORKED;
  7912. }
  7913. /* The totag did not match the one we had stored, and this is not a Forked Request. */
  7914. return SIP_REQ_NOT_MATCH;
  7915. }
  7916. }
  7917. } else {
  7918. /* Verify the fromtag of Request matches the tag they provided earlier.
  7919. * If this is a Request with authentication credentials, forget their old
  7920. * tag as it is not valid after the 401 or 407 response. */
  7921. if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
  7922. /* their tag does not match the one was have stored for them */
  7923. return SIP_REQ_NOT_MATCH;
  7924. }
  7925. /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
  7926. if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
  7927. /* totag from Request does not match our tag */
  7928. return SIP_REQ_NOT_MATCH;
  7929. }
  7930. }
  7931. /*
  7932. * Compare incoming request against initial transaction.
  7933. *
  7934. * This is a best effort attempt at distinguishing forked requests from
  7935. * our initial transaction. If all the elements are NOT in place to evaluate
  7936. * this, this block is ignored and the dialog match is made regardless.
  7937. * Once the totag is established after the dialog is confirmed, this is not necessary.
  7938. *
  7939. * CRITERIA required for initial transaction matching.
  7940. *
  7941. * 1. Is a Request
  7942. * 2. Callid and theirtag match (this is done in the dialog matching block)
  7943. * 3. totag is NOT present
  7944. * 4. CSeq matchs our initial transaction's cseq number
  7945. * 5. pvt has init via branch parameter stored
  7946. */
  7947. if ((arg->method != SIP_RESPONSE) && /* must be a Request */
  7948. ast_strlen_zero(arg->totag) && /* must not have a totag */
  7949. (sip_pvt_ptr->init_icseq == arg->seqno) && /* the cseq must be the same as this dialogs initial cseq */
  7950. !ast_strlen_zero(sip_pvt_ptr->initviabranch) && /* The dialog must have started with a RFC3261 compliant branch tag */
  7951. init_ruri) { /* the dialog must have an initial request uri associated with it */
  7952. /* This Request matches all the criteria required for Loop/Merge detection.
  7953. * Now we must go down the path of comparing VIA's and RURIs. */
  7954. if (ast_strlen_zero(arg->viabranch) ||
  7955. strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
  7956. ast_strlen_zero(arg->viasentby) ||
  7957. strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
  7958. /* At this point, this request does not match this Dialog.*/
  7959. /* if methods are different this is just a mismatch */
  7960. if ((sip_pvt_ptr->method != arg->method)) {
  7961. return SIP_REQ_NOT_MATCH;
  7962. }
  7963. /* If RUIs are different, this is a forked request to a separate URI.
  7964. * Returning a mismatch allows this Request to be processed separately. */
  7965. if (sip_uri_cmp(init_ruri, arg->ruri)) {
  7966. /* not a match, request uris are different */
  7967. return SIP_REQ_NOT_MATCH;
  7968. }
  7969. /* Loop/Merge Detected
  7970. *
  7971. * ---Current Matches to Initial Request---
  7972. * request uri
  7973. * Call-id
  7974. * their-tag
  7975. * no totag present
  7976. * method
  7977. * cseq
  7978. *
  7979. * --- Does not Match Initial Request ---
  7980. * Top Via
  7981. *
  7982. * Without the same Via, this can not match our initial transaction for this dialog,
  7983. * but given that this Request matches everything else associated with that initial
  7984. * Request this is most certainly a Forked request in which we have already received
  7985. * part of the fork.
  7986. */
  7987. return SIP_REQ_LOOP_DETECTED;
  7988. }
  7989. } /* end of Request Via check */
  7990. /* Match Authentication Request.
  7991. *
  7992. * A Request with an Authentication header must come back with the
  7993. * same Request URI. Otherwise it is not a match.
  7994. */
  7995. if ((arg->method != SIP_RESPONSE) && /* Must be a Request type to even begin checking this */
  7996. ast_strlen_zero(arg->totag) && /* no totag is present to match */
  7997. arg->authentication_present && /* Authentication header is present in Request */
  7998. sip_uri_cmp(init_ruri, arg->ruri)) { /* Compare the Request URI of both the last Request and this new one */
  7999. /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
  8000. return SIP_REQ_NOT_MATCH;
  8001. }
  8002. return SIP_REQ_MATCH;
  8003. }
  8004. /*! \brief This function creates a dialog to handle a forked request. This dialog
  8005. * exists only to properly terminiate the the forked request immediately.
  8006. */
  8007. static void forked_invite_init(struct sip_request *req, const char *new_theirtag, struct sip_pvt *original, struct ast_sockaddr *addr)
  8008. {
  8009. struct sip_pvt *p;
  8010. const char *callid;
  8011. struct ast_callid *logger_callid;
  8012. sip_pvt_lock(original);
  8013. callid = ast_strdupa(original->callid);
  8014. logger_callid = original->logger_callid;
  8015. if (logger_callid) {
  8016. ast_callid_ref(logger_callid);
  8017. }
  8018. sip_pvt_unlock(original);
  8019. p = sip_alloc(callid, addr, 1, SIP_INVITE, req, logger_callid);
  8020. if (logger_callid) {
  8021. ast_callid_unref(logger_callid);
  8022. }
  8023. if (!p) {
  8024. return; /* alloc error */
  8025. }
  8026. /* Lock p and original private structures. */
  8027. sip_pvt_lock(p);
  8028. while (sip_pvt_trylock(original)) {
  8029. /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
  8030. sip_pvt_unlock(p);
  8031. sched_yield();
  8032. sip_pvt_lock(p);
  8033. }
  8034. p->invitestate = INV_TERMINATED;
  8035. p->ocseq = original->ocseq;
  8036. p->branch = original->branch;
  8037. memcpy(&p->flags, &original->flags, sizeof(p->flags));
  8038. copy_request(&p->initreq, &original->initreq);
  8039. ast_string_field_set(p, theirtag, new_theirtag);
  8040. ast_string_field_set(p, tag, original->tag);
  8041. ast_string_field_set(p, uri, original->uri);
  8042. ast_string_field_set(p, our_contact, original->our_contact);
  8043. ast_string_field_set(p, fullcontact, original->fullcontact);
  8044. sip_pvt_unlock(original);
  8045. parse_ok_contact(p, req);
  8046. build_route(p, req, 1, 0);
  8047. transmit_request(p, SIP_ACK, p->ocseq, XMIT_UNRELIABLE, TRUE);
  8048. transmit_request(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
  8049. pvt_set_needdestroy(p, "forked request"); /* this dialog will terminate once the BYE is responed to or times out. */
  8050. sip_pvt_unlock(p);
  8051. dialog_unref(p, "setup forked invite termination");
  8052. }
  8053. /*! \internal
  8054. *
  8055. * \brief Locks both pvt and pvt owner if owner is present.
  8056. *
  8057. * \note This function gives a ref to pvt->owner if it is present and locked.
  8058. * This reference must be decremented after pvt->owner is unlocked.
  8059. *
  8060. * \note This function will never give you up,
  8061. * \note This function will never let you down.
  8062. * \note This function will run around and desert you.
  8063. *
  8064. * \pre pvt is not locked
  8065. * \post pvt is locked
  8066. * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
  8067. *
  8068. * \returns a pointer to the locked and reffed pvt->owner channel if it exists.
  8069. */
  8070. static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
  8071. {
  8072. struct ast_channel *chan;
  8073. /* Locking is simple when it is done right. If you see a deadlock resulting
  8074. * in this function, it is not this function's fault, Your problem exists elsewhere.
  8075. * This function is perfect... seriously. */
  8076. for (;;) {
  8077. /* First, get the channel and grab a reference to it */
  8078. sip_pvt_lock(pvt);
  8079. chan = pvt->owner;
  8080. if (chan) {
  8081. /* The channel can not go away while we hold the pvt lock.
  8082. * Give the channel a ref so it will not go away after we let
  8083. * the pvt lock go. */
  8084. ast_channel_ref(chan);
  8085. } else {
  8086. /* no channel, return pvt locked */
  8087. return NULL;
  8088. }
  8089. /* We had to hold the pvt lock while getting a ref to the owner channel
  8090. * but now we have to let this lock go in order to preserve proper
  8091. * locking order when grabbing the channel lock */
  8092. sip_pvt_unlock(pvt);
  8093. /* Look, no deadlock avoidance, hooray! */
  8094. ast_channel_lock(chan);
  8095. sip_pvt_lock(pvt);
  8096. if (pvt->owner == chan) {
  8097. /* done */
  8098. break;
  8099. }
  8100. /* If the owner changed while everything was unlocked, no problem,
  8101. * just start over and everthing will work. This is rare, do not be
  8102. * confused by this loop and think this it is an expensive operation.
  8103. * The majority of the calls to this function will never involve multiple
  8104. * executions of this loop. */
  8105. ast_channel_unlock(chan);
  8106. ast_channel_unref(chan);
  8107. sip_pvt_unlock(pvt);
  8108. }
  8109. /* If owner exists, it is locked and reffed */
  8110. return pvt->owner;
  8111. }
  8112. /*! \brief Set the owning channel on the \ref sip_pvt object */
  8113. static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan)
  8114. {
  8115. p->owner = chan;
  8116. if (p->rtp) {
  8117. ast_rtp_instance_set_channel_id(p->rtp, p->owner ? ast_channel_uniqueid(p->owner) : "");
  8118. }
  8119. if (p->vrtp) {
  8120. ast_rtp_instance_set_channel_id(p->vrtp, p->owner ? ast_channel_uniqueid(p->owner) : "");
  8121. }
  8122. if (p->trtp) {
  8123. ast_rtp_instance_set_channel_id(p->trtp, p->owner ? ast_channel_uniqueid(p->owner) : "");
  8124. }
  8125. }
  8126. /*! \brief find or create a dialog structure for an incoming SIP message.
  8127. * Connect incoming SIP message to current dialog or create new dialog structure
  8128. * Returns a reference to the sip_pvt object, remember to give it back once done.
  8129. * Called by handle_request_do
  8130. */
  8131. static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
  8132. {
  8133. char totag[128];
  8134. char fromtag[128];
  8135. const char *callid = sip_get_header(req, "Call-ID");
  8136. const char *from = sip_get_header(req, "From");
  8137. const char *to = sip_get_header(req, "To");
  8138. const char *cseq = sip_get_header(req, "Cseq");
  8139. struct sip_pvt *sip_pvt_ptr;
  8140. uint32_t seqno;
  8141. /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
  8142. /* sip_get_header always returns non-NULL so we must use ast_strlen_zero() */
  8143. if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
  8144. ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
  8145. (sscanf(cseq, "%30u", &seqno) != 1)) {
  8146. /* RFC 3261 section 24.4.1. Send a 400 Bad Request if the request is malformed. */
  8147. if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
  8148. transmit_response_using_temp(callid, addr, 1, intended_method,
  8149. req, "400 Bad Request");
  8150. }
  8151. return NULL; /* Invalid packet */
  8152. }
  8153. if (sip_cfg.pedanticsipchecking) {
  8154. /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
  8155. we need more to identify a branch - so we have to check branch, from
  8156. and to tags to identify a call leg.
  8157. For Asterisk to behave correctly, you need to turn on pedanticsipchecking
  8158. in sip.conf
  8159. */
  8160. if (gettag(req, "To", totag, sizeof(totag)))
  8161. req->has_to_tag = 1; /* Used in handle_request/response */
  8162. gettag(req, "From", fromtag, sizeof(fromtag));
  8163. 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);
  8164. /* All messages must always have From: tag */
  8165. if (ast_strlen_zero(fromtag)) {
  8166. ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
  8167. return NULL;
  8168. }
  8169. /* reject requests that must always have a To: tag */
  8170. if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
  8171. if (req->method != SIP_ACK) {
  8172. transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
  8173. }
  8174. ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
  8175. return NULL;
  8176. }
  8177. }
  8178. if (!sip_cfg.pedanticsipchecking) {
  8179. struct sip_pvt tmp_dialog = {
  8180. .callid = callid,
  8181. };
  8182. sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
  8183. if (sip_pvt_ptr) { /* well, if we don't find it-- what IS in there? */
  8184. /* Found the call */
  8185. return sip_pvt_ptr;
  8186. }
  8187. } else { /* in pedantic mode! -- do the fancy search */
  8188. struct sip_pvt tmp_dialog = {
  8189. .callid = callid,
  8190. };
  8191. /* if a Outbound forked Request is detected, this pvt will point
  8192. * to the dialog the Request is forking off of. */
  8193. struct sip_pvt *fork_pvt = NULL;
  8194. struct match_req_args args = { 0, };
  8195. int found;
  8196. struct ao2_iterator *iterator = ao2_t_callback(dialogs,
  8197. OBJ_POINTER | OBJ_MULTIPLE,
  8198. dialog_find_multiple,
  8199. &tmp_dialog,
  8200. "pedantic ao2_find in dialogs");
  8201. struct sip_via *via = NULL;
  8202. args.method = req->method;
  8203. args.callid = NULL; /* we already matched this. */
  8204. args.totag = totag;
  8205. args.fromtag = fromtag;
  8206. args.seqno = seqno;
  8207. /* get via header information. */
  8208. args.ruri = REQ_OFFSET_TO_STR(req, rlpart2);
  8209. via = parse_via(sip_get_header(req, "Via"));
  8210. if (via) {
  8211. args.viasentby = via->sent_by;
  8212. args.viabranch = via->branch;
  8213. }
  8214. /* determine if this is a Request with authentication credentials. */
  8215. if (!ast_strlen_zero(sip_get_header(req, "Authorization")) ||
  8216. !ast_strlen_zero(sip_get_header(req, "Proxy-Authorization"))) {
  8217. args.authentication_present = 1;
  8218. }
  8219. /* if it is a response, get the response code */
  8220. if (req->method == SIP_RESPONSE) {
  8221. const char* e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
  8222. int respid;
  8223. if (!ast_strlen_zero(e) && (sscanf(e, "%30d", &respid) == 1)) {
  8224. args.respid = respid;
  8225. }
  8226. }
  8227. /* Iterate a list of dialogs already matched by Call-id */
  8228. while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
  8229. sip_pvt_lock(sip_pvt_ptr);
  8230. found = match_req_to_dialog(sip_pvt_ptr, &args);
  8231. sip_pvt_unlock(sip_pvt_ptr);
  8232. switch (found) {
  8233. case SIP_REQ_MATCH:
  8234. ao2_iterator_destroy(iterator);
  8235. dialog_unref(fork_pvt, "unref fork_pvt");
  8236. free_via(via);
  8237. return sip_pvt_ptr; /* return pvt with ref */
  8238. case SIP_REQ_LOOP_DETECTED:
  8239. /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
  8240. * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
  8241. transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
  8242. dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
  8243. ao2_iterator_destroy(iterator);
  8244. dialog_unref(fork_pvt, "unref fork_pvt");
  8245. free_via(via);
  8246. return NULL;
  8247. case SIP_REQ_FORKED:
  8248. dialog_unref(fork_pvt, "throwing way pvt to fork off of.");
  8249. fork_pvt = dialog_ref(sip_pvt_ptr, "this pvt has a forked request, save this off to copy information into new dialog\n");
  8250. /* fall through */
  8251. case SIP_REQ_NOT_MATCH:
  8252. default:
  8253. dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
  8254. break;
  8255. }
  8256. }
  8257. if (iterator) {
  8258. ao2_iterator_destroy(iterator);
  8259. }
  8260. /* Handle any possible forked requests. This must be done only after transaction matching is complete. */
  8261. if (fork_pvt) {
  8262. /* XXX right now we only support handling forked INVITE Requests. Any other
  8263. * forked request type must be added here. */
  8264. if (fork_pvt->method == SIP_INVITE) {
  8265. forked_invite_init(req, args.totag, fork_pvt, addr);
  8266. dialog_unref(fork_pvt, "throwing way old forked pvt");
  8267. free_via(via);
  8268. return NULL;
  8269. }
  8270. fork_pvt = dialog_unref(fork_pvt, "throwing way pvt to fork off of");
  8271. }
  8272. free_via(via);
  8273. } /* end of pedantic mode Request/Reponse to Dialog matching */
  8274. /* See if the method is capable of creating a dialog */
  8275. if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
  8276. struct sip_pvt *p = NULL;
  8277. struct ast_callid *logger_callid = NULL;
  8278. if (intended_method == SIP_INVITE) {
  8279. logger_callid = ast_create_callid();
  8280. }
  8281. /* Ok, time to create a new SIP dialog object, a pvt */
  8282. if (!(p = sip_alloc(callid, addr, 1, intended_method, req, logger_callid))) {
  8283. /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
  8284. getting a dialog from sip_alloc.
  8285. Without a dialog we can't retransmit and handle ACKs and all that, but at least
  8286. send an error message.
  8287. Sorry, we apologize for the inconvienience
  8288. */
  8289. transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
  8290. ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
  8291. }
  8292. /* If we created an ast_callid for an invite, we need to free it now. */
  8293. if (logger_callid) {
  8294. ast_callid_unref(logger_callid);
  8295. }
  8296. return p; /* can be NULL */
  8297. } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
  8298. /* A method we do not support, let's take it on the volley */
  8299. transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
  8300. ast_debug(2, "Got a request with unsupported SIP method.\n");
  8301. } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
  8302. /* This is a request outside of a dialog that we don't know about */
  8303. transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
  8304. ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
  8305. }
  8306. /* We do not respond to responses for dialogs that we don't know about, we just drop
  8307. the session quickly */
  8308. if (intended_method == SIP_RESPONSE)
  8309. ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
  8310. return NULL;
  8311. }
  8312. /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
  8313. static int sip_register(const char *value, int lineno)
  8314. {
  8315. struct sip_registry *reg;
  8316. reg = ao2_t_find(registry_list, value, OBJ_SEARCH_KEY, "check for existing registry");
  8317. if (reg) {
  8318. ao2_t_ref(reg, -1, "throw away found registry");
  8319. return 0;
  8320. }
  8321. if (!(reg = ao2_t_alloc(sizeof(*reg), sip_registry_destroy, "allocate a registry struct"))) {
  8322. ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
  8323. return -1;
  8324. }
  8325. if (ast_string_field_init(reg, 256)) {
  8326. ao2_t_ref(reg, -1, "failed to string_field_init, drop reg");
  8327. return -1;
  8328. }
  8329. ast_string_field_set(reg, configvalue, value);
  8330. if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
  8331. ao2_t_ref(reg, -1, "failure to parse, unref the reg pointer");
  8332. return -1;
  8333. }
  8334. /* set default expiry if necessary */
  8335. if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
  8336. reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
  8337. }
  8338. ao2_t_link(registry_list, reg, "link reg to registry_list");
  8339. ao2_t_ref(reg, -1, "unref the reg pointer");
  8340. return 0;
  8341. }
  8342. /*! \brief Parse mwi=> line in sip.conf and add to list */
  8343. static int sip_subscribe_mwi(const char *value, int lineno)
  8344. {
  8345. struct sip_subscription_mwi *mwi;
  8346. int portnum = 0;
  8347. enum ast_transport transport = AST_TRANSPORT_UDP;
  8348. char buf[256] = "";
  8349. char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
  8350. if (!value) {
  8351. return -1;
  8352. }
  8353. ast_copy_string(buf, value, sizeof(buf));
  8354. username = buf;
  8355. if ((hostname = strrchr(buf, '@'))) {
  8356. *hostname++ = '\0';
  8357. } else {
  8358. return -1;
  8359. }
  8360. if ((secret = strchr(username, ':'))) {
  8361. *secret++ = '\0';
  8362. if ((authuser = strchr(secret, ':'))) {
  8363. *authuser++ = '\0';
  8364. }
  8365. }
  8366. if ((mailbox = strchr(hostname, '/'))) {
  8367. *mailbox++ = '\0';
  8368. }
  8369. if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
  8370. ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
  8371. return -1;
  8372. }
  8373. if ((porta = strchr(hostname, ':'))) {
  8374. *porta++ = '\0';
  8375. if (!(portnum = atoi(porta))) {
  8376. ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
  8377. return -1;
  8378. }
  8379. }
  8380. if (!(mwi = ao2_t_alloc(sizeof(*mwi), sip_subscribe_mwi_destroy, "allocate an mwi struct"))) {
  8381. return -1;
  8382. }
  8383. if (ast_string_field_init(mwi, 256)) {
  8384. ao2_t_ref(mwi, -1, "failed to string_field_init, drop mwi");
  8385. return -1;
  8386. }
  8387. ast_string_field_set(mwi, username, username);
  8388. if (secret) {
  8389. ast_string_field_set(mwi, secret, secret);
  8390. }
  8391. if (authuser) {
  8392. ast_string_field_set(mwi, authuser, authuser);
  8393. }
  8394. ast_string_field_set(mwi, hostname, hostname);
  8395. ast_string_field_set(mwi, mailbox, mailbox);
  8396. mwi->resub = -1;
  8397. mwi->portno = portnum;
  8398. mwi->transport = transport;
  8399. ao2_t_link(subscription_mwi_list, mwi, "link new mwi object");
  8400. ao2_t_ref(mwi, -1, "unref to match ao2_t_alloc");
  8401. return 0;
  8402. }
  8403. static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
  8404. {
  8405. (*allowed_methods) |= (1 << method);
  8406. }
  8407. static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
  8408. {
  8409. (*allowed_methods) &= ~(1 << method);
  8410. }
  8411. /*! \brief Check if method is allowed for a device or a dialog */
  8412. static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
  8413. {
  8414. return ((*allowed_methods) >> method) & 1;
  8415. }
  8416. static void mark_parsed_methods(unsigned int *methods, char *methods_str)
  8417. {
  8418. char *method;
  8419. for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
  8420. int id = find_sip_method(ast_skip_blanks(method));
  8421. if (id == SIP_UNKNOWN) {
  8422. continue;
  8423. }
  8424. mark_method_allowed(methods, id);
  8425. }
  8426. }
  8427. /*!
  8428. * \brief parse the Allow header to see what methods the endpoint we
  8429. * are communicating with allows.
  8430. *
  8431. * We parse the allow header on incoming Registrations and save the
  8432. * result to the SIP peer that is registering. When the registration
  8433. * expires, we clear what we know about the peer's allowed methods.
  8434. * When the peer re-registers, we once again parse to see if the
  8435. * list of allowed methods has changed.
  8436. *
  8437. * For peers that do not register, we parse the first message we receive
  8438. * during a call to see what is allowed, and save the information
  8439. * for the duration of the call.
  8440. * \param req The SIP request we are parsing
  8441. * \retval The methods allowed
  8442. */
  8443. static unsigned int parse_allowed_methods(struct sip_request *req)
  8444. {
  8445. char *allow = ast_strdupa(sip_get_header(req, "Allow"));
  8446. unsigned int allowed_methods = SIP_UNKNOWN;
  8447. if (ast_strlen_zero(allow)) {
  8448. /* I have witnessed that REGISTER requests from Polycom phones do not
  8449. * place the phone's allowed methods in an Allow header. Instead, they place the
  8450. * allowed methods in a methods= parameter in the Contact header.
  8451. */
  8452. char *contact = ast_strdupa(sip_get_header(req, "Contact"));
  8453. char *methods = strstr(contact, ";methods=");
  8454. if (ast_strlen_zero(methods)) {
  8455. /* RFC 3261 states:
  8456. *
  8457. * "The absence of an Allow header field MUST NOT be
  8458. * interpreted to mean that the UA sending the message supports no
  8459. * methods. Rather, it implies that the UA is not providing any
  8460. * information on what methods it supports."
  8461. *
  8462. * For simplicity, we'll assume that the peer allows all known
  8463. * SIP methods if they have no Allow header. We can then clear out the necessary
  8464. * bits if the peer lets us know that we have sent an unsupported method.
  8465. */
  8466. return UINT_MAX;
  8467. }
  8468. allow = ast_strip_quoted(methods + 9, "\"", "\"");
  8469. }
  8470. mark_parsed_methods(&allowed_methods, allow);
  8471. return allowed_methods;
  8472. }
  8473. /*! A wrapper for parse_allowed_methods geared toward sip_pvts
  8474. *
  8475. * This function, in addition to setting the allowed methods for a sip_pvt
  8476. * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
  8477. *
  8478. * \param pvt The sip_pvt we are setting the allowed_methods for
  8479. * \param req The request which we are parsing
  8480. * \retval The methods alloweded by the sip_pvt
  8481. */
  8482. static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
  8483. {
  8484. pvt->allowed_methods = parse_allowed_methods(req);
  8485. if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
  8486. mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
  8487. }
  8488. pvt->allowed_methods &= ~(pvt->disallowed_methods);
  8489. return pvt->allowed_methods;
  8490. }
  8491. /*! \brief Parse multiline SIP headers into one header
  8492. This is enabled if pedanticsipchecking is enabled */
  8493. static void lws2sws(struct ast_str *data)
  8494. {
  8495. char *msgbuf = data->str;
  8496. int len = ast_str_strlen(data);
  8497. int h = 0, t = 0;
  8498. int lws = 0;
  8499. for (; h < len;) {
  8500. /* Eliminate all CRs */
  8501. if (msgbuf[h] == '\r') {
  8502. h++;
  8503. continue;
  8504. }
  8505. /* Check for end-of-line */
  8506. if (msgbuf[h] == '\n') {
  8507. /* Check for end-of-message */
  8508. if (h + 1 == len)
  8509. break;
  8510. /* Check for a continuation line */
  8511. if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
  8512. /* Merge continuation line */
  8513. h++;
  8514. continue;
  8515. }
  8516. /* Propagate LF and start new line */
  8517. msgbuf[t++] = msgbuf[h++];
  8518. lws = 0;
  8519. continue;
  8520. }
  8521. if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
  8522. if (lws) {
  8523. h++;
  8524. continue;
  8525. }
  8526. msgbuf[t++] = msgbuf[h++];
  8527. lws = 1;
  8528. continue;
  8529. }
  8530. msgbuf[t++] = msgbuf[h++];
  8531. if (lws)
  8532. lws = 0;
  8533. }
  8534. msgbuf[t] = '\0';
  8535. data->used = t;
  8536. }
  8537. /*! \brief Parse a SIP message
  8538. \note this function is used both on incoming and outgoing packets
  8539. */
  8540. static int parse_request(struct sip_request *req)
  8541. {
  8542. char *c = req->data->str;
  8543. ptrdiff_t *dst = req->header;
  8544. int i = 0, lim = SIP_MAX_HEADERS - 1;
  8545. unsigned int skipping_headers = 0;
  8546. ptrdiff_t current_header_offset = 0;
  8547. char *previous_header = "";
  8548. req->header[0] = 0;
  8549. req->headers = -1; /* mark that we are working on the header */
  8550. for (; *c; c++) {
  8551. if (*c == '\r') { /* remove \r */
  8552. *c = '\0';
  8553. } else if (*c == '\n') { /* end of this line */
  8554. *c = '\0';
  8555. current_header_offset = (c + 1) - ast_str_buffer(req->data);
  8556. previous_header = ast_str_buffer(req->data) + dst[i];
  8557. if (skipping_headers) {
  8558. /* check to see if this line is blank; if so, turn off
  8559. the skipping flag, so the next line will be processed
  8560. as a body line */
  8561. if (ast_strlen_zero(previous_header)) {
  8562. skipping_headers = 0;
  8563. }
  8564. dst[i] = current_header_offset; /* record start of next line */
  8565. continue;
  8566. }
  8567. if (sipdebug) {
  8568. ast_debug(4, "%7s %2d [%3d]: %s\n",
  8569. req->headers < 0 ? "Header" : "Body",
  8570. i, (int) strlen(previous_header), previous_header);
  8571. }
  8572. if (ast_strlen_zero(previous_header) && req->headers < 0) {
  8573. req->headers = i; /* record number of header lines */
  8574. dst = req->line; /* start working on the body */
  8575. i = 0;
  8576. lim = SIP_MAX_LINES - 1;
  8577. } else { /* move to next line, check for overflows */
  8578. if (i++ == lim) {
  8579. /* if we're processing headers, then skip any remaining
  8580. headers and move on to processing the body, otherwise
  8581. we're done */
  8582. if (req->headers != -1) {
  8583. break;
  8584. } else {
  8585. req->headers = i;
  8586. dst = req->line;
  8587. i = 0;
  8588. lim = SIP_MAX_LINES - 1;
  8589. skipping_headers = 1;
  8590. }
  8591. }
  8592. }
  8593. dst[i] = current_header_offset; /* record start of next line */
  8594. }
  8595. }
  8596. /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
  8597. but since some devices send without, we'll be generous in what we accept. However,
  8598. if we've already reached the maximum number of lines for portion of the message
  8599. we were parsing, we can't accept any more, so just ignore it.
  8600. */
  8601. previous_header = ast_str_buffer(req->data) + dst[i];
  8602. if ((i < lim) && !ast_strlen_zero(previous_header)) {
  8603. if (sipdebug) {
  8604. ast_debug(4, "%7s %2d [%3d]: %s\n",
  8605. req->headers < 0 ? "Header" : "Body",
  8606. i, (int) strlen(previous_header), previous_header );
  8607. }
  8608. i++;
  8609. }
  8610. /* update count of header or body lines */
  8611. if (req->headers >= 0) { /* we are in the body */
  8612. req->lines = i;
  8613. } else { /* no body */
  8614. req->headers = i;
  8615. req->lines = 0;
  8616. /* req->data->used will be a NULL byte */
  8617. req->line[0] = ast_str_strlen(req->data);
  8618. }
  8619. if (*c) {
  8620. ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
  8621. }
  8622. /* Split up the first line parts */
  8623. return determine_firstline_parts(req);
  8624. }
  8625. /*!
  8626. \brief Determine whether a SIP message contains an SDP in its body
  8627. \param req the SIP request to process
  8628. \return 1 if SDP found, 0 if not found
  8629. Also updates req->sdp_start and req->sdp_count to indicate where the SDP
  8630. lives in the message body.
  8631. */
  8632. static int find_sdp(struct sip_request *req)
  8633. {
  8634. const char *content_type;
  8635. const char *content_length;
  8636. const char *search;
  8637. char *boundary;
  8638. unsigned int x;
  8639. int boundaryisquoted = FALSE;
  8640. int found_application_sdp = FALSE;
  8641. int found_end_of_headers = FALSE;
  8642. content_length = sip_get_header(req, "Content-Length");
  8643. if (!ast_strlen_zero(content_length)) {
  8644. if (sscanf(content_length, "%30u", &x) != 1) {
  8645. ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
  8646. return 0;
  8647. }
  8648. /* Content-Length of zero means there can't possibly be an
  8649. SDP here, even if the Content-Type says there is */
  8650. if (x == 0)
  8651. return 0;
  8652. }
  8653. content_type = sip_get_header(req, "Content-Type");
  8654. /* if the body contains only SDP, this is easy */
  8655. if (!strncasecmp(content_type, "application/sdp", 15)) {
  8656. req->sdp_start = 0;
  8657. req->sdp_count = req->lines;
  8658. return req->lines ? 1 : 0;
  8659. }
  8660. /* if it's not multipart/mixed, there cannot be an SDP */
  8661. if (strncasecmp(content_type, "multipart/mixed", 15))
  8662. return 0;
  8663. /* if there is no boundary marker, it's invalid */
  8664. if ((search = strcasestr(content_type, ";boundary=")))
  8665. search += 10;
  8666. else if ((search = strcasestr(content_type, "; boundary=")))
  8667. search += 11;
  8668. else
  8669. return 0;
  8670. if (ast_strlen_zero(search))
  8671. return 0;
  8672. /* If the boundary is quoted with ", remove quote */
  8673. if (*search == '\"') {
  8674. search++;
  8675. boundaryisquoted = TRUE;
  8676. }
  8677. /* make a duplicate of the string, with two extra characters
  8678. at the beginning */
  8679. boundary = ast_strdupa(search - 2);
  8680. boundary[0] = boundary[1] = '-';
  8681. /* Remove final quote */
  8682. if (boundaryisquoted)
  8683. boundary[strlen(boundary) - 1] = '\0';
  8684. /* search for the boundary marker, the empty line delimiting headers from
  8685. sdp part and the end boundry if it exists */
  8686. for (x = 0; x < (req->lines); x++) {
  8687. const char *line = REQ_OFFSET_TO_STR(req, line[x]);
  8688. if (!strncasecmp(line, boundary, strlen(boundary))){
  8689. if (found_application_sdp && found_end_of_headers) {
  8690. req->sdp_count = (x - 1) - req->sdp_start;
  8691. return 1;
  8692. }
  8693. found_application_sdp = FALSE;
  8694. }
  8695. if (!strcasecmp(line, "Content-Type: application/sdp"))
  8696. found_application_sdp = TRUE;
  8697. if (ast_strlen_zero(line)) {
  8698. if (found_application_sdp && !found_end_of_headers){
  8699. req->sdp_start = x;
  8700. found_end_of_headers = TRUE;
  8701. }
  8702. }
  8703. }
  8704. if (found_application_sdp && found_end_of_headers) {
  8705. req->sdp_count = x - req->sdp_start;
  8706. return TRUE;
  8707. }
  8708. return FALSE;
  8709. }
  8710. /*! \brief Change hold state for a call */
  8711. static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
  8712. {
  8713. if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD))) {
  8714. sip_peer_hold(dialog, holdstate);
  8715. }
  8716. append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", ast_str_buffer(req->data));
  8717. if (!holdstate) { /* Put off remote hold */
  8718. ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
  8719. return;
  8720. }
  8721. /* No address for RTP, we're on hold */
  8722. /* Ensure hold flags are cleared so that overlapping flags do not conflict */
  8723. ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
  8724. if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
  8725. ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
  8726. else if (sendonly == 2) /* Inactive stream */
  8727. ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
  8728. else
  8729. ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
  8730. return;
  8731. }
  8732. /*! \internal
  8733. * \brief Returns whether or not the address is null or ANY / unspecified (0.0.0.0 or ::)
  8734. * \retval TRUE if the address is null or any
  8735. * \retval FALSE if the address it not null or any
  8736. * \note In some circumstances, calls should be placed on hold if either of these conditions exist.
  8737. */
  8738. static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
  8739. {
  8740. return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
  8741. }
  8742. /*! \brief Check the media stream list to see if the given type already exists */
  8743. static int has_media_stream(struct sip_pvt *p, enum media_type m)
  8744. {
  8745. struct offered_media *offer = NULL;
  8746. AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
  8747. if (m == offer->type) {
  8748. return 1;
  8749. }
  8750. }
  8751. return 0;
  8752. }
  8753. /*! \brief Process SIP SDP offer, select formats and activate media channels
  8754. If offer is rejected, we will not change any properties of the call
  8755. Return 0 on success, a negative value on errors.
  8756. Must be called after find_sdp().
  8757. */
  8758. static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
  8759. {
  8760. int res = 0;
  8761. /* Iterators for SDP parsing */
  8762. int start = req->sdp_start;
  8763. int next = start;
  8764. int iterator = start;
  8765. /* Temporary vars for SDP parsing */
  8766. char type = '\0';
  8767. const char *value = NULL;
  8768. const char *m = NULL; /* SDP media offer */
  8769. const char *nextm = NULL;
  8770. int len = -1;
  8771. struct offered_media *offer;
  8772. /* Host information */
  8773. struct ast_sockaddr sessionsa;
  8774. struct ast_sockaddr audiosa;
  8775. struct ast_sockaddr videosa;
  8776. struct ast_sockaddr textsa;
  8777. struct ast_sockaddr imagesa;
  8778. struct ast_sockaddr *sa = NULL; /*!< RTP audio destination IP address */
  8779. struct ast_sockaddr *vsa = NULL; /*!< RTP video destination IP address */
  8780. struct ast_sockaddr *tsa = NULL; /*!< RTP text destination IP address */
  8781. struct ast_sockaddr *isa = NULL; /*!< UDPTL image destination IP address */
  8782. int portno = -1; /*!< RTP audio destination port number */
  8783. int vportno = -1; /*!< RTP video destination port number */
  8784. int tportno = -1; /*!< RTP text destination port number */
  8785. int udptlportno = -1; /*!< UDPTL image destination port number */
  8786. /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
  8787. struct ast_format_cap *peercapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  8788. struct ast_format_cap *vpeercapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  8789. struct ast_format_cap *tpeercapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  8790. int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
  8791. struct ast_rtp_codecs newaudiortp = AST_RTP_CODECS_NULL_INIT;
  8792. struct ast_rtp_codecs newvideortp = AST_RTP_CODECS_NULL_INIT;
  8793. struct ast_rtp_codecs newtextrtp = AST_RTP_CODECS_NULL_INIT;
  8794. struct ast_format_cap *newjointcapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT); /* Negotiated capability */
  8795. struct ast_format_cap *newpeercapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  8796. int newnoncodeccapability;
  8797. const char *codecs;
  8798. unsigned int codec;
  8799. /* SRTP */
  8800. int secure_audio = FALSE;
  8801. int secure_video = FALSE;
  8802. /* Others */
  8803. int sendonly = -1;
  8804. unsigned int numberofports;
  8805. int last_rtpmap_codec = 0;
  8806. int red_data_pt[10]; /* For T.140 RED */
  8807. int red_num_gen = 0; /* For T.140 RED */
  8808. char red_fmtp[100] = "empty"; /* For T.140 RED */
  8809. int debug = sip_debug_test_pvt(p);
  8810. /* START UNKNOWN */
  8811. struct ast_str *codec_buf = ast_str_alloca(64);
  8812. struct ast_format *tmp_fmt;
  8813. /* END UNKNOWN */
  8814. /* Initial check */
  8815. if (!p->rtp) {
  8816. ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
  8817. res = -1;
  8818. goto process_sdp_cleanup;
  8819. }
  8820. if (!peercapability || !vpeercapability || !tpeercapability || !newpeercapability || !newjointcapability) {
  8821. res = -1;
  8822. goto process_sdp_cleanup;
  8823. }
  8824. if (ast_rtp_codecs_payloads_initialize(&newaudiortp) || ast_rtp_codecs_payloads_initialize(&newvideortp) ||
  8825. ast_rtp_codecs_payloads_initialize(&newtextrtp)) {
  8826. res = -1;
  8827. goto process_sdp_cleanup;
  8828. }
  8829. /* Update our last rtprx when we receive an SDP, too */
  8830. p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
  8831. offered_media_list_destroy(p);
  8832. /* Scan for the first media stream (m=) line to limit scanning of globals */
  8833. nextm = get_sdp_iterate(&next, req, "m");
  8834. if (ast_strlen_zero(nextm)) {
  8835. ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
  8836. res = -1;
  8837. goto process_sdp_cleanup;
  8838. }
  8839. /* Scan session level SDP parameters (lines before first media stream) */
  8840. while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
  8841. int processed = FALSE;
  8842. switch (type) {
  8843. case 'o':
  8844. /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
  8845. * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
  8846. */
  8847. if (!process_sdp_o(value, p)) {
  8848. res = (p->session_modify == FALSE) ? 0 : -1;
  8849. goto process_sdp_cleanup;
  8850. }
  8851. processed = TRUE;
  8852. break;
  8853. case 'c':
  8854. if (process_sdp_c(value, &sessionsa)) {
  8855. processed = TRUE;
  8856. sa = &sessionsa;
  8857. vsa = sa;
  8858. tsa = sa;
  8859. isa = sa;
  8860. }
  8861. break;
  8862. case 'a':
  8863. if (process_sdp_a_sendonly(value, &sendonly)) {
  8864. processed = TRUE;
  8865. }
  8866. else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
  8867. processed = TRUE;
  8868. else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
  8869. processed = TRUE;
  8870. else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
  8871. processed = TRUE;
  8872. else if (process_sdp_a_image(value, p))
  8873. processed = TRUE;
  8874. if (process_sdp_a_ice(value, p, p->rtp)) {
  8875. processed = TRUE;
  8876. }
  8877. if (process_sdp_a_ice(value, p, p->vrtp)) {
  8878. processed = TRUE;
  8879. }
  8880. if (process_sdp_a_ice(value, p, p->trtp)) {
  8881. processed = TRUE;
  8882. }
  8883. if (process_sdp_a_dtls(value, p, p->rtp)) {
  8884. processed = TRUE;
  8885. if (p->srtp) {
  8886. ast_set_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK);
  8887. }
  8888. }
  8889. if (process_sdp_a_dtls(value, p, p->vrtp)) {
  8890. processed = TRUE;
  8891. if (p->vsrtp) {
  8892. ast_set_flag(p->vsrtp, AST_SRTP_CRYPTO_OFFER_OK);
  8893. }
  8894. }
  8895. if (process_sdp_a_dtls(value, p, p->trtp)) {
  8896. processed = TRUE;
  8897. if (p->tsrtp) {
  8898. ast_set_flag(p->tsrtp, AST_SRTP_CRYPTO_OFFER_OK);
  8899. }
  8900. }
  8901. break;
  8902. }
  8903. ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
  8904. }
  8905. /* default: novideo and notext set */
  8906. p->novideo = TRUE;
  8907. p->notext = TRUE;
  8908. /* Scan media stream (m=) specific parameters loop */
  8909. while (!ast_strlen_zero(nextm)) {
  8910. int audio = FALSE;
  8911. int video = FALSE;
  8912. int image = FALSE;
  8913. int text = FALSE;
  8914. int processed_crypto = FALSE;
  8915. char protocol[18] = {0,};
  8916. unsigned int x;
  8917. struct ast_rtp_engine_dtls *dtls;
  8918. numberofports = 0;
  8919. len = -1;
  8920. start = next;
  8921. m = nextm;
  8922. iterator = next;
  8923. nextm = get_sdp_iterate(&next, req, "m");
  8924. if (!(offer = ast_calloc(1, sizeof(*offer)))) {
  8925. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer list\n");
  8926. res = -1;
  8927. goto process_sdp_cleanup;
  8928. }
  8929. AST_LIST_INSERT_TAIL(&p->offered_media, offer, next);
  8930. offer->type = SDP_UNKNOWN;
  8931. /* Check for 'audio' media offer */
  8932. if (strncmp(m, "audio ", 6) == 0) {
  8933. if ((sscanf(m, "audio %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
  8934. (sscanf(m, "audio %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
  8935. codecs = m + len;
  8936. /* produce zero-port m-line since it may be needed later
  8937. * length is "m=audio 0 " + protocol + " " + codecs + "\r\n\0" */
  8938. if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
  8939. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  8940. res = -1;
  8941. goto process_sdp_cleanup;
  8942. }
  8943. /* guaranteed to be exactly the right length */
  8944. sprintf(offer->decline_m_line, "m=audio 0 %s %s\r\n", protocol, codecs);
  8945. if (x == 0) {
  8946. ast_debug(1, "Ignoring audio media offer because port number is zero\n");
  8947. continue;
  8948. }
  8949. if (has_media_stream(p, SDP_AUDIO)) {
  8950. ast_log(LOG_WARNING, "Declining non-primary audio stream: %s\n", m);
  8951. continue;
  8952. }
  8953. /* Check number of ports offered for stream */
  8954. if (numberofports > 1) {
  8955. ast_log(LOG_WARNING, "%u ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
  8956. }
  8957. if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  8958. if (req->method != SIP_RESPONSE) {
  8959. ast_log(LOG_NOTICE, "Received SAVPF profle in audio offer but AVPF is not enabled, enabling: %s\n", m);
  8960. secure_audio = 1;
  8961. ast_set_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
  8962. }
  8963. else {
  8964. ast_log(LOG_WARNING, "Received SAVPF profle in audio answer but AVPF is not enabled: %s\n", m);
  8965. continue;
  8966. }
  8967. } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  8968. if (req->method != SIP_RESPONSE) {
  8969. ast_log(LOG_NOTICE, "Received SAVP profle in audio offer but AVPF is enabled, disabling: %s\n", m);
  8970. secure_audio = 1;
  8971. ast_clear_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
  8972. }
  8973. else {
  8974. ast_log(LOG_WARNING, "Received SAVP profile in audio offer but AVPF is enabled: %s\n", m);
  8975. continue;
  8976. }
  8977. } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
  8978. secure_audio = 1;
  8979. processed_crypto = 1;
  8980. if (p->srtp) {
  8981. ast_set_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK);
  8982. }
  8983. } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
  8984. secure_audio = 1;
  8985. } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  8986. if (req->method != SIP_RESPONSE) {
  8987. ast_log(LOG_NOTICE, "Received AVPF profile in audio offer but AVPF is not enabled, enabling: %s\n", m);
  8988. ast_set_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
  8989. }
  8990. else {
  8991. ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
  8992. continue;
  8993. }
  8994. } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  8995. if (req->method != SIP_RESPONSE) {
  8996. ast_log(LOG_NOTICE, "Received AVP profile in audio answer but AVPF is enabled, disabling: %s\n", m);
  8997. ast_clear_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
  8998. }
  8999. else {
  9000. ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
  9001. continue;
  9002. }
  9003. } else if ((!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) &&
  9004. (!(dtls = ast_rtp_instance_get_dtls(p->rtp)) || !dtls->active(p->rtp))) {
  9005. ast_log(LOG_WARNING, "Received UDP/TLS in audio offer but DTLS is not enabled: %s\n", m);
  9006. continue;
  9007. } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
  9008. ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
  9009. continue;
  9010. }
  9011. audio = TRUE;
  9012. offer->type = SDP_AUDIO;
  9013. portno = x;
  9014. /* Scan through the RTP payload types specified in a "m=" line: */
  9015. for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
  9016. if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
  9017. ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
  9018. res = -1;
  9019. goto process_sdp_cleanup;
  9020. }
  9021. if (debug) {
  9022. ast_verbose("Found RTP audio format %u\n", codec);
  9023. }
  9024. ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
  9025. }
  9026. } else {
  9027. ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
  9028. res = -1;
  9029. goto process_sdp_cleanup;
  9030. }
  9031. }
  9032. /* Check for 'video' media offer */
  9033. else if (strncmp(m, "video ", 6) == 0) {
  9034. if ((sscanf(m, "video %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
  9035. (sscanf(m, "video %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
  9036. codecs = m + len;
  9037. /* produce zero-port m-line since it may be needed later
  9038. * length is "m=video 0 " + protocol + " " + codecs + "\r\n\0" */
  9039. if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
  9040. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  9041. res = -1;
  9042. goto process_sdp_cleanup;
  9043. }
  9044. /* guaranteed to be exactly the right length */
  9045. sprintf(offer->decline_m_line, "m=video 0 %s %s\r\n", protocol, codecs);
  9046. if (x == 0) {
  9047. ast_debug(1, "Ignoring video stream offer because port number is zero\n");
  9048. continue;
  9049. }
  9050. /* Check number of ports offered for stream */
  9051. if (numberofports > 1) {
  9052. ast_log(LOG_WARNING, "%u ports offered for video stream, not supported by Asterisk. Will try anyway...\n", numberofports);
  9053. }
  9054. if (has_media_stream(p, SDP_VIDEO)) {
  9055. ast_log(LOG_WARNING, "Declining non-primary video stream: %s\n", m);
  9056. continue;
  9057. }
  9058. if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9059. ast_log(LOG_WARNING, "Received SAVPF profle in video offer but AVPF is not enabled: %s\n", m);
  9060. continue;
  9061. } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9062. ast_log(LOG_WARNING, "Received SAVP profile in video offer but AVPF is enabled: %s\n", m);
  9063. continue;
  9064. } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
  9065. secure_video = 1;
  9066. processed_crypto = 1;
  9067. if (p->vsrtp || (p->vsrtp = ast_sdp_srtp_alloc())) {
  9068. ast_set_flag(p->vsrtp, AST_SRTP_CRYPTO_OFFER_OK);
  9069. }
  9070. } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
  9071. secure_video = 1;
  9072. } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9073. ast_log(LOG_WARNING, "Received AVPF profile in video offer but AVPF is not enabled: %s\n", m);
  9074. continue;
  9075. } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9076. ast_log(LOG_WARNING, "Received AVP profile in video offer but AVPF is enabled: %s\n", m);
  9077. continue;
  9078. } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
  9079. ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
  9080. continue;
  9081. }
  9082. video = TRUE;
  9083. p->novideo = FALSE;
  9084. offer->type = SDP_VIDEO;
  9085. vportno = x;
  9086. /* Scan through the RTP payload types specified in a "m=" line: */
  9087. for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
  9088. if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
  9089. ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
  9090. res = -1;
  9091. goto process_sdp_cleanup;
  9092. }
  9093. if (debug) {
  9094. ast_verbose("Found RTP video format %u\n", codec);
  9095. }
  9096. ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
  9097. }
  9098. } else {
  9099. ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
  9100. res = -1;
  9101. goto process_sdp_cleanup;
  9102. }
  9103. }
  9104. /* Check for 'text' media offer */
  9105. else if (strncmp(m, "text ", 5) == 0) {
  9106. if ((sscanf(m, "text %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
  9107. (sscanf(m, "text %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
  9108. codecs = m + len;
  9109. /* produce zero-port m-line since it may be needed later
  9110. * length is "m=text 0 " + protocol + " " + codecs + "\r\n\0" */
  9111. if (!(offer->decline_m_line = ast_malloc(9 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
  9112. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  9113. res = -1;
  9114. goto process_sdp_cleanup;
  9115. }
  9116. /* guaranteed to be exactly the right length */
  9117. sprintf(offer->decline_m_line, "m=text 0 %s %s\r\n", protocol, codecs);
  9118. if (x == 0) {
  9119. ast_debug(1, "Ignoring text stream offer because port number is zero\n");
  9120. continue;
  9121. }
  9122. /* Check number of ports offered for stream */
  9123. if (numberofports > 1) {
  9124. ast_log(LOG_WARNING, "%u ports offered for text stream, not supported by Asterisk. Will try anyway...\n", numberofports);
  9125. }
  9126. if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9127. ast_log(LOG_WARNING, "Received AVPF profile in text offer but AVPF is not enabled: %s\n", m);
  9128. continue;
  9129. } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
  9130. ast_log(LOG_WARNING, "Received AVP profile in text offer but AVPF is enabled: %s\n", m);
  9131. continue;
  9132. } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
  9133. ast_log(LOG_WARNING, "Unknown RTP profile in text offer: %s\n", m);
  9134. continue;
  9135. }
  9136. if (has_media_stream(p, SDP_TEXT)) {
  9137. ast_log(LOG_WARNING, "Declining non-primary text stream: %s\n", m);
  9138. continue;
  9139. }
  9140. text = TRUE;
  9141. p->notext = FALSE;
  9142. offer->type = SDP_TEXT;
  9143. tportno = x;
  9144. /* Scan through the RTP payload types specified in a "m=" line: */
  9145. for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
  9146. if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
  9147. ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
  9148. res = -1;
  9149. goto process_sdp_cleanup;
  9150. }
  9151. if (debug) {
  9152. ast_verbose("Found RTP text format %u\n", codec);
  9153. }
  9154. ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
  9155. }
  9156. } else {
  9157. ast_log(LOG_WARNING, "Rejecting text stream offer due to invalid or unsupported syntax: %s\n", m);
  9158. res = -1;
  9159. goto process_sdp_cleanup;
  9160. }
  9161. }
  9162. /* Check for 'image' media offer */
  9163. else if (strncmp(m, "image ", 6) == 0) {
  9164. if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
  9165. (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
  9166. /* produce zero-port m-line since it may be needed later
  9167. * length is "m=image 0 udptl t38" + "\r\n\0" */
  9168. if (!(offer->decline_m_line = ast_malloc(22))) {
  9169. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  9170. res = -1;
  9171. goto process_sdp_cleanup;
  9172. }
  9173. /* guaranteed to be exactly the right length */
  9174. strcpy(offer->decline_m_line, "m=image 0 udptl t38\r\n");
  9175. if (x == 0) {
  9176. ast_debug(1, "Ignoring image stream offer because port number is zero\n");
  9177. continue;
  9178. }
  9179. if (initialize_udptl(p)) {
  9180. ast_log(LOG_WARNING, "Failed to initialize UDPTL, declining image stream\n");
  9181. continue;
  9182. }
  9183. if (has_media_stream(p, SDP_IMAGE)) {
  9184. ast_log(LOG_WARNING, "Declining non-primary image stream: %s\n", m);
  9185. continue;
  9186. }
  9187. image = TRUE;
  9188. if (debug) {
  9189. ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
  9190. }
  9191. offer->type = SDP_IMAGE;
  9192. udptlportno = x;
  9193. if (p->t38.state != T38_ENABLED) {
  9194. memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
  9195. /* default EC to none, the remote end should
  9196. * respond with the EC they want to use */
  9197. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
  9198. }
  9199. } else if (sscanf(m, "image %30u %17s t38%n", &x, protocol, &len) == 2 && len > 0) {
  9200. ast_log(LOG_WARNING, "Declining image stream due to unsupported transport: %s\n", m);
  9201. /* produce zero-port m-line since this is guaranteed to be declined
  9202. * length is "m=image 0 strlen(protocol) t38" + "\r\n\0" */
  9203. if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 7))) {
  9204. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  9205. res = -1;
  9206. goto process_sdp_cleanup;
  9207. }
  9208. /* guaranteed to be exactly the right length */
  9209. sprintf(offer->decline_m_line, "m=image 0 %s t38\r\n", protocol);
  9210. continue;
  9211. } else {
  9212. ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
  9213. res = -1;
  9214. goto process_sdp_cleanup;
  9215. }
  9216. } else {
  9217. char type[20] = {0,};
  9218. if ((sscanf(m, "%19s %30u/%30u %n", type, &x, &numberofports, &len) == 3 && len > 0) ||
  9219. (sscanf(m, "%19s %30u %n", type, &x, &len) == 2 && len > 0)) {
  9220. /* produce zero-port m-line since it may be needed later
  9221. * length is "m=" + type + " 0 " + remainder + "\r\n\0" */
  9222. if (!(offer->decline_m_line = ast_malloc(2 + strlen(type) + 3 + strlen(m + len) + 3))) {
  9223. ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
  9224. res = -1;
  9225. goto process_sdp_cleanup;
  9226. }
  9227. /* guaranteed to be long enough */
  9228. sprintf(offer->decline_m_line, "m=%s 0 %s\r\n", type, m + len);
  9229. continue;
  9230. } else {
  9231. ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
  9232. res = -1;
  9233. goto process_sdp_cleanup;
  9234. }
  9235. }
  9236. /* Media stream specific parameters */
  9237. while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
  9238. int processed = FALSE;
  9239. switch (type) {
  9240. case 'c':
  9241. if (audio) {
  9242. if (process_sdp_c(value, &audiosa)) {
  9243. processed = TRUE;
  9244. sa = &audiosa;
  9245. }
  9246. } else if (video) {
  9247. if (process_sdp_c(value, &videosa)) {
  9248. processed = TRUE;
  9249. vsa = &videosa;
  9250. }
  9251. } else if (text) {
  9252. if (process_sdp_c(value, &textsa)) {
  9253. processed = TRUE;
  9254. tsa = &textsa;
  9255. }
  9256. } else if (image) {
  9257. if (process_sdp_c(value, &imagesa)) {
  9258. processed = TRUE;
  9259. isa = &imagesa;
  9260. }
  9261. }
  9262. break;
  9263. case 'a':
  9264. /* Audio specific scanning */
  9265. if (audio) {
  9266. if (process_sdp_a_ice(value, p, p->rtp)) {
  9267. processed = TRUE;
  9268. } else if (process_sdp_a_dtls(value, p, p->rtp)) {
  9269. processed_crypto = TRUE;
  9270. processed = TRUE;
  9271. if (p->srtp) {
  9272. ast_set_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK);
  9273. }
  9274. } else if (process_sdp_a_sendonly(value, &sendonly)) {
  9275. processed = TRUE;
  9276. } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
  9277. processed_crypto = TRUE;
  9278. processed = TRUE;
  9279. } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
  9280. processed = TRUE;
  9281. }
  9282. }
  9283. /* Video specific scanning */
  9284. else if (video) {
  9285. if (process_sdp_a_ice(value, p, p->vrtp)) {
  9286. processed = TRUE;
  9287. } else if (process_sdp_a_dtls(value, p, p->vrtp)) {
  9288. processed_crypto = TRUE;
  9289. processed = TRUE;
  9290. if (p->vsrtp) {
  9291. ast_set_flag(p->vsrtp, AST_SRTP_CRYPTO_OFFER_OK);
  9292. }
  9293. } else if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
  9294. processed_crypto = TRUE;
  9295. processed = TRUE;
  9296. } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
  9297. processed = TRUE;
  9298. }
  9299. }
  9300. /* Text (T.140) specific scanning */
  9301. else if (text) {
  9302. if (process_sdp_a_ice(value, p, p->trtp)) {
  9303. processed = TRUE;
  9304. } else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
  9305. processed = TRUE;
  9306. } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
  9307. processed_crypto = TRUE;
  9308. processed = TRUE;
  9309. }
  9310. }
  9311. /* Image (T.38 FAX) specific scanning */
  9312. else if (image) {
  9313. if (process_sdp_a_image(value, p))
  9314. processed = TRUE;
  9315. }
  9316. break;
  9317. }
  9318. ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
  9319. (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
  9320. type, value,
  9321. (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
  9322. }
  9323. /* Ensure crypto lines are provided where necessary */
  9324. if (audio && secure_audio && !processed_crypto) {
  9325. ast_log(LOG_WARNING, "Rejecting secure audio stream without encryption details: %s\n", m);
  9326. res = -1;
  9327. goto process_sdp_cleanup;
  9328. } else if (video && secure_video && !processed_crypto) {
  9329. ast_log(LOG_WARNING, "Rejecting secure video stream without encryption details: %s\n", m);
  9330. res = -1;
  9331. goto process_sdp_cleanup;
  9332. }
  9333. }
  9334. /* Sanity checks */
  9335. if (!sa && !vsa && !tsa && !isa) {
  9336. ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
  9337. res = -1;
  9338. goto process_sdp_cleanup;
  9339. }
  9340. if ((portno == -1) &&
  9341. (vportno == -1) &&
  9342. (tportno == -1) &&
  9343. (udptlportno == -1)) {
  9344. ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
  9345. res = -1;
  9346. goto process_sdp_cleanup;
  9347. }
  9348. if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK)))) {
  9349. ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
  9350. res = -1;
  9351. goto process_sdp_cleanup;
  9352. }
  9353. if (!secure_audio && p->srtp) {
  9354. ast_log(LOG_WARNING, "We are requesting SRTP for audio, but they responded without it!\n");
  9355. res = -1;
  9356. goto process_sdp_cleanup;
  9357. }
  9358. if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, AST_SRTP_CRYPTO_OFFER_OK)))) {
  9359. ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
  9360. res = -1;
  9361. goto process_sdp_cleanup;
  9362. }
  9363. if (!p->novideo && !secure_video && p->vsrtp) {
  9364. ast_log(LOG_WARNING, "We are requesting SRTP for video, but they responded without it!\n");
  9365. res = -1;
  9366. goto process_sdp_cleanup;
  9367. }
  9368. if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
  9369. ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
  9370. res = -1;
  9371. goto process_sdp_cleanup;
  9372. }
  9373. if (udptlportno == -1) {
  9374. change_t38_state(p, T38_DISABLED);
  9375. }
  9376. /* Now gather all of the codecs that we are asked for: */
  9377. ast_rtp_codecs_payload_formats(&newaudiortp, peercapability, &peernoncodeccapability);
  9378. ast_rtp_codecs_payload_formats(&newvideortp, vpeercapability, &vpeernoncodeccapability);
  9379. ast_rtp_codecs_payload_formats(&newtextrtp, tpeercapability, &tpeernoncodeccapability);
  9380. ast_format_cap_append_from_cap(newpeercapability, peercapability, AST_MEDIA_TYPE_AUDIO);
  9381. ast_format_cap_append_from_cap(newpeercapability, vpeercapability, AST_MEDIA_TYPE_VIDEO);
  9382. ast_format_cap_append_from_cap(newpeercapability, tpeercapability, AST_MEDIA_TYPE_TEXT);
  9383. ast_format_cap_get_compatible(p->caps, newpeercapability, newjointcapability);
  9384. if (!ast_format_cap_count(newjointcapability) && udptlportno == -1) {
  9385. ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
  9386. /* Do NOT Change current setting */
  9387. res = -1;
  9388. goto process_sdp_cleanup;
  9389. }
  9390. newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
  9391. if (debug) {
  9392. /* shame on whoever coded this.... */
  9393. struct ast_str *cap_buf = ast_str_alloca(64);
  9394. struct ast_str *peer_buf = ast_str_alloca(64);
  9395. struct ast_str *vpeer_buf = ast_str_alloca(64);
  9396. struct ast_str *tpeer_buf = ast_str_alloca(64);
  9397. struct ast_str *joint_buf = ast_str_alloca(64);
  9398. ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
  9399. ast_format_cap_get_names(p->caps, &cap_buf),
  9400. ast_format_cap_get_names(peercapability, &peer_buf),
  9401. ast_format_cap_get_names(vpeercapability, &vpeer_buf),
  9402. ast_format_cap_get_names(tpeercapability, &tpeer_buf),
  9403. ast_format_cap_get_names(newjointcapability, &joint_buf));
  9404. }
  9405. if (debug) {
  9406. struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
  9407. struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
  9408. struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
  9409. ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
  9410. ast_rtp_lookup_mime_multiple2(s1, NULL, p->noncodeccapability, 0, 0),
  9411. ast_rtp_lookup_mime_multiple2(s2, NULL, peernoncodeccapability, 0, 0),
  9412. ast_rtp_lookup_mime_multiple2(s3, NULL, newnoncodeccapability, 0, 0));
  9413. }
  9414. if (portno != -1 || vportno != -1 || tportno != -1) {
  9415. /* We are now ready to change the sip session and RTP structures with the offered codecs, since
  9416. they are acceptable */
  9417. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  9418. ast_format_cap_append_from_cap(p->jointcaps, newjointcapability, AST_MEDIA_TYPE_UNKNOWN); /* Our joint codec profile for this call */
  9419. ast_format_cap_remove_by_type(p->peercaps, AST_MEDIA_TYPE_UNKNOWN);
  9420. ast_format_cap_append_from_cap(p->peercaps, newpeercapability, AST_MEDIA_TYPE_UNKNOWN); /* The other side's capability in latest offer */
  9421. p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
  9422. /* respond with single most preferred joint codec, limiting the other side's choice */
  9423. if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
  9424. unsigned int framing;
  9425. tmp_fmt = ast_format_cap_get_format(p->jointcaps, 0);
  9426. framing = ast_format_cap_get_format_framing(p->jointcaps, tmp_fmt);
  9427. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  9428. ast_format_cap_append(p->jointcaps, tmp_fmt, framing);
  9429. ao2_ref(tmp_fmt, -1);
  9430. }
  9431. }
  9432. /* Setup audio address and port */
  9433. if (p->rtp) {
  9434. if (sa && portno > 0) {
  9435. start_ice(p->rtp, (req->method != SIP_RESPONSE) ? 0 : 1);
  9436. ast_sockaddr_set_port(sa, portno);
  9437. ast_rtp_instance_set_remote_address(p->rtp, sa);
  9438. if (debug) {
  9439. ast_verbose("Peer audio RTP is at port %s\n",
  9440. ast_sockaddr_stringify(sa));
  9441. }
  9442. ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
  9443. /* Ensure RTCP is enabled since it may be inactive
  9444. if we're coming back from a T.38 session */
  9445. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
  9446. /* Ensure audio RTCP reads are enabled */
  9447. if (p->owner) {
  9448. ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
  9449. }
  9450. if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
  9451. ast_clear_flag(&p->flags[0], SIP_DTMF);
  9452. if (newnoncodeccapability & AST_RTP_DTMF) {
  9453. /* XXX Would it be reasonable to drop the DSP at this point? XXX */
  9454. ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
  9455. /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
  9456. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
  9457. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  9458. } else {
  9459. ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
  9460. }
  9461. }
  9462. } else if (udptlportno > 0) {
  9463. if (debug)
  9464. ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
  9465. /* Prevent audio RTCP reads */
  9466. if (p->owner) {
  9467. ast_channel_set_fd(p->owner, 1, -1);
  9468. }
  9469. /* Silence RTCP while audio RTP is inactive */
  9470. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
  9471. } else {
  9472. ast_rtp_instance_stop(p->rtp);
  9473. if (debug)
  9474. ast_verbose("Peer doesn't provide audio\n");
  9475. }
  9476. }
  9477. /* Setup video address and port */
  9478. if (p->vrtp) {
  9479. if (vsa && vportno > 0) {
  9480. start_ice(p->vrtp, (req->method != SIP_RESPONSE) ? 0 : 1);
  9481. ast_sockaddr_set_port(vsa, vportno);
  9482. ast_rtp_instance_set_remote_address(p->vrtp, vsa);
  9483. if (debug) {
  9484. ast_verbose("Peer video RTP is at port %s\n",
  9485. ast_sockaddr_stringify(vsa));
  9486. }
  9487. ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
  9488. } else {
  9489. ast_rtp_instance_stop(p->vrtp);
  9490. if (debug)
  9491. ast_verbose("Peer doesn't provide video\n");
  9492. }
  9493. }
  9494. /* Setup text address and port */
  9495. if (p->trtp) {
  9496. if (tsa && tportno > 0) {
  9497. start_ice(p->trtp, (req->method != SIP_RESPONSE) ? 0 : 1);
  9498. ast_sockaddr_set_port(tsa, tportno);
  9499. ast_rtp_instance_set_remote_address(p->trtp, tsa);
  9500. if (debug) {
  9501. ast_verbose("Peer T.140 RTP is at port %s\n",
  9502. ast_sockaddr_stringify(tsa));
  9503. }
  9504. if (ast_format_cap_iscompatible_format(p->jointcaps, ast_format_t140_red) != AST_FORMAT_CMP_NOT_EQUAL) {
  9505. p->red = 1;
  9506. ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
  9507. } else {
  9508. p->red = 0;
  9509. }
  9510. ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
  9511. } else {
  9512. ast_rtp_instance_stop(p->trtp);
  9513. if (debug)
  9514. ast_verbose("Peer doesn't provide T.140\n");
  9515. }
  9516. }
  9517. /* Setup image address and port */
  9518. if (p->udptl) {
  9519. if (isa && udptlportno > 0) {
  9520. if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
  9521. ast_rtp_instance_get_remote_address(p->rtp, isa);
  9522. if (!ast_sockaddr_isnull(isa) && debug) {
  9523. ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
  9524. }
  9525. }
  9526. ast_sockaddr_set_port(isa, udptlportno);
  9527. ast_udptl_set_peer(p->udptl, isa);
  9528. if (debug)
  9529. ast_debug(1, "Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
  9530. /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
  9531. if (!ast_udptl_get_far_max_datagram(p->udptl)) {
  9532. /* setting to zero will force a default if none was provided by the SDP */
  9533. ast_udptl_set_far_max_datagram(p->udptl, 0);
  9534. }
  9535. /* Remote party offers T38, we need to update state */
  9536. if ((t38action == SDP_T38_ACCEPT) &&
  9537. (p->t38.state == T38_LOCAL_REINVITE)) {
  9538. change_t38_state(p, T38_ENABLED);
  9539. } else if ((t38action == SDP_T38_INITIATE) &&
  9540. p->owner && p->lastinvite) {
  9541. change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
  9542. /* If fax detection is enabled then send us off to the fax extension */
  9543. if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
  9544. ast_channel_lock(p->owner);
  9545. if (strcmp(ast_channel_exten(p->owner), "fax")) {
  9546. const char *target_context = S_OR(ast_channel_macrocontext(p->owner), ast_channel_context(p->owner));
  9547. ast_channel_unlock(p->owner);
  9548. if (ast_exists_extension(p->owner, target_context, "fax", 1,
  9549. S_COR(ast_channel_caller(p->owner)->id.number.valid, ast_channel_caller(p->owner)->id.number.str, NULL))) {
  9550. ast_verb(2, "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", ast_channel_name(p->owner));
  9551. pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", ast_channel_exten(p->owner));
  9552. if (ast_async_goto(p->owner, target_context, "fax", 1)) {
  9553. ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(p->owner), target_context);
  9554. }
  9555. } else {
  9556. ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
  9557. }
  9558. } else {
  9559. ast_channel_unlock(p->owner);
  9560. }
  9561. }
  9562. }
  9563. } else {
  9564. change_t38_state(p, T38_DISABLED);
  9565. ast_udptl_stop(p->udptl);
  9566. if (debug)
  9567. ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
  9568. }
  9569. }
  9570. if ((portno == -1) && (p->t38.state != T38_DISABLED) && (p->t38.state != T38_REJECTED)) {
  9571. ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
  9572. res = 0;
  9573. goto process_sdp_cleanup;
  9574. }
  9575. /* Ok, we're going with this offer */
  9576. ast_debug(2, "We're settling with these formats: %s\n", ast_format_cap_get_names(p->jointcaps, &codec_buf));
  9577. if (!p->owner) { /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
  9578. res = 0;
  9579. goto process_sdp_cleanup;
  9580. }
  9581. ast_debug(4, "We have an owner, now see if we need to change this call\n");
  9582. if (ast_format_cap_has_type(p->jointcaps, AST_MEDIA_TYPE_AUDIO)) {
  9583. struct ast_format_cap *caps;
  9584. unsigned int framing;
  9585. if (debug) {
  9586. struct ast_str *cap_buf = ast_str_alloca(64);
  9587. struct ast_str *joint_buf = ast_str_alloca(64);
  9588. ast_debug(1, "Setting native formats after processing SDP. peer joint formats %s, old nativeformats %s\n",
  9589. ast_format_cap_get_names(p->jointcaps, &joint_buf),
  9590. ast_format_cap_get_names(ast_channel_nativeformats(p->owner), &cap_buf));
  9591. }
  9592. caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  9593. if (caps) {
  9594. tmp_fmt = ast_format_cap_get_format(p->jointcaps, 0);
  9595. framing = ast_format_cap_get_format_framing(p->jointcaps, tmp_fmt);
  9596. ast_format_cap_append(caps, tmp_fmt, framing);
  9597. ast_format_cap_append_from_cap(caps, vpeercapability, AST_MEDIA_TYPE_VIDEO);
  9598. ast_format_cap_append_from_cap(caps, tpeercapability, AST_MEDIA_TYPE_TEXT);
  9599. ast_channel_nativeformats_set(p->owner, caps);
  9600. ao2_ref(caps, -1);
  9601. ao2_ref(tmp_fmt, -1);
  9602. }
  9603. ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
  9604. ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
  9605. }
  9606. 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)) {
  9607. if (!ast_test_flag(&p->flags[2], SIP_PAGE3_DISCARD_REMOTE_HOLD_RETRIEVAL)) {
  9608. ast_queue_unhold(p->owner);
  9609. }
  9610. /* Activate a re-invite */
  9611. ast_queue_frame(p->owner, &ast_null_frame);
  9612. change_hold_state(p, req, FALSE, sendonly);
  9613. } 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)) {
  9614. if (!ast_test_flag(&p->flags[2], SIP_PAGE3_DISCARD_REMOTE_HOLD_RETRIEVAL)) {
  9615. ast_queue_hold(p->owner, p->mohsuggest);
  9616. }
  9617. if (sendonly)
  9618. ast_rtp_instance_stop(p->rtp);
  9619. /* RTCP needs to go ahead, even if we're on hold!!! */
  9620. /* Activate a re-invite */
  9621. ast_queue_frame(p->owner, &ast_null_frame);
  9622. change_hold_state(p, req, TRUE, sendonly);
  9623. }
  9624. process_sdp_cleanup:
  9625. if (res) {
  9626. offered_media_list_destroy(p);
  9627. }
  9628. ast_rtp_codecs_payloads_destroy(&newtextrtp);
  9629. ast_rtp_codecs_payloads_destroy(&newvideortp);
  9630. ast_rtp_codecs_payloads_destroy(&newaudiortp);
  9631. ao2_cleanup(peercapability);
  9632. ao2_cleanup(vpeercapability);
  9633. ao2_cleanup(tpeercapability);
  9634. ao2_cleanup(newjointcapability);
  9635. ao2_cleanup(newpeercapability);
  9636. return res;
  9637. }
  9638. static int process_sdp_o(const char *o, struct sip_pvt *p)
  9639. {
  9640. char *o_copy;
  9641. char *token;
  9642. int64_t rua_version;
  9643. /* Store the SDP version number of remote UA. This will allow us to
  9644. distinguish between session modifications and session refreshes. If
  9645. the remote UA does not send an incremented SDP version number in a
  9646. subsequent RE-INVITE then that means its not changing media session.
  9647. The RE-INVITE may have been sent to update connected party, remote
  9648. target or to refresh the session (Session-Timers). Asterisk must not
  9649. change media session and increment its own version number in answer
  9650. SDP in this case. */
  9651. p->session_modify = TRUE;
  9652. if (ast_strlen_zero(o)) {
  9653. ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
  9654. return FALSE;
  9655. }
  9656. o_copy = ast_strdupa(o);
  9657. token = strsep(&o_copy, " "); /* Skip username */
  9658. if (!o_copy) {
  9659. ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
  9660. return FALSE;
  9661. }
  9662. token = strsep(&o_copy, " "); /* Skip session-id */
  9663. if (!o_copy) {
  9664. ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
  9665. return FALSE;
  9666. }
  9667. token = strsep(&o_copy, " "); /* Version */
  9668. if (!o_copy) {
  9669. ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
  9670. return FALSE;
  9671. }
  9672. if (!sscanf(token, "%30" SCNd64, &rua_version)) {
  9673. ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
  9674. return FALSE;
  9675. }
  9676. /* we need to check the SDP version number the other end sent us;
  9677. * our rules for deciding what to accept are a bit complex.
  9678. *
  9679. * 1) if 'ignoresdpversion' has been set for this dialog, then
  9680. * we will just accept whatever they sent and assume it is
  9681. * a modification of the session, even if it is not
  9682. * 2) otherwise, if this is the first SDP we've seen from them
  9683. * we accept it
  9684. * 3) otherwise, if the new SDP version number is higher than the
  9685. * old one, we accept it
  9686. * 4) otherwise, if this SDP is in response to us requesting a switch
  9687. * to T.38, we accept the SDP, but also generate a warning message
  9688. * that this peer should have the 'ignoresdpversion' option set,
  9689. * because it is not following the SDP offer/answer RFC; if we did
  9690. * not request a switch to T.38, then we stop parsing the SDP, as it
  9691. * has not changed from the previous version
  9692. */
  9693. if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
  9694. (p->sessionversion_remote < 0) ||
  9695. (p->sessionversion_remote < rua_version)) {
  9696. p->sessionversion_remote = rua_version;
  9697. } else {
  9698. if (p->t38.state == T38_LOCAL_REINVITE) {
  9699. p->sessionversion_remote = rua_version;
  9700. 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);
  9701. } else {
  9702. p->session_modify = FALSE;
  9703. ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
  9704. return FALSE;
  9705. }
  9706. }
  9707. return TRUE;
  9708. }
  9709. static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
  9710. {
  9711. char proto[4], host[258];
  9712. int af;
  9713. /* Check for Media-description-level-address */
  9714. if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
  9715. if (!strcmp("IP4", proto)) {
  9716. af = AF_INET;
  9717. } else if (!strcmp("IP6", proto)) {
  9718. af = AF_INET6;
  9719. } else {
  9720. ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
  9721. return FALSE;
  9722. }
  9723. if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
  9724. ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
  9725. return FALSE;
  9726. }
  9727. return TRUE;
  9728. } else {
  9729. ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
  9730. return FALSE;
  9731. }
  9732. return FALSE;
  9733. }
  9734. static int process_sdp_a_sendonly(const char *a, int *sendonly)
  9735. {
  9736. int found = FALSE;
  9737. if (!strcasecmp(a, "sendonly")) {
  9738. if (*sendonly == -1)
  9739. *sendonly = 1;
  9740. found = TRUE;
  9741. } else if (!strcasecmp(a, "inactive")) {
  9742. if (*sendonly == -1)
  9743. *sendonly = 2;
  9744. found = TRUE;
  9745. } else if (!strcasecmp(a, "sendrecv")) {
  9746. if (*sendonly == -1)
  9747. *sendonly = 0;
  9748. found = TRUE;
  9749. }
  9750. return found;
  9751. }
  9752. static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
  9753. {
  9754. struct ast_rtp_engine_ice *ice;
  9755. int found = FALSE;
  9756. char ufrag[256], pwd[256], foundation[32], transport[4], address[46], cand_type[6], relay_address[46] = "";
  9757. struct ast_rtp_engine_ice_candidate candidate = { 0, };
  9758. unsigned int port, relay_port = 0;
  9759. if (!instance || !(ice = ast_rtp_instance_get_ice(instance))) {
  9760. return found;
  9761. }
  9762. if (sscanf(a, "ice-ufrag: %255s", ufrag) == 1) {
  9763. ice->set_authentication(instance, ufrag, NULL);
  9764. found = TRUE;
  9765. } else if (sscanf(a, "ice-pwd: %255s", pwd) == 1) {
  9766. ice->set_authentication(instance, NULL, pwd);
  9767. found = TRUE;
  9768. } else if (sscanf(a, "candidate: %31s %30u %3s %30u %23s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport, (unsigned *)&candidate.priority,
  9769. address, &port, cand_type, relay_address, &relay_port) >= 7) {
  9770. candidate.foundation = foundation;
  9771. candidate.transport = transport;
  9772. ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
  9773. ast_sockaddr_set_port(&candidate.address, port);
  9774. if (!strcasecmp(cand_type, "host")) {
  9775. candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
  9776. } else if (!strcasecmp(cand_type, "srflx")) {
  9777. candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
  9778. } else if (!strcasecmp(cand_type, "relay")) {
  9779. candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
  9780. } else {
  9781. return found;
  9782. }
  9783. if (!ast_strlen_zero(relay_address)) {
  9784. ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
  9785. }
  9786. if (relay_port) {
  9787. ast_sockaddr_set_port(&candidate.relay_address, relay_port);
  9788. }
  9789. ice->add_remote_candidate(instance, &candidate);
  9790. found = TRUE;
  9791. } else if (!strcasecmp(a, "ice-lite")) {
  9792. ice->ice_lite(instance);
  9793. found = TRUE;
  9794. }
  9795. return found;
  9796. }
  9797. static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
  9798. {
  9799. struct ast_rtp_engine_dtls *dtls;
  9800. int found = FALSE;
  9801. char value[256], hash[32];
  9802. if (!instance || !p->dtls_cfg.enabled || !(dtls = ast_rtp_instance_get_dtls(instance))) {
  9803. return found;
  9804. }
  9805. if (sscanf(a, "setup: %255s", value) == 1) {
  9806. found = TRUE;
  9807. if (!strcasecmp(value, "active")) {
  9808. dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTIVE);
  9809. } else if (!strcasecmp(value, "passive")) {
  9810. dtls->set_setup(instance, AST_RTP_DTLS_SETUP_PASSIVE);
  9811. } else if (!strcasecmp(value, "actpass")) {
  9812. dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTPASS);
  9813. } else if (!strcasecmp(value, "holdconn")) {
  9814. dtls->set_setup(instance, AST_RTP_DTLS_SETUP_HOLDCONN);
  9815. } else {
  9816. ast_log(LOG_WARNING, "Unsupported setup attribute value '%s' received on dialog '%s'\n",
  9817. value, p->callid);
  9818. }
  9819. } else if (sscanf(a, "connection: %255s", value) == 1) {
  9820. found = TRUE;
  9821. if (!strcasecmp(value, "new")) {
  9822. dtls->reset(instance);
  9823. } else if (!strcasecmp(value, "existing")) {
  9824. /* Since they want to just use what already exists we go on as if nothing happened */
  9825. } else {
  9826. ast_log(LOG_WARNING, "Unsupported connection attribute value '%s' received on dialog '%s'\n",
  9827. value, p->callid);
  9828. }
  9829. } else if (sscanf(a, "fingerprint: %31s %255s", hash, value) == 2) {
  9830. found = TRUE;
  9831. if (!strcasecmp(hash, "sha-1")) {
  9832. dtls->set_fingerprint(instance, AST_RTP_DTLS_HASH_SHA1, value);
  9833. } else if (!strcasecmp(hash, "sha-256")) {
  9834. dtls->set_fingerprint(instance, AST_RTP_DTLS_HASH_SHA256, value);
  9835. } else {
  9836. ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s' received on dialog '%s'\n",
  9837. hash, p->callid);
  9838. }
  9839. }
  9840. return found;
  9841. }
  9842. static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
  9843. {
  9844. int found = FALSE;
  9845. unsigned int codec;
  9846. char mimeSubtype[128];
  9847. char fmtp_string[256];
  9848. unsigned int sample_rate;
  9849. int debug = sip_debug_test_pvt(p);
  9850. if (!strncasecmp(a, "ptime", 5)) {
  9851. char *tmp = strrchr(a, ':');
  9852. long int framing = 0;
  9853. if (tmp) {
  9854. tmp++;
  9855. framing = strtol(tmp, NULL, 10);
  9856. if (framing == LONG_MIN || framing == LONG_MAX) {
  9857. framing = 0;
  9858. ast_debug(1, "Can't read framing from SDP: %s\n", a);
  9859. }
  9860. }
  9861. if (framing && p->autoframing) {
  9862. ast_debug(1, "Setting framing to %ld\n", framing);
  9863. ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(p->rtp), framing);
  9864. }
  9865. found = TRUE;
  9866. } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
  9867. /* We have a rtpmap to handle */
  9868. if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
  9869. if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
  9870. ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
  9871. if (debug)
  9872. ast_verbose("Found audio description format %s for ID %u\n", mimeSubtype, codec);
  9873. //found_rtpmap_codecs[last_rtpmap_codec] = codec;
  9874. (*last_rtpmap_codec)++;
  9875. found = TRUE;
  9876. } else {
  9877. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  9878. if (debug)
  9879. ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
  9880. }
  9881. } else {
  9882. if (debug)
  9883. ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
  9884. }
  9885. } else if (sscanf(a, "fmtp: %30u %255[^\t\n]", &codec, fmtp_string) == 2) {
  9886. struct ast_format *format;
  9887. if ((format = ast_rtp_codecs_get_payload_format(newaudiortp, codec))) {
  9888. unsigned int bit_rate;
  9889. struct ast_format *format_parsed;
  9890. format_parsed = ast_format_parse_sdp_fmtp(format, fmtp_string);
  9891. if (format_parsed) {
  9892. ast_rtp_codecs_payload_replace_format(newaudiortp, codec, format_parsed);
  9893. ao2_replace(format, format_parsed);
  9894. ao2_ref(format_parsed, -1);
  9895. found = TRUE;
  9896. } else {
  9897. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  9898. }
  9899. if (ast_format_cmp(format, ast_format_siren7) == AST_FORMAT_CMP_EQUAL) {
  9900. if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
  9901. if (bit_rate != 32000) {
  9902. ast_log(LOG_WARNING, "Got Siren7 offer at %u bps, but only 32000 bps supported; ignoring.\n", bit_rate);
  9903. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  9904. } else {
  9905. found = TRUE;
  9906. }
  9907. }
  9908. } else if (ast_format_cmp(format, ast_format_siren14) == AST_FORMAT_CMP_EQUAL) {
  9909. if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
  9910. if (bit_rate != 48000) {
  9911. ast_log(LOG_WARNING, "Got Siren14 offer at %u bps, but only 48000 bps supported; ignoring.\n", bit_rate);
  9912. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  9913. } else {
  9914. found = TRUE;
  9915. }
  9916. }
  9917. } else if (ast_format_cmp(format, ast_format_g719) == AST_FORMAT_CMP_EQUAL) {
  9918. if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
  9919. if (bit_rate != 64000) {
  9920. ast_log(LOG_WARNING, "Got G.719 offer at %u bps, but only 64000 bps supported; ignoring.\n", bit_rate);
  9921. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  9922. } else {
  9923. found = TRUE;
  9924. }
  9925. }
  9926. }
  9927. ao2_ref(format, -1);
  9928. }
  9929. }
  9930. return found;
  9931. }
  9932. static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
  9933. {
  9934. int found = FALSE;
  9935. unsigned int codec;
  9936. char mimeSubtype[128];
  9937. unsigned int sample_rate;
  9938. int debug = sip_debug_test_pvt(p);
  9939. char fmtp_string[256];
  9940. if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
  9941. /* We have a rtpmap to handle */
  9942. if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
  9943. /* Note: should really look at the '#chans' params too */
  9944. if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)
  9945. || !strncasecmp(mimeSubtype, "VP8", 3)) {
  9946. if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
  9947. if (debug)
  9948. ast_verbose("Found video description format %s for ID %u\n", mimeSubtype, codec);
  9949. //found_rtpmap_codecs[last_rtpmap_codec] = codec;
  9950. (*last_rtpmap_codec)++;
  9951. found = TRUE;
  9952. } else {
  9953. ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
  9954. if (debug)
  9955. ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
  9956. }
  9957. }
  9958. } else {
  9959. if (debug)
  9960. ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
  9961. }
  9962. } else if (sscanf(a, "fmtp: %30u %255[^\t\n]", &codec, fmtp_string) == 2) {
  9963. struct ast_format *format;
  9964. if ((format = ast_rtp_codecs_get_payload_format(newvideortp, codec))) {
  9965. struct ast_format *format_parsed;
  9966. format_parsed = ast_format_parse_sdp_fmtp(format, fmtp_string);
  9967. if (format_parsed) {
  9968. ast_rtp_codecs_payload_replace_format(newvideortp, codec, format_parsed);
  9969. ao2_replace(format, format_parsed);
  9970. ao2_ref(format_parsed, -1);
  9971. found = TRUE;
  9972. } else {
  9973. ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
  9974. }
  9975. ao2_ref(format, -1);
  9976. }
  9977. }
  9978. return found;
  9979. }
  9980. 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)
  9981. {
  9982. int found = FALSE;
  9983. unsigned int codec;
  9984. char mimeSubtype[128];
  9985. unsigned int sample_rate;
  9986. char *red_cp;
  9987. int debug = sip_debug_test_pvt(p);
  9988. if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
  9989. /* We have a rtpmap to handle */
  9990. if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
  9991. if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
  9992. if (p->trtp) {
  9993. /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
  9994. ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
  9995. found = TRUE;
  9996. }
  9997. } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
  9998. if (p->trtp) {
  9999. ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
  10000. sprintf(red_fmtp, "fmtp:%u ", codec);
  10001. if (debug)
  10002. ast_verbose("RED submimetype has payload type: %u\n", codec);
  10003. found = TRUE;
  10004. }
  10005. }
  10006. } else {
  10007. if (debug)
  10008. ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
  10009. }
  10010. } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
  10011. /* count numbers of generations in fmtp */
  10012. red_cp = &red_fmtp[strlen(red_fmtp)];
  10013. strncpy(red_fmtp, a, 100);
  10014. sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
  10015. red_cp = strtok(red_cp, "/");
  10016. while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
  10017. sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
  10018. red_cp = strtok(NULL, "/");
  10019. }
  10020. red_cp = red_fmtp;
  10021. found = TRUE;
  10022. }
  10023. return found;
  10024. }
  10025. static int process_sdp_a_image(const char *a, struct sip_pvt *p)
  10026. {
  10027. int found = FALSE;
  10028. char s[256];
  10029. unsigned int x;
  10030. char *attrib = ast_strdupa(a);
  10031. char *pos;
  10032. if (initialize_udptl(p)) {
  10033. return found;
  10034. }
  10035. /* Due to a typo in an IANA registration of one of the T.38 attributes,
  10036. * RFC5347 section 2.5.2 recommends that all T.38 attributes be parsed in
  10037. * a case insensitive manner. Hence, the importance of proof reading (and
  10038. * code reviews).
  10039. */
  10040. for (pos = attrib; *pos; ++pos) {
  10041. *pos = tolower(*pos);
  10042. }
  10043. if ((sscanf(attrib, "t38faxmaxbuffer:%30u", &x) == 1)) {
  10044. ast_debug(3, "MaxBufferSize:%u\n", x);
  10045. found = TRUE;
  10046. } else if ((sscanf(attrib, "t38maxbitrate:%30u", &x) == 1) || (sscanf(attrib, "t38faxmaxrate:%30u", &x) == 1)) {
  10047. ast_debug(3, "T38MaxBitRate: %u\n", x);
  10048. switch (x) {
  10049. case 14400:
  10050. p->t38.their_parms.rate = AST_T38_RATE_14400;
  10051. break;
  10052. case 12000:
  10053. p->t38.their_parms.rate = AST_T38_RATE_12000;
  10054. break;
  10055. case 9600:
  10056. p->t38.their_parms.rate = AST_T38_RATE_9600;
  10057. break;
  10058. case 7200:
  10059. p->t38.their_parms.rate = AST_T38_RATE_7200;
  10060. break;
  10061. case 4800:
  10062. p->t38.their_parms.rate = AST_T38_RATE_4800;
  10063. break;
  10064. case 2400:
  10065. p->t38.their_parms.rate = AST_T38_RATE_2400;
  10066. break;
  10067. }
  10068. found = TRUE;
  10069. } else if ((sscanf(attrib, "t38faxversion:%30u", &x) == 1)) {
  10070. ast_debug(3, "FaxVersion: %u\n", x);
  10071. p->t38.their_parms.version = x;
  10072. found = TRUE;
  10073. } else if ((sscanf(attrib, "t38faxmaxdatagram:%30u", &x) == 1) || (sscanf(attrib, "t38maxdatagram:%30u", &x) == 1)) {
  10074. /* override the supplied value if the configuration requests it */
  10075. if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
  10076. ast_debug(1, "Overriding T38FaxMaxDatagram '%u' with '%d'\n", x, p->t38_maxdatagram);
  10077. x = p->t38_maxdatagram;
  10078. }
  10079. ast_debug(3, "FaxMaxDatagram: %u\n", x);
  10080. ast_udptl_set_far_max_datagram(p->udptl, x);
  10081. found = TRUE;
  10082. } else if ((strncmp(attrib, "t38faxfillbitremoval", sizeof("t38faxfillbitremoval") - 1) == 0)) {
  10083. if (sscanf(attrib, "t38faxfillbitremoval:%30u", &x) == 1) {
  10084. ast_debug(3, "FillBitRemoval: %u\n", x);
  10085. if (x == 1) {
  10086. p->t38.their_parms.fill_bit_removal = TRUE;
  10087. }
  10088. } else {
  10089. ast_debug(3, "FillBitRemoval\n");
  10090. p->t38.their_parms.fill_bit_removal = TRUE;
  10091. }
  10092. found = TRUE;
  10093. } else if ((strncmp(attrib, "t38faxtranscodingmmr", sizeof("t38faxtranscodingmmr") - 1) == 0)) {
  10094. if (sscanf(attrib, "t38faxtranscodingmmr:%30u", &x) == 1) {
  10095. ast_debug(3, "Transcoding MMR: %u\n", x);
  10096. if (x == 1) {
  10097. p->t38.their_parms.transcoding_mmr = TRUE;
  10098. }
  10099. } else {
  10100. ast_debug(3, "Transcoding MMR\n");
  10101. p->t38.their_parms.transcoding_mmr = TRUE;
  10102. }
  10103. found = TRUE;
  10104. } else if ((strncmp(attrib, "t38faxtranscodingjbig", sizeof("t38faxtranscodingjbig") - 1) == 0)) {
  10105. if (sscanf(attrib, "t38faxtranscodingjbig:%30u", &x) == 1) {
  10106. ast_debug(3, "Transcoding JBIG: %u\n", x);
  10107. if (x == 1) {
  10108. p->t38.their_parms.transcoding_jbig = TRUE;
  10109. }
  10110. } else {
  10111. ast_debug(3, "Transcoding JBIG\n");
  10112. p->t38.their_parms.transcoding_jbig = TRUE;
  10113. }
  10114. found = TRUE;
  10115. } else if ((sscanf(attrib, "t38faxratemanagement:%255s", s) == 1)) {
  10116. ast_debug(3, "RateManagement: %s\n", s);
  10117. if (!strcasecmp(s, "localTCF"))
  10118. p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
  10119. else if (!strcasecmp(s, "transferredTCF"))
  10120. p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
  10121. found = TRUE;
  10122. } else if ((sscanf(attrib, "t38faxudpec:%255s", s) == 1)) {
  10123. ast_debug(3, "UDP EC: %s\n", s);
  10124. if (!strcasecmp(s, "t38UDPRedundancy")) {
  10125. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
  10126. } else if (!strcasecmp(s, "t38UDPFEC")) {
  10127. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
  10128. } else {
  10129. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
  10130. }
  10131. found = TRUE;
  10132. }
  10133. return found;
  10134. }
  10135. /*! \brief Add "Supported" header to sip message. Since some options may
  10136. * be disabled in the config, the sip_pvt must be inspected to determine what
  10137. * is supported for this dialog. */
  10138. static int add_supported(struct sip_pvt *pvt, struct sip_request *req)
  10139. {
  10140. char supported_value[SIPBUFSIZE];
  10141. int res;
  10142. sprintf(supported_value, "replaces%s%s",
  10143. (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) ? ", timer" : "",
  10144. ast_test_flag(&pvt->flags[0], SIP_USEPATH) ? ", path" : "");
  10145. res = add_header(req, "Supported", supported_value);
  10146. return res;
  10147. }
  10148. /*! \brief Add header to SIP message */
  10149. static int add_header(struct sip_request *req, const char *var, const char *value)
  10150. {
  10151. if (req->headers == SIP_MAX_HEADERS) {
  10152. ast_log(LOG_WARNING, "Out of SIP header space\n");
  10153. return -1;
  10154. }
  10155. if (req->lines) {
  10156. ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
  10157. return -1;
  10158. }
  10159. if (sip_cfg.compactheaders) {
  10160. var = find_alias(var, var);
  10161. }
  10162. ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
  10163. req->header[req->headers] = ast_str_strlen(req->data);
  10164. req->headers++;
  10165. return 0;
  10166. }
  10167. /*!
  10168. * \pre dialog is assumed to be locked while calling this function
  10169. * \brief Add 'Max-Forwards' header to SIP message
  10170. */
  10171. static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
  10172. {
  10173. char clen[10];
  10174. snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
  10175. return add_header(req, "Max-Forwards", clen);
  10176. }
  10177. /*! \brief Add 'Content-Length' header and content to SIP message */
  10178. static int finalize_content(struct sip_request *req)
  10179. {
  10180. char clen[10];
  10181. if (req->lines) {
  10182. ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
  10183. return -1;
  10184. }
  10185. snprintf(clen, sizeof(clen), "%zu", ast_str_strlen(req->content));
  10186. add_header(req, "Content-Length", clen);
  10187. if (ast_str_strlen(req->content)) {
  10188. ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
  10189. }
  10190. req->lines = ast_str_strlen(req->content) ? 1 : 0;
  10191. return 0;
  10192. }
  10193. /*! \brief Add content (not header) to SIP message */
  10194. static int add_content(struct sip_request *req, const char *line)
  10195. {
  10196. if (req->lines) {
  10197. ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
  10198. return -1;
  10199. }
  10200. ast_str_append(&req->content, 0, "%s", line);
  10201. return 0;
  10202. }
  10203. /*! \brief Copy one header field from one request to another */
  10204. static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
  10205. {
  10206. const char *tmp = sip_get_header(orig, field);
  10207. if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
  10208. return add_header(req, field, tmp);
  10209. ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
  10210. return -1;
  10211. }
  10212. /*! \brief Copy all headers from one request to another */
  10213. static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
  10214. {
  10215. int start = 0;
  10216. int copied = 0;
  10217. for (;;) {
  10218. const char *tmp = __get_header(orig, field, &start);
  10219. if (ast_strlen_zero(tmp))
  10220. break;
  10221. /* Add what we're responding to */
  10222. add_header(req, field, tmp);
  10223. copied++;
  10224. }
  10225. return copied ? 0 : -1;
  10226. }
  10227. /*! \brief Copy SIP VIA Headers from the request to the response
  10228. \note If the client indicates that it wishes to know the port we received from,
  10229. it adds ;rport without an argument to the topmost via header. We need to
  10230. add the port number (from our point of view) to that parameter.
  10231. \verbatim
  10232. We always add ;received=<ip address> to the topmost via header.
  10233. \endverbatim
  10234. Received: RFC 3261, rport RFC 3581 */
  10235. static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
  10236. {
  10237. int copied = 0;
  10238. int start = 0;
  10239. for (;;) {
  10240. char new[512];
  10241. const char *oh = __get_header(orig, field, &start);
  10242. if (ast_strlen_zero(oh))
  10243. break;
  10244. if (!copied) { /* Only check for empty rport in topmost via header */
  10245. char leftmost[512], *others, *rport;
  10246. /* Only work on leftmost value */
  10247. ast_copy_string(leftmost, oh, sizeof(leftmost));
  10248. others = strchr(leftmost, ',');
  10249. if (others)
  10250. *others++ = '\0';
  10251. /* Find ;rport; (empty request) */
  10252. rport = strstr(leftmost, ";rport");
  10253. if (rport && *(rport+6) == '=')
  10254. rport = NULL; /* We already have a parameter to rport */
  10255. if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
  10256. /* We need to add received port - rport */
  10257. char *end;
  10258. rport = strstr(leftmost, ";rport");
  10259. if (rport) {
  10260. end = strchr(rport + 1, ';');
  10261. if (end)
  10262. memmove(rport, end, strlen(end) + 1);
  10263. else
  10264. *rport = '\0';
  10265. }
  10266. /* Add rport to first VIA header if requested */
  10267. snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
  10268. leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
  10269. ast_sockaddr_port(&p->recv),
  10270. others ? "," : "", others ? others : "");
  10271. } else {
  10272. /* We should *always* add a received to the topmost via */
  10273. snprintf(new, sizeof(new), "%s;received=%s%s%s",
  10274. leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
  10275. others ? "," : "", others ? others : "");
  10276. }
  10277. oh = new; /* the header to copy */
  10278. } /* else add the following via headers untouched */
  10279. add_header(req, field, oh);
  10280. copied++;
  10281. }
  10282. if (!copied) {
  10283. ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
  10284. return -1;
  10285. }
  10286. return 0;
  10287. }
  10288. /*! \brief Add route header into request per learned route */
  10289. static void add_route(struct sip_request *req, struct sip_route *route, int skip)
  10290. {
  10291. struct ast_str *r;
  10292. if (sip_route_empty(route)) {
  10293. return;
  10294. }
  10295. if ((r = sip_route_list(route, 0, skip))) {
  10296. if (ast_str_strlen(r)) {
  10297. add_header(req, "Route", ast_str_buffer(r));
  10298. }
  10299. ast_free(r);
  10300. }
  10301. }
  10302. /*! \brief Set destination from SIP URI
  10303. *
  10304. * Parse uri to h (host) and port - uri is already just the part inside the <>
  10305. * general form we are expecting is \verbatim sip[s]:username[:password][;parameter]@host[:port][;...] \endverbatim
  10306. * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
  10307. * for SIP: uri's
  10308. *
  10309. * If there's a sips: uri scheme, TLS will be required.
  10310. */
  10311. static void set_destination(struct sip_pvt *p, const char *uri)
  10312. {
  10313. char *trans, *maddr, hostname[256];
  10314. const char *h;
  10315. int hn;
  10316. int debug=sip_debug_test_pvt(p);
  10317. int tls_on = FALSE;
  10318. if (debug)
  10319. ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
  10320. if ((trans = strcasestr(uri, ";transport="))) {
  10321. trans += strlen(";transport=");
  10322. if (!strncasecmp(trans, "ws", 2)) {
  10323. if (debug)
  10324. ast_verbose("set_destination: URI is for WebSocket, we can't set destination\n");
  10325. return;
  10326. }
  10327. }
  10328. /* Find and parse hostname */
  10329. h = strchr(uri, '@');
  10330. if (h)
  10331. ++h;
  10332. else {
  10333. h = uri;
  10334. if (!strncasecmp(h, "sip:", 4)) {
  10335. h += 4;
  10336. } else if (!strncasecmp(h, "sips:", 5)) {
  10337. h += 5;
  10338. tls_on = TRUE;
  10339. }
  10340. }
  10341. hn = strcspn(h, ";>") + 1;
  10342. if (hn > sizeof(hostname))
  10343. hn = sizeof(hostname);
  10344. ast_copy_string(hostname, h, hn);
  10345. /* XXX bug here if string has been trimmed to sizeof(hostname) */
  10346. h += hn - 1;
  10347. /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
  10348. * otherwise, just look for A records */
  10349. if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
  10350. ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
  10351. return;
  10352. }
  10353. /* Got the hostname - but maybe there's a "maddr=" to override address? */
  10354. maddr = strstr(h, "maddr=");
  10355. if (maddr) {
  10356. int port;
  10357. maddr += 6;
  10358. hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  10359. "0123456789-.:[]") + 1;
  10360. if (hn > sizeof(hostname))
  10361. hn = sizeof(hostname);
  10362. ast_copy_string(hostname, maddr, hn);
  10363. port = ast_sockaddr_port(&p->sa);
  10364. /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
  10365. * NAPTR/SRV, otherwise, just look for A records */
  10366. if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
  10367. ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
  10368. return;
  10369. }
  10370. ast_sockaddr_set_port(&p->sa, port);
  10371. }
  10372. if (!ast_sockaddr_port(&p->sa)) {
  10373. ast_sockaddr_set_port(&p->sa, tls_on ?
  10374. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  10375. }
  10376. if (debug) {
  10377. ast_verbose("set_destination: set destination to %s\n",
  10378. ast_sockaddr_stringify(&p->sa));
  10379. }
  10380. }
  10381. /*! \brief Initialize SIP response, based on SIP request */
  10382. static int init_resp(struct sip_request *resp, const char *msg)
  10383. {
  10384. /* Initialize a response */
  10385. memset(resp, 0, sizeof(*resp));
  10386. resp->method = SIP_RESPONSE;
  10387. if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
  10388. goto e_return;
  10389. if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
  10390. goto e_free_data;
  10391. resp->header[0] = 0;
  10392. ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
  10393. resp->headers++;
  10394. return 0;
  10395. e_free_data:
  10396. ast_free(resp->data);
  10397. resp->data = NULL;
  10398. e_return:
  10399. return -1;
  10400. }
  10401. /*! \brief Initialize SIP request */
  10402. static int init_req(struct sip_request *req, int sipmethod, const char *recip)
  10403. {
  10404. /* Initialize a request */
  10405. memset(req, 0, sizeof(*req));
  10406. if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
  10407. goto e_return;
  10408. if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
  10409. goto e_free_data;
  10410. req->method = sipmethod;
  10411. req->header[0] = 0;
  10412. ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
  10413. req->headers++;
  10414. return 0;
  10415. e_free_data:
  10416. ast_free(req->data);
  10417. req->data = NULL;
  10418. e_return:
  10419. return -1;
  10420. }
  10421. /*! \brief Deinitialize SIP response/request */
  10422. static void deinit_req(struct sip_request *req)
  10423. {
  10424. if (req->data) {
  10425. ast_free(req->data);
  10426. req->data = NULL;
  10427. }
  10428. if (req->content) {
  10429. ast_free(req->content);
  10430. req->content = NULL;
  10431. }
  10432. }
  10433. /*! \brief Test if this response needs a contact header */
  10434. static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
  10435. /* Requirements for Contact header inclusion in responses generated
  10436. * from the header tables found in the following RFCs. Where the
  10437. * Contact header was marked mandatory (m) or optional (o) this
  10438. * function returns 1.
  10439. *
  10440. * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
  10441. * - RFC 2976 (INFO)
  10442. * - RFC 3262 (PRACK)
  10443. * - RFC 3265 (SUBSCRIBE, NOTIFY)
  10444. * - RFC 3311 (UPDATE)
  10445. * - RFC 3428 (MESSAGE)
  10446. * - RFC 3515 (REFER)
  10447. * - RFC 3903 (PUBLISH)
  10448. */
  10449. switch (method) {
  10450. /* 1xx, 2xx, 3xx, 485 */
  10451. case SIP_INVITE:
  10452. case SIP_UPDATE:
  10453. case SIP_SUBSCRIBE:
  10454. case SIP_NOTIFY:
  10455. if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
  10456. return 1;
  10457. break;
  10458. /* 2xx, 3xx, 485 */
  10459. case SIP_REGISTER:
  10460. case SIP_OPTIONS:
  10461. if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
  10462. return 1;
  10463. break;
  10464. /* 3xx, 485 */
  10465. case SIP_BYE:
  10466. case SIP_PRACK:
  10467. case SIP_MESSAGE:
  10468. case SIP_PUBLISH:
  10469. if (msg[0] == '3' || !strncmp(msg, "485", 3))
  10470. return 1;
  10471. break;
  10472. /* 2xx, 3xx, 4xx, 5xx, 6xx */
  10473. case SIP_REFER:
  10474. if (msg[0] >= '2' && msg[0] <= '6')
  10475. return 1;
  10476. break;
  10477. /* contact will not be included for everything else */
  10478. case SIP_ACK:
  10479. case SIP_CANCEL:
  10480. case SIP_INFO:
  10481. case SIP_PING:
  10482. default:
  10483. return 0;
  10484. }
  10485. return 0;
  10486. }
  10487. /*! \brief Prepare SIP response packet */
  10488. static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
  10489. {
  10490. char newto[256];
  10491. const char *ot;
  10492. init_resp(resp, msg);
  10493. copy_via_headers(p, resp, req, "Via");
  10494. if (msg[0] == '1' || msg[0] == '2')
  10495. copy_all_header(resp, req, "Record-Route");
  10496. copy_header(resp, req, "From");
  10497. ot = sip_get_header(req, "To");
  10498. if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
  10499. /* Add the proper tag if we don't have it already. If they have specified
  10500. their tag, use it. Otherwise, use our own tag */
  10501. if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
  10502. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
  10503. else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
  10504. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
  10505. else
  10506. ast_copy_string(newto, ot, sizeof(newto));
  10507. ot = newto;
  10508. }
  10509. add_header(resp, "To", ot);
  10510. copy_header(resp, req, "Call-ID");
  10511. copy_header(resp, req, "CSeq");
  10512. if (!ast_strlen_zero(global_useragent))
  10513. add_header(resp, "Server", global_useragent);
  10514. add_header(resp, "Allow", ALLOWED_METHODS);
  10515. add_supported(p, resp);
  10516. /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
  10517. if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE) {
  10518. char se_hdr[256];
  10519. snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
  10520. p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
  10521. add_header(resp, "Session-Expires", se_hdr);
  10522. /* RFC 2048, Section 9
  10523. * If the refresher parameter in the Session-Expires header field in the
  10524. * 2xx response has a value of 'uac', the UAS MUST place a Require
  10525. * header field into the response with the value 'timer'.
  10526. * ...
  10527. * If the refresher parameter in
  10528. * the 2xx response has a value of 'uas' and the Supported header field
  10529. * in the request contained the value 'timer', the UAS SHOULD place a
  10530. * Require header field into the response with the value 'timer'
  10531. */
  10532. if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_THEM ||
  10533. (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US &&
  10534. p->stimer->st_active_peer_ua == TRUE)) {
  10535. resp->reqsipoptions |= SIP_OPT_TIMER;
  10536. }
  10537. }
  10538. if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
  10539. /* For registration responses, we also need expiry and
  10540. contact info */
  10541. add_expires(resp, p->expiry);
  10542. if (p->expiry) { /* Only add contact if we have an expiry time */
  10543. char contact[SIPBUFSIZE];
  10544. const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
  10545. char *brackets = strchr(contact_uri, '<');
  10546. snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
  10547. add_header(resp, "Contact", contact); /* Not when we unregister */
  10548. }
  10549. if (p->method == SIP_REGISTER && ast_test_flag(&p->flags[0], SIP_USEPATH)) {
  10550. copy_header(resp, req, "Path");
  10551. }
  10552. } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
  10553. add_header(resp, "Contact", p->our_contact);
  10554. }
  10555. if (!ast_strlen_zero(p->url)) {
  10556. add_header(resp, "Access-URL", p->url);
  10557. ast_string_field_set(p, url, NULL);
  10558. }
  10559. /* default to routing the response to the address where the request
  10560. * came from. Since we don't have a transport layer, we do this here.
  10561. * The process_via() function will update the port to either the port
  10562. * specified in the via header or the default port later on (per RFC
  10563. * 3261 section 18.2.2).
  10564. */
  10565. p->sa = p->recv;
  10566. if (process_via(p, req)) {
  10567. ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
  10568. }
  10569. return 0;
  10570. }
  10571. /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
  10572. static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
  10573. {
  10574. struct sip_request *orig = &p->initreq;
  10575. char stripped[80];
  10576. char tmp[80];
  10577. char newto[256];
  10578. const char *c;
  10579. const char *ot, *of;
  10580. int is_strict = FALSE; /*!< Strict routing flag */
  10581. int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING); /* Session direction */
  10582. snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
  10583. if (!seqno) {
  10584. p->ocseq++;
  10585. seqno = p->ocseq;
  10586. }
  10587. /* A CANCEL must have the same branch as the INVITE that it is canceling. */
  10588. if (sipmethod == SIP_CANCEL) {
  10589. p->branch = p->invite_branch;
  10590. build_via(p);
  10591. } else if (newbranch && (sipmethod == SIP_INVITE)) {
  10592. p->branch ^= ast_random();
  10593. p->invite_branch = p->branch;
  10594. build_via(p);
  10595. } else if (newbranch) {
  10596. p->branch ^= ast_random();
  10597. build_via(p);
  10598. }
  10599. /* Check for strict or loose router */
  10600. if (sip_route_is_strict(&p->route)) {
  10601. is_strict = TRUE;
  10602. if (sipdebug)
  10603. ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
  10604. }
  10605. if (sipmethod == SIP_CANCEL) {
  10606. c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2); /* Use original URI */
  10607. } else if (sipmethod == SIP_ACK) {
  10608. /* Use URI from Contact: in 200 OK (if INVITE)
  10609. (we only have the contacturi on INVITEs) */
  10610. if (!ast_strlen_zero(p->okcontacturi)) {
  10611. c = is_strict ? sip_route_first_uri(&p->route) : p->okcontacturi;
  10612. } else {
  10613. c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
  10614. }
  10615. } else if (!ast_strlen_zero(p->okcontacturi)) {
  10616. /* Use for BYE or REINVITE */
  10617. c = is_strict ? sip_route_first_uri(&p->route) : p->okcontacturi;
  10618. } else if (!ast_strlen_zero(p->uri)) {
  10619. c = p->uri;
  10620. } else {
  10621. char *n;
  10622. /* We have no URI, use To: or From: header as URI (depending on direction) */
  10623. ast_copy_string(stripped, sip_get_header(orig, is_outbound ? "To" : "From"),
  10624. sizeof(stripped));
  10625. n = get_in_brackets(stripped);
  10626. c = remove_uri_parameters(n);
  10627. }
  10628. init_req(req, sipmethod, c);
  10629. snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
  10630. add_header(req, "Via", p->via);
  10631. /*
  10632. * Use the learned route set unless this is a CANCEL on an ACK for a non-2xx
  10633. * final response. For a CANCEL or ACK, we have to send to the same destination
  10634. * as the original INVITE.
  10635. */
  10636. if (!sip_route_empty(&p->route) &&
  10637. !(sipmethod == SIP_CANCEL ||
  10638. (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)))) {
  10639. if (p->socket.type != AST_TRANSPORT_UDP && p->socket.tcptls_session) {
  10640. /* For TCP/TLS sockets that are connected we won't need
  10641. * to do any hostname/IP lookups */
  10642. } else if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
  10643. /* For NATed traffic, we ignore the contact/route and
  10644. * simply send to the received-from address. No need
  10645. * for lookups. */
  10646. } else {
  10647. set_destination(p, sip_route_first_uri(&p->route));
  10648. }
  10649. add_route(req, &p->route, is_strict ? 1 : 0);
  10650. }
  10651. add_max_forwards(p, req);
  10652. ot = sip_get_header(orig, "To");
  10653. of = sip_get_header(orig, "From");
  10654. /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
  10655. as our original request, including tag (or presumably lack thereof) */
  10656. if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
  10657. /* Add the proper tag if we don't have it already. If they have specified
  10658. their tag, use it. Otherwise, use our own tag */
  10659. if (is_outbound && !ast_strlen_zero(p->theirtag))
  10660. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
  10661. else if (!is_outbound)
  10662. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
  10663. else
  10664. snprintf(newto, sizeof(newto), "%s", ot);
  10665. ot = newto;
  10666. }
  10667. if (is_outbound) {
  10668. add_header(req, "From", of);
  10669. add_header(req, "To", ot);
  10670. } else {
  10671. add_header(req, "From", ot);
  10672. add_header(req, "To", of);
  10673. }
  10674. /* Do not add Contact for MESSAGE, BYE and Cancel requests */
  10675. if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
  10676. add_header(req, "Contact", p->our_contact);
  10677. copy_header(req, orig, "Call-ID");
  10678. add_header(req, "CSeq", tmp);
  10679. if (!ast_strlen_zero(global_useragent))
  10680. add_header(req, "User-Agent", global_useragent);
  10681. if (!ast_strlen_zero(p->url)) {
  10682. add_header(req, "Access-URL", p->url);
  10683. ast_string_field_set(p, url, NULL);
  10684. }
  10685. /* Add Session-Timers related headers if the feature is active for this session.
  10686. An exception to this behavior is the ACK request. Since Asterisk never requires
  10687. session-timers support from a remote end-point (UAS) in an INVITE, it must
  10688. not send 'Require: timer' header in the ACK request.
  10689. This should only be added in the INVITE transactions, not MESSAGE or REFER or other
  10690. in-dialog messages.
  10691. */
  10692. if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
  10693. && sipmethod == SIP_INVITE) {
  10694. char se_hdr[256];
  10695. snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
  10696. p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
  10697. add_header(req, "Session-Expires", se_hdr);
  10698. snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
  10699. add_header(req, "Min-SE", se_hdr);
  10700. }
  10701. return 0;
  10702. }
  10703. /*! \brief Base transmit response function */
  10704. static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
  10705. {
  10706. struct sip_request resp;
  10707. uint32_t seqno = 0;
  10708. if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
  10709. ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
  10710. return -1;
  10711. }
  10712. respprep(&resp, p, msg, req);
  10713. if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
  10714. && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
  10715. && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
  10716. ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  10717. add_rpid(&resp, p);
  10718. }
  10719. if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
  10720. add_cc_call_info_to_response(p, &resp);
  10721. }
  10722. /* If we are sending a 302 Redirect we can add a diversion header if the redirect information is set */
  10723. if (!strncmp(msg, "302", 3)) {
  10724. add_diversion(&resp, p);
  10725. }
  10726. /* If we are cancelling an incoming invite for some reason, add information
  10727. about the reason why we are doing this in clear text */
  10728. if (p->method == SIP_INVITE && msg[0] != '1') {
  10729. char buf[20];
  10730. if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
  10731. int hangupcause = 0;
  10732. if (p->owner && ast_channel_hangupcause(p->owner)) {
  10733. hangupcause = ast_channel_hangupcause(p->owner);
  10734. } else if (p->hangupcause) {
  10735. hangupcause = p->hangupcause;
  10736. } else {
  10737. int respcode;
  10738. if (sscanf(msg, "%30d ", &respcode))
  10739. hangupcause = hangup_sip2cause(respcode);
  10740. }
  10741. if (hangupcause) {
  10742. sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
  10743. add_header(&resp, "Reason", buf);
  10744. }
  10745. }
  10746. if (p->owner && ast_channel_hangupcause(p->owner)) {
  10747. add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(ast_channel_hangupcause(p->owner)));
  10748. snprintf(buf, sizeof(buf), "%d", ast_channel_hangupcause(p->owner));
  10749. add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
  10750. }
  10751. }
  10752. return send_response(p, &resp, reliable, seqno);
  10753. }
  10754. 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)
  10755. {
  10756. struct sip_request resp;
  10757. if (need_new_etag) {
  10758. create_new_sip_etag(esc_entry, 1);
  10759. }
  10760. respprep(&resp, p, msg, req);
  10761. add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
  10762. return send_response(p, &resp, 0, 0);
  10763. }
  10764. static int temp_pvt_init(void *data)
  10765. {
  10766. struct sip_pvt *p = data;
  10767. p->do_history = 0; /* XXX do we need it ? isn't already all 0 ? */
  10768. return ast_string_field_init(p, 512);
  10769. }
  10770. static void temp_pvt_cleanup(void *data)
  10771. {
  10772. struct sip_pvt *p = data;
  10773. ast_string_field_free_memory(p);
  10774. ast_free(data);
  10775. }
  10776. /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
  10777. 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)
  10778. {
  10779. struct sip_pvt *p = NULL;
  10780. if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
  10781. ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
  10782. return -1;
  10783. }
  10784. /* XXX the structure may be dirty from previous usage.
  10785. * Here we should state clearly how we should reinitialize it
  10786. * before using it.
  10787. * E.g. certainly the threadstorage should be left alone,
  10788. * but other thihngs such as flags etc. maybe need cleanup ?
  10789. */
  10790. /* Initialize the bare minimum */
  10791. p->method = intended_method;
  10792. if (!addr) {
  10793. ast_sockaddr_copy(&p->ourip, &internip);
  10794. } else {
  10795. ast_sockaddr_copy(&p->sa, addr);
  10796. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  10797. }
  10798. p->branch = ast_random();
  10799. make_our_tag(p);
  10800. p->ocseq = INITIAL_CSEQ;
  10801. if (useglobal_nat && addr) {
  10802. ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
  10803. ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT);
  10804. ast_sockaddr_copy(&p->recv, addr);
  10805. check_via(p, req);
  10806. }
  10807. ast_string_field_set(p, fromdomain, default_fromdomain);
  10808. p->fromdomainport = default_fromdomainport;
  10809. build_via(p);
  10810. ast_string_field_set(p, callid, callid);
  10811. copy_socket_data(&p->socket, &req->socket);
  10812. /* Use this temporary pvt structure to send the message */
  10813. __transmit_response(p, msg, req, XMIT_UNRELIABLE);
  10814. /* Free the string fields, but not the pool space */
  10815. ast_string_field_init(p, 0);
  10816. return 0;
  10817. }
  10818. /*! \brief Transmit response, no retransmits */
  10819. static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
  10820. {
  10821. return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
  10822. }
  10823. /*! \brief Transmit response, no retransmits */
  10824. static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
  10825. {
  10826. struct sip_request resp;
  10827. respprep(&resp, p, msg, req);
  10828. add_date(&resp);
  10829. add_header(&resp, "Unsupported", unsupported);
  10830. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  10831. }
  10832. /*! \brief Transmit 422 response with Min-SE header (Session-Timers) */
  10833. static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
  10834. {
  10835. struct sip_request resp;
  10836. char minse_str[20];
  10837. respprep(&resp, p, msg, req);
  10838. add_date(&resp);
  10839. snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
  10840. add_header(&resp, "Min-SE", minse_str);
  10841. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  10842. }
  10843. /*! \brief Transmit response, Make sure you get an ACK
  10844. This is only used for responses to INVITEs, where we need to make sure we get an ACK
  10845. */
  10846. static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
  10847. {
  10848. return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
  10849. }
  10850. /*! \brief Add date header to SIP message */
  10851. static void add_date(struct sip_request *req)
  10852. {
  10853. char tmp[256];
  10854. struct tm tm;
  10855. time_t t = time(NULL);
  10856. gmtime_r(&t, &tm);
  10857. strftime(tmp, sizeof(tmp), "%a, %d %b %Y %T GMT", &tm);
  10858. add_header(req, "Date", tmp);
  10859. }
  10860. /*! \brief Add Expires header to SIP message */
  10861. static void add_expires(struct sip_request *req, int expires)
  10862. {
  10863. char tmp[32];
  10864. snprintf(tmp, sizeof(tmp), "%d", expires);
  10865. add_header(req, "Expires", tmp);
  10866. }
  10867. /*! \brief Append Retry-After header field when transmitting response */
  10868. static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
  10869. {
  10870. struct sip_request resp;
  10871. respprep(&resp, p, msg, req);
  10872. add_header(&resp, "Retry-After", seconds);
  10873. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  10874. }
  10875. /*! \brief Add date before transmitting response */
  10876. static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
  10877. {
  10878. struct sip_request resp;
  10879. respprep(&resp, p, msg, req);
  10880. add_date(&resp);
  10881. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  10882. }
  10883. /*! \brief Append Accept header, content length before transmitting response */
  10884. static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
  10885. {
  10886. struct sip_request resp;
  10887. respprep(&resp, p, msg, req);
  10888. add_header(&resp, "Accept", "application/sdp");
  10889. return send_response(p, &resp, reliable, 0);
  10890. }
  10891. /*! \brief Append Min-Expires header, content length before transmitting response */
  10892. static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minexpires)
  10893. {
  10894. struct sip_request resp;
  10895. char tmp[32];
  10896. snprintf(tmp, sizeof(tmp), "%d", minexpires);
  10897. respprep(&resp, p, msg, req);
  10898. add_header(&resp, "Min-Expires", tmp);
  10899. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  10900. }
  10901. /*! \brief Respond with authorization request */
  10902. 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)
  10903. {
  10904. struct sip_request resp;
  10905. char tmp[512];
  10906. uint32_t seqno = 0;
  10907. if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
  10908. ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
  10909. return -1;
  10910. }
  10911. /* Choose Realm */
  10912. get_realm(p, req);
  10913. /* Stale means that they sent us correct authentication, but
  10914. based it on an old challenge (nonce) */
  10915. snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, nonce, stale ? ", stale=true" : "");
  10916. respprep(&resp, p, msg, req);
  10917. add_header(&resp, header, tmp);
  10918. append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
  10919. return send_response(p, &resp, reliable, seqno);
  10920. }
  10921. /*!
  10922. \brief Extract domain from SIP To/From header
  10923. \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
  10924. \note TODO: Such code is all over SIP channel, there is a sense to organize
  10925. this patern in one function
  10926. */
  10927. static int get_domain(const char *str, char *domain, int len)
  10928. {
  10929. char tmpf[256];
  10930. char *a, *from;
  10931. *domain = '\0';
  10932. ast_copy_string(tmpf, str, sizeof(tmpf));
  10933. from = get_in_brackets(tmpf);
  10934. if (!ast_strlen_zero(from)) {
  10935. if (strncasecmp(from, "sip:", 4)) {
  10936. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
  10937. return -1;
  10938. }
  10939. from += 4;
  10940. } else
  10941. from = NULL;
  10942. if (from) {
  10943. int bracket = 0;
  10944. /* Strip any params or options from user */
  10945. if ((a = strchr(from, ';')))
  10946. *a = '\0';
  10947. /* Strip port from domain if present */
  10948. for (a = from; *a != '\0'; ++a) {
  10949. if (*a == ':' && bracket == 0) {
  10950. *a = '\0';
  10951. break;
  10952. } else if (*a == '[') {
  10953. ++bracket;
  10954. } else if (*a == ']') {
  10955. --bracket;
  10956. }
  10957. }
  10958. if ((a = strchr(from, '@'))) {
  10959. *a = '\0';
  10960. ast_copy_string(domain, a + 1, len);
  10961. } else
  10962. ast_copy_string(domain, from, len);
  10963. }
  10964. return ast_strlen_zero(domain);
  10965. }
  10966. /*!
  10967. \brief Choose realm based on From header and then To header or use globaly configured realm.
  10968. Realm from From/To header should be listed among served domains in config file: domain=...
  10969. */
  10970. static void get_realm(struct sip_pvt *p, const struct sip_request *req)
  10971. {
  10972. char domain[MAXHOSTNAMELEN];
  10973. if (!ast_strlen_zero(p->realm))
  10974. return;
  10975. if (sip_cfg.domainsasrealm &&
  10976. !AST_LIST_EMPTY(&domain_list))
  10977. {
  10978. /* Check From header first */
  10979. if (!get_domain(sip_get_header(req, "From"), domain, sizeof(domain))) {
  10980. if (check_sip_domain(domain, NULL, 0)) {
  10981. ast_string_field_set(p, realm, domain);
  10982. return;
  10983. }
  10984. }
  10985. /* Check To header */
  10986. if (!get_domain(sip_get_header(req, "To"), domain, sizeof(domain))) {
  10987. if (check_sip_domain(domain, NULL, 0)) {
  10988. ast_string_field_set(p, realm, domain);
  10989. return;
  10990. }
  10991. }
  10992. }
  10993. /* Use default realm from config file */
  10994. ast_string_field_set(p, realm, sip_cfg.realm);
  10995. }
  10996. /*!
  10997. * \internal
  10998. *
  10999. * \arg msg Only use a string constant for the msg, here, it is shallow copied
  11000. *
  11001. * \note assumes the sip_pvt is locked.
  11002. */
  11003. static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
  11004. {
  11005. int res;
  11006. if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
  11007. p->last_provisional = msg;
  11008. update_provisional_keepalive(p, with_sdp);
  11009. }
  11010. return res;
  11011. }
  11012. /*!
  11013. * \internal
  11014. * \brief Destroy all additional MESSAGE headers.
  11015. *
  11016. * \param pvt SIP private dialog struct.
  11017. *
  11018. * \return Nothing
  11019. */
  11020. static void destroy_msg_headers(struct sip_pvt *pvt)
  11021. {
  11022. struct sip_msg_hdr *doomed;
  11023. while ((doomed = AST_LIST_REMOVE_HEAD(&pvt->msg_headers, next))) {
  11024. ast_free(doomed);
  11025. }
  11026. }
  11027. /*!
  11028. * \internal
  11029. * \brief Add a MESSAGE header to the dialog.
  11030. *
  11031. * \param pvt SIP private dialog struct.
  11032. * \param hdr_name Name of header for MESSAGE.
  11033. * \param hdr_value Value of header for MESSAGE.
  11034. *
  11035. * \return Nothing
  11036. */
  11037. static void add_msg_header(struct sip_pvt *pvt, const char *hdr_name, const char *hdr_value)
  11038. {
  11039. size_t hdr_len_name;
  11040. size_t hdr_len_value;
  11041. struct sip_msg_hdr *node;
  11042. char *pos;
  11043. hdr_len_name = strlen(hdr_name) + 1;
  11044. hdr_len_value = strlen(hdr_value) + 1;
  11045. node = ast_calloc(1, sizeof(*node) + hdr_len_name + hdr_len_value);
  11046. if (!node) {
  11047. return;
  11048. }
  11049. pos = node->stuff;
  11050. node->name = pos;
  11051. strcpy(pos, hdr_name);
  11052. pos += hdr_len_name;
  11053. node->value = pos;
  11054. strcpy(pos, hdr_value);
  11055. AST_LIST_INSERT_TAIL(&pvt->msg_headers, node, next);
  11056. }
  11057. /*! \brief Add text body to SIP message */
  11058. static int add_text(struct sip_request *req, struct sip_pvt *p)
  11059. {
  11060. const char *content_type = NULL;
  11061. struct sip_msg_hdr *node;
  11062. /* Add any additional MESSAGE headers. */
  11063. AST_LIST_TRAVERSE(&p->msg_headers, node, next) {
  11064. if (!strcasecmp(node->name, "Content-Type")) {
  11065. /* Save content type */
  11066. content_type = node->value;
  11067. } else {
  11068. add_header(req, node->name, node->value);
  11069. }
  11070. }
  11071. if (ast_strlen_zero(content_type)) {
  11072. /* "Content-Type" not set - use default value */
  11073. content_type = "text/plain;charset=UTF-8";
  11074. }
  11075. add_header(req, "Content-Type", content_type);
  11076. /* XXX Convert \n's to \r\n's XXX */
  11077. add_content(req, p->msg_body);
  11078. return 0;
  11079. }
  11080. /*! \brief Add DTMF INFO tone to sip message
  11081. Mode = 0 for application/dtmf-relay (Cisco)
  11082. 1 for application/dtmf
  11083. */
  11084. static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
  11085. {
  11086. char tmp[256];
  11087. int event;
  11088. if (mode) {
  11089. /* Application/dtmf short version used by some implementations */
  11090. if ('0' <= digit && digit <= '9') {
  11091. event = digit - '0';
  11092. } else if (digit == '*') {
  11093. event = 10;
  11094. } else if (digit == '#') {
  11095. event = 11;
  11096. } else if ('A' <= digit && digit <= 'D') {
  11097. event = 12 + digit - 'A';
  11098. } else if ('a' <= digit && digit <= 'd') {
  11099. event = 12 + digit - 'a';
  11100. } else {
  11101. /* Unknown digit */
  11102. event = 0;
  11103. }
  11104. snprintf(tmp, sizeof(tmp), "%d\r\n", event);
  11105. add_header(req, "Content-Type", "application/dtmf");
  11106. add_content(req, tmp);
  11107. } else {
  11108. /* Application/dtmf-relay as documented by Cisco */
  11109. snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
  11110. add_header(req, "Content-Type", "application/dtmf-relay");
  11111. add_content(req, tmp);
  11112. }
  11113. return 0;
  11114. }
  11115. /*!
  11116. * \pre if p->owner exists, it must be locked
  11117. * \brief Add Remote-Party-ID header to SIP message
  11118. */
  11119. static int add_rpid(struct sip_request *req, struct sip_pvt *p)
  11120. {
  11121. struct ast_str *tmp = ast_str_alloca(256);
  11122. char tmp2[256];
  11123. char lid_name_buf[128];
  11124. char *lid_num;
  11125. char *lid_name;
  11126. int lid_pres;
  11127. const char *fromdomain;
  11128. const char *privacy = NULL;
  11129. const char *screen = NULL;
  11130. struct ast_party_id connected_id;
  11131. const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
  11132. if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
  11133. return 0;
  11134. }
  11135. if (!p->owner) {
  11136. return 0;
  11137. }
  11138. connected_id = ast_channel_connected_effective_id(p->owner);
  11139. lid_num = S_COR(connected_id.number.valid, connected_id.number.str, NULL);
  11140. if (!lid_num) {
  11141. return 0;
  11142. }
  11143. lid_name = S_COR(connected_id.name.valid, connected_id.name.str, NULL);
  11144. if (!lid_name) {
  11145. lid_name = lid_num;
  11146. }
  11147. ast_escape_quoted(lid_name, lid_name_buf, sizeof(lid_name_buf));
  11148. lid_pres = ast_party_id_presentation(&connected_id);
  11149. if (((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) &&
  11150. (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_NO)) {
  11151. /* If pres is not allowed and we don't trust the peer, we don't apply an RPID header */
  11152. return 0;
  11153. }
  11154. fromdomain = p->fromdomain;
  11155. if (!fromdomain ||
  11156. ((ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_YES) &&
  11157. !strcmp("anonymous.invalid", fromdomain))) {
  11158. /* If the fromdomain is NULL or if it was set to anonymous.invalid due to privacy settings and we trust the peer,
  11159. * use the host IP address */
  11160. fromdomain = ast_sockaddr_stringify_host_remote(&p->ourip);
  11161. }
  11162. lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), ast_uri_sip_user);
  11163. if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
  11164. if (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) != SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY) {
  11165. /* trust_id_outbound = yes - Always give full information even if it's private, but append a privacy header
  11166. * When private data is included */
  11167. ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name_buf, lid_num, fromdomain);
  11168. if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  11169. add_header(req, "Privacy", "id");
  11170. }
  11171. } else {
  11172. /* trust_id_outbound = legacy - behave in a non RFC-3325 compliant manner and send anonymized data when
  11173. * when handling private data. */
  11174. if ((lid_pres & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
  11175. ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name_buf, lid_num, fromdomain);
  11176. } else {
  11177. ast_str_set(&tmp, -1, "%s", anonymous_string);
  11178. }
  11179. }
  11180. add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
  11181. } else {
  11182. ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name_buf, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
  11183. switch (lid_pres) {
  11184. case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
  11185. case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
  11186. privacy = "off";
  11187. screen = "no";
  11188. break;
  11189. case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
  11190. case AST_PRES_ALLOWED_NETWORK_NUMBER:
  11191. privacy = "off";
  11192. screen = "yes";
  11193. break;
  11194. case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
  11195. case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
  11196. privacy = "full";
  11197. screen = "no";
  11198. break;
  11199. case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
  11200. case AST_PRES_PROHIB_NETWORK_NUMBER:
  11201. privacy = "full";
  11202. screen = "yes";
  11203. break;
  11204. case AST_PRES_NUMBER_NOT_AVAILABLE:
  11205. break;
  11206. default:
  11207. if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  11208. privacy = "full";
  11209. }
  11210. else
  11211. privacy = "off";
  11212. screen = "no";
  11213. break;
  11214. }
  11215. if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
  11216. ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
  11217. }
  11218. add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
  11219. }
  11220. return 0;
  11221. }
  11222. /*! \brief add XML encoded media control with update
  11223. \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
  11224. static int add_vidupdate(struct sip_request *req)
  11225. {
  11226. const char *xml_is_a_huge_waste_of_space =
  11227. "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
  11228. " <media_control>\r\n"
  11229. " <vc_primitive>\r\n"
  11230. " <to_encoder>\r\n"
  11231. " <picture_fast_update>\r\n"
  11232. " </picture_fast_update>\r\n"
  11233. " </to_encoder>\r\n"
  11234. " </vc_primitive>\r\n"
  11235. " </media_control>\r\n";
  11236. add_header(req, "Content-Type", "application/media_control+xml");
  11237. add_content(req, xml_is_a_huge_waste_of_space);
  11238. return 0;
  11239. }
  11240. /*! \brief Add ICE attributes to SDP */
  11241. static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
  11242. {
  11243. struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
  11244. const char *username, *password;
  11245. struct ao2_container *candidates;
  11246. struct ao2_iterator i;
  11247. struct ast_rtp_engine_ice_candidate *candidate;
  11248. /* If no ICE support is present we can't very well add the attributes */
  11249. if (!ice || !(candidates = ice->get_local_candidates(instance))) {
  11250. return;
  11251. }
  11252. if ((username = ice->get_ufrag(instance))) {
  11253. ast_str_append(a_buf, 0, "a=ice-ufrag:%s\r\n", username);
  11254. }
  11255. if ((password = ice->get_password(instance))) {
  11256. ast_str_append(a_buf, 0, "a=ice-pwd:%s\r\n", password);
  11257. }
  11258. i = ao2_iterator_init(candidates, 0);
  11259. while ((candidate = ao2_iterator_next(&i))) {
  11260. ast_str_append(a_buf, 0, "a=candidate:%s %u %s %d ", candidate->foundation, candidate->id, candidate->transport, candidate->priority);
  11261. ast_str_append(a_buf, 0, "%s ", ast_sockaddr_stringify_host(&candidate->address));
  11262. ast_str_append(a_buf, 0, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
  11263. if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
  11264. ast_str_append(a_buf, 0, "host");
  11265. } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
  11266. ast_str_append(a_buf, 0, "srflx");
  11267. } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
  11268. ast_str_append(a_buf, 0, "relay");
  11269. }
  11270. if (!ast_sockaddr_isnull(&candidate->relay_address)) {
  11271. ast_str_append(a_buf, 0, " raddr %s ", ast_sockaddr_stringify_host(&candidate->relay_address));
  11272. ast_str_append(a_buf, 0, "rport %s", ast_sockaddr_stringify_port(&candidate->relay_address));
  11273. }
  11274. ast_str_append(a_buf, 0, "\r\n");
  11275. ao2_ref(candidate, -1);
  11276. }
  11277. ao2_iterator_destroy(&i);
  11278. ao2_ref(candidates, -1);
  11279. }
  11280. /*! \brief Start ICE negotiation on an RTP instance */
  11281. static void start_ice(struct ast_rtp_instance *instance, int offer)
  11282. {
  11283. struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
  11284. if (!ice) {
  11285. return;
  11286. }
  11287. /* If we are the offerer then we are the controlling agent, otherwise they are */
  11288. ice->set_role(instance, offer ? AST_RTP_ICE_ROLE_CONTROLLING : AST_RTP_ICE_ROLE_CONTROLLED);
  11289. ice->start(instance);
  11290. }
  11291. /*! \brief Add DTLS attributes to SDP */
  11292. static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
  11293. {
  11294. struct ast_rtp_engine_dtls *dtls;
  11295. enum ast_rtp_dtls_hash hash;
  11296. const char *fingerprint;
  11297. if (!instance || !(dtls = ast_rtp_instance_get_dtls(instance)) || !dtls->active(instance)) {
  11298. return;
  11299. }
  11300. switch (dtls->get_connection(instance)) {
  11301. case AST_RTP_DTLS_CONNECTION_NEW:
  11302. ast_str_append(a_buf, 0, "a=connection:new\r\n");
  11303. break;
  11304. case AST_RTP_DTLS_CONNECTION_EXISTING:
  11305. ast_str_append(a_buf, 0, "a=connection:existing\r\n");
  11306. break;
  11307. default:
  11308. break;
  11309. }
  11310. switch (dtls->get_setup(instance)) {
  11311. case AST_RTP_DTLS_SETUP_ACTIVE:
  11312. ast_str_append(a_buf, 0, "a=setup:active\r\n");
  11313. break;
  11314. case AST_RTP_DTLS_SETUP_PASSIVE:
  11315. ast_str_append(a_buf, 0, "a=setup:passive\r\n");
  11316. break;
  11317. case AST_RTP_DTLS_SETUP_ACTPASS:
  11318. ast_str_append(a_buf, 0, "a=setup:actpass\r\n");
  11319. break;
  11320. case AST_RTP_DTLS_SETUP_HOLDCONN:
  11321. ast_str_append(a_buf, 0, "a=setup:holdconn\r\n");
  11322. break;
  11323. default:
  11324. break;
  11325. }
  11326. hash = dtls->get_fingerprint_hash(instance);
  11327. fingerprint = dtls->get_fingerprint(instance);
  11328. if (fingerprint && (hash == AST_RTP_DTLS_HASH_SHA1 || hash == AST_RTP_DTLS_HASH_SHA256)) {
  11329. ast_str_append(a_buf, 0, "a=fingerprint:%s %s\r\n", hash == AST_RTP_DTLS_HASH_SHA1 ? "SHA-1" : "SHA-256",
  11330. fingerprint);
  11331. }
  11332. }
  11333. /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
  11334. static void add_codec_to_sdp(const struct sip_pvt *p,
  11335. struct ast_format *format,
  11336. struct ast_str **m_buf,
  11337. struct ast_str **a_buf,
  11338. int debug,
  11339. int *min_packet_size,
  11340. int *max_packet_size)
  11341. {
  11342. int rtp_code;
  11343. const char *mime;
  11344. unsigned int rate, framing;
  11345. if (debug)
  11346. ast_verbose("Adding codec %s to SDP\n", ast_format_get_name(format));
  11347. if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, format, 0)) == -1) ||
  11348. !(mime = ast_rtp_lookup_mime_subtype2(1, format, 0, ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0)) ||
  11349. !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
  11350. return;
  11351. }
  11352. ast_str_append(m_buf, 0, " %d", rtp_code);
  11353. /* Opus mandates 2 channels in rtpmap */
  11354. if (ast_format_cmp(format, ast_format_opus) == AST_FORMAT_CMP_EQUAL) {
  11355. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u/2\r\n", rtp_code, mime, rate);
  11356. } else {
  11357. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code, mime, rate);
  11358. }
  11359. ast_format_generate_sdp_fmtp(format, rtp_code, a_buf);
  11360. framing = ast_format_cap_get_format_framing(p->caps, format);
  11361. if (ast_format_cmp(format, ast_format_g729) == AST_FORMAT_CMP_EQUAL) {
  11362. /* Indicate that we don't support VAD (G.729 annex B) */
  11363. ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
  11364. } else if (ast_format_cmp(format, ast_format_g723) == AST_FORMAT_CMP_EQUAL) {
  11365. /* Indicate that we don't support VAD (G.723.1 annex A) */
  11366. ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
  11367. } else if (ast_format_cmp(format, ast_format_ilbc) == AST_FORMAT_CMP_EQUAL) {
  11368. /* Add information about us using only 20/30 ms packetization */
  11369. ast_str_append(a_buf, 0, "a=fmtp:%d mode=%u\r\n", rtp_code, framing);
  11370. } else if (ast_format_cmp(format, ast_format_siren7) == AST_FORMAT_CMP_EQUAL) {
  11371. /* Indicate that we only expect 32Kbps */
  11372. ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
  11373. } else if (ast_format_cmp(format, ast_format_siren14) == AST_FORMAT_CMP_EQUAL) {
  11374. /* Indicate that we only expect 48Kbps */
  11375. ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
  11376. } else if (ast_format_cmp(format, ast_format_g719) == AST_FORMAT_CMP_EQUAL) {
  11377. /* Indicate that we only expect 64Kbps */
  11378. ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
  11379. }
  11380. if (max_packet_size && ast_format_get_maximum_ms(format) &&
  11381. (ast_format_get_maximum_ms(format) < *max_packet_size)) {
  11382. *max_packet_size = ast_format_get_maximum_ms(format);
  11383. }
  11384. if (framing && (framing < *min_packet_size)) {
  11385. *min_packet_size = framing;
  11386. }
  11387. /* Our first codec packetization processed cannot be zero */
  11388. if ((*min_packet_size) == 0 && framing) {
  11389. *min_packet_size = framing;
  11390. }
  11391. if ((*max_packet_size) == 0 && ast_format_get_maximum_ms(format)) {
  11392. *max_packet_size = ast_format_get_maximum_ms(format);
  11393. }
  11394. }
  11395. /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
  11396. /* This is different to the audio one now so we can add more caps later */
  11397. static void add_vcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
  11398. struct ast_str **m_buf, struct ast_str **a_buf,
  11399. int debug, int *min_packet_size)
  11400. {
  11401. int rtp_code;
  11402. const char *subtype;
  11403. unsigned int rate;
  11404. if (!p->vrtp)
  11405. return;
  11406. if (debug)
  11407. ast_verbose("Adding video codec %s to SDP\n", ast_format_get_name(format));
  11408. if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, format, 0)) == -1) ||
  11409. !(subtype = ast_rtp_lookup_mime_subtype2(1, format, 0, 0)) ||
  11410. !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
  11411. return;
  11412. }
  11413. ast_str_append(m_buf, 0, " %d", rtp_code);
  11414. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code, subtype, rate);
  11415. /* VP8: add RTCP FIR support */
  11416. if (ast_format_cmp(format, ast_format_vp8) == AST_FORMAT_CMP_EQUAL) {
  11417. ast_str_append(a_buf, 0, "a=rtcp-fb:* ccm fir\r\n");
  11418. }
  11419. ast_format_generate_sdp_fmtp(format, rtp_code, a_buf);
  11420. }
  11421. /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
  11422. static void add_tcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
  11423. struct ast_str **m_buf, struct ast_str **a_buf,
  11424. int debug, int *min_packet_size)
  11425. {
  11426. int rtp_code;
  11427. if (!p->trtp)
  11428. return;
  11429. if (debug)
  11430. ast_verbose("Adding text codec %s to SDP\n", ast_format_get_name(format));
  11431. if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, format, 0)) == -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(1, format, 0, 0),
  11436. ast_rtp_lookup_sample_rate2(1, format, 0));
  11437. /* Add fmtp code here */
  11438. if (ast_format_cmp(format, ast_format_t140_red) == AST_FORMAT_CMP_EQUAL) {
  11439. int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, ast_format_t140, 0);
  11440. ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
  11441. t140code,
  11442. t140code,
  11443. t140code);
  11444. }
  11445. }
  11446. /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
  11447. static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
  11448. {
  11449. switch (rate) {
  11450. case AST_T38_RATE_2400:
  11451. return 2400;
  11452. case AST_T38_RATE_4800:
  11453. return 4800;
  11454. case AST_T38_RATE_7200:
  11455. return 7200;
  11456. case AST_T38_RATE_9600:
  11457. return 9600;
  11458. case AST_T38_RATE_12000:
  11459. return 12000;
  11460. case AST_T38_RATE_14400:
  11461. return 14400;
  11462. default:
  11463. return 0;
  11464. }
  11465. }
  11466. /*! \brief Add RFC 2833 DTMF offer to SDP */
  11467. static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
  11468. struct ast_str **m_buf, struct ast_str **a_buf,
  11469. int debug)
  11470. {
  11471. int rtp_code;
  11472. if (debug)
  11473. ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", (unsigned)format, ast_rtp_lookup_mime_subtype2(0, NULL, format, 0));
  11474. if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, NULL, format)) == -1)
  11475. return;
  11476. ast_str_append(m_buf, 0, " %d", rtp_code);
  11477. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
  11478. ast_rtp_lookup_mime_subtype2(0, NULL, format, 0),
  11479. ast_rtp_lookup_sample_rate2(0, NULL, format));
  11480. if (format == AST_RTP_DTMF) /* Indicate we support DTMF and FLASH... */
  11481. ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
  11482. }
  11483. /*! \brief Set all IP media addresses for this call
  11484. \note called from add_sdp()
  11485. */
  11486. static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
  11487. struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
  11488. struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
  11489. struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
  11490. {
  11491. int use_externip = 0;
  11492. /* First, get our address */
  11493. ast_rtp_instance_get_local_address(p->rtp, addr);
  11494. if (p->vrtp) {
  11495. ast_rtp_instance_get_local_address(p->vrtp, vaddr);
  11496. }
  11497. if (p->trtp) {
  11498. ast_rtp_instance_get_local_address(p->trtp, taddr);
  11499. }
  11500. /* If our real IP differs from the local address returned by the RTP engine, use it. */
  11501. /* The premise is that if we are already using that IP to communicate with the client, */
  11502. /* we should be using it for RTP too. */
  11503. use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
  11504. /* Now, try to figure out where we want them to send data */
  11505. /* Is this a re-invite to move the media out, then use the original offer from caller */
  11506. if (!ast_sockaddr_isnull(&p->redirip)) { /* If we have a redirection IP, use it */
  11507. ast_sockaddr_copy(dest, &p->redirip);
  11508. } else {
  11509. /*
  11510. * Audio Destination IP:
  11511. *
  11512. * 1. Specifically configured media address.
  11513. * 2. Local address as specified by the RTP engine.
  11514. * 3. The local IP as defined by chan_sip.
  11515. *
  11516. * Audio Destination Port:
  11517. *
  11518. * 1. Provided by the RTP engine.
  11519. */
  11520. ast_sockaddr_copy(dest,
  11521. !ast_sockaddr_isnull(&media_address) ? &media_address :
  11522. !ast_sockaddr_is_any(addr) && !use_externip ? addr :
  11523. &p->ourip);
  11524. ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
  11525. }
  11526. if (needvideo) {
  11527. /* Determine video destination */
  11528. if (!ast_sockaddr_isnull(&p->vredirip)) {
  11529. ast_sockaddr_copy(vdest, &p->vredirip);
  11530. } else {
  11531. /*
  11532. * Video Destination IP:
  11533. *
  11534. * 1. Specifically configured media address.
  11535. * 2. Local address as specified by the RTP engine.
  11536. * 3. The local IP as defined by chan_sip.
  11537. *
  11538. * Video Destination Port:
  11539. *
  11540. * 1. Provided by the RTP engine.
  11541. */
  11542. ast_sockaddr_copy(vdest,
  11543. !ast_sockaddr_isnull(&media_address) ? &media_address :
  11544. !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr :
  11545. &p->ourip);
  11546. ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
  11547. }
  11548. }
  11549. if (needtext) {
  11550. /* Determine text destination */
  11551. if (!ast_sockaddr_isnull(&p->tredirip)) {
  11552. ast_sockaddr_copy(tdest, &p->tredirip);
  11553. } else {
  11554. /*
  11555. * Text Destination IP:
  11556. *
  11557. * 1. Specifically configured media address.
  11558. * 2. Local address as specified by the RTP engine.
  11559. * 3. The local IP as defined by chan_sip.
  11560. *
  11561. * Text Destination Port:
  11562. *
  11563. * 1. Provided by the RTP engine.
  11564. */
  11565. ast_sockaddr_copy(tdest,
  11566. !ast_sockaddr_isnull(&media_address) ? &media_address :
  11567. !ast_sockaddr_is_any(taddr) && !use_externip ? taddr :
  11568. &p->ourip);
  11569. ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
  11570. }
  11571. }
  11572. }
  11573. static char *crypto_get_attrib(struct ast_sdp_srtp *srtp, int dtls_enabled, int default_taglen_32)
  11574. {
  11575. char *a_crypto;
  11576. const char *orig_crypto;
  11577. if (!srtp || dtls_enabled) {
  11578. return NULL;
  11579. }
  11580. orig_crypto = ast_sdp_srtp_get_attrib(srtp, dtls_enabled, default_taglen_32);
  11581. if (ast_strlen_zero(orig_crypto)) {
  11582. return NULL;
  11583. }
  11584. if (ast_asprintf(&a_crypto, "a=crypto:%s\r\n", orig_crypto) == -1) {
  11585. return NULL;
  11586. }
  11587. return a_crypto;
  11588. }
  11589. /*! \brief Add Session Description Protocol message
  11590. If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
  11591. is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
  11592. without modifying the media session in any way.
  11593. */
  11594. static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
  11595. {
  11596. struct ast_format_cap *alreadysent = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  11597. struct ast_format_cap *tmpcap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  11598. int res = AST_SUCCESS;
  11599. int doing_directmedia = FALSE;
  11600. struct ast_sockaddr addr = { {0,} };
  11601. struct ast_sockaddr vaddr = { {0,} };
  11602. struct ast_sockaddr taddr = { {0,} };
  11603. struct ast_sockaddr udptladdr = { {0,} };
  11604. struct ast_sockaddr dest = { {0,} };
  11605. struct ast_sockaddr vdest = { {0,} };
  11606. struct ast_sockaddr tdest = { {0,} };
  11607. struct ast_sockaddr udptldest = { {0,} };
  11608. /* SDP fields */
  11609. struct offered_media *offer;
  11610. char *version = "v=0\r\n"; /* Protocol version */
  11611. char subject[256]; /* Subject of the session */
  11612. char owner[256]; /* Session owner/creator */
  11613. char connection[256]; /* Connection data */
  11614. char *session_time = "t=0 0\r\n"; /* Time the session is active */
  11615. char bandwidth[256] = ""; /* Max bitrate */
  11616. char *hold = "";
  11617. struct ast_str *m_audio = ast_str_alloca(256); /* Media declaration line for audio */
  11618. struct ast_str *m_video = ast_str_alloca(256); /* Media declaration line for video */
  11619. struct ast_str *m_text = ast_str_alloca(256); /* Media declaration line for text */
  11620. struct ast_str *m_modem = ast_str_alloca(256); /* Media declaration line for modem */
  11621. struct ast_str *a_audio = ast_str_create(256); /* Attributes for audio */
  11622. struct ast_str *a_video = ast_str_create(256); /* Attributes for video */
  11623. struct ast_str *a_text = ast_str_create(256); /* Attributes for text */
  11624. struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
  11625. RAII_VAR(char *, a_crypto, NULL, ast_free);
  11626. RAII_VAR(char *, v_a_crypto, NULL, ast_free);
  11627. RAII_VAR(char *, t_a_crypto, NULL, ast_free);
  11628. int x;
  11629. struct ast_format *tmp_fmt;
  11630. int needaudio = FALSE;
  11631. int needvideo = FALSE;
  11632. int needtext = FALSE;
  11633. int debug = sip_debug_test_pvt(p);
  11634. int min_audio_packet_size = 0;
  11635. int max_audio_packet_size = 0;
  11636. int min_video_packet_size = 0;
  11637. int min_text_packet_size = 0;
  11638. struct ast_str *codec_buf = ast_str_alloca(64);
  11639. /* Set the SDP session name */
  11640. snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
  11641. if (!alreadysent || !tmpcap) {
  11642. res = AST_FAILURE;
  11643. goto add_sdp_cleanup;
  11644. }
  11645. if (!p->rtp) {
  11646. ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
  11647. res = AST_FAILURE;
  11648. goto add_sdp_cleanup;
  11649. }
  11650. /* XXX We should not change properties in the SIP dialog until
  11651. we have acceptance of the offer if this is a re-invite */
  11652. /* Set RTP Session ID and version */
  11653. if (!p->sessionid) {
  11654. p->sessionid = (int)ast_random();
  11655. p->sessionversion = p->sessionid;
  11656. } else {
  11657. if (oldsdp == FALSE)
  11658. p->sessionversion++;
  11659. }
  11660. if (add_audio) {
  11661. doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && (ast_format_cap_count(p->redircaps))) ? TRUE : FALSE;
  11662. if (doing_directmedia) {
  11663. ast_format_cap_get_compatible(p->jointcaps, p->redircaps, tmpcap);
  11664. ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_format_cap_get_names(tmpcap, &codec_buf));
  11665. } else {
  11666. ast_format_cap_append_from_cap(tmpcap, p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  11667. }
  11668. /* Check if we need audio */
  11669. if (ast_format_cap_has_type(tmpcap, AST_MEDIA_TYPE_AUDIO)
  11670. || ast_format_cap_has_type(p->caps, AST_MEDIA_TYPE_AUDIO)) {
  11671. needaudio = TRUE;
  11672. }
  11673. /* Check if we need video in this call */
  11674. if ((ast_format_cap_has_type(tmpcap, AST_MEDIA_TYPE_VIDEO)) && !p->novideo) {
  11675. if (doing_directmedia && !ast_format_cap_has_type(tmpcap, AST_MEDIA_TYPE_VIDEO)) {
  11676. ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
  11677. } else if (p->vrtp) {
  11678. needvideo = TRUE;
  11679. ast_debug(2, "This call needs video offers!\n");
  11680. } else {
  11681. ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
  11682. }
  11683. }
  11684. /* Check if we need text in this call */
  11685. if ((ast_format_cap_has_type(p->jointcaps, AST_MEDIA_TYPE_TEXT)) && !p->notext) {
  11686. if (sipdebug_text)
  11687. ast_verbose("We think we can do text\n");
  11688. if (p->trtp) {
  11689. if (sipdebug_text) {
  11690. ast_verbose("And we have a text rtp object\n");
  11691. }
  11692. needtext = TRUE;
  11693. ast_debug(2, "This call needs text offers! \n");
  11694. } else {
  11695. ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
  11696. }
  11697. }
  11698. /* XXX note, Video and Text are negated - 'true' means 'no' */
  11699. ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n",
  11700. ast_format_cap_get_names(tmpcap, &codec_buf),
  11701. p->novideo ? "True" : "False", p->notext ? "True" : "False");
  11702. ast_debug(1, "** Our prefcodec: %s \n", ast_format_cap_get_names(p->prefcaps, &codec_buf));
  11703. }
  11704. get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
  11705. snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
  11706. ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
  11707. p->sessionid, p->sessionversion,
  11708. (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
  11709. "IP6" : "IP4",
  11710. ast_sockaddr_stringify_addr_remote(&dest));
  11711. snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
  11712. (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
  11713. "IP6" : "IP4",
  11714. ast_sockaddr_stringify_addr_remote(&dest));
  11715. if (add_audio) {
  11716. if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
  11717. hold = "a=recvonly\r\n";
  11718. doing_directmedia = FALSE;
  11719. } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
  11720. hold = "a=inactive\r\n";
  11721. doing_directmedia = FALSE;
  11722. } else {
  11723. hold = "a=sendrecv\r\n";
  11724. }
  11725. if (debug) {
  11726. ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
  11727. }
  11728. /* Ok, we need video. Let's add what we need for video and set codecs.
  11729. Video is handled differently than audio since we can not transcode. */
  11730. if (needvideo) {
  11731. v_a_crypto = crypto_get_attrib(p->vsrtp, p->dtls_cfg.enabled,
  11732. ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32));
  11733. ast_str_append(&m_video, 0, "m=video %d %s", ast_sockaddr_port(&vdest),
  11734. ast_sdp_get_rtp_profile(v_a_crypto ? 1 : 0, p->vrtp,
  11735. ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF),
  11736. ast_test_flag(&p->flags[2], SIP_PAGE3_FORCE_AVP)));
  11737. /* Build max bitrate string */
  11738. if (p->maxcallbitrate)
  11739. snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
  11740. if (debug) {
  11741. ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
  11742. }
  11743. if (!doing_directmedia) {
  11744. if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
  11745. add_ice_to_sdp(p->vrtp, &a_video);
  11746. }
  11747. add_dtls_to_sdp(p->vrtp, &a_video);
  11748. }
  11749. }
  11750. /* Ok, we need text. Let's add what we need for text and set codecs.
  11751. Text is handled differently than audio since we can not transcode. */
  11752. if (needtext) {
  11753. if (sipdebug_text)
  11754. ast_verbose("Lets set up the text sdp\n");
  11755. t_a_crypto = crypto_get_attrib(p->tsrtp, p->dtls_cfg.enabled,
  11756. ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32));
  11757. ast_str_append(&m_text, 0, "m=text %d %s", ast_sockaddr_port(&tdest),
  11758. ast_sdp_get_rtp_profile(t_a_crypto ? 1 : 0, p->trtp,
  11759. ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF),
  11760. ast_test_flag(&p->flags[2], SIP_PAGE3_FORCE_AVP)));
  11761. if (debug) { /* XXX should I use tdest below ? */
  11762. ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
  11763. }
  11764. if (!doing_directmedia) {
  11765. if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
  11766. add_ice_to_sdp(p->trtp, &a_text);
  11767. }
  11768. add_dtls_to_sdp(p->trtp, &a_text);
  11769. }
  11770. }
  11771. /* Start building generic SDP headers */
  11772. /* We break with the "recommendation" and send our IP, in order that our
  11773. peer doesn't have to ast_gethostbyname() us */
  11774. a_crypto = crypto_get_attrib(p->srtp, p->dtls_cfg.enabled,
  11775. ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32));
  11776. ast_str_append(&m_audio, 0, "m=audio %d %s", ast_sockaddr_port(&dest),
  11777. ast_sdp_get_rtp_profile(a_crypto ? 1 : 0, p->rtp,
  11778. ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF),
  11779. ast_test_flag(&p->flags[2], SIP_PAGE3_FORCE_AVP)));
  11780. /* Now, start adding audio codecs. These are added in this order:
  11781. - First what was requested by the calling channel
  11782. - Then our mutually shared capabilities, determined previous in tmpcap
  11783. - Then preferences in order from sip.conf device config for this peer/user
  11784. */
  11785. /* Unless otherwise configured, the prefcaps is added before the peer's
  11786. * configured codecs.
  11787. */
  11788. if (!ast_test_flag(&p->flags[2], SIP_PAGE3_IGNORE_PREFCAPS)) {
  11789. for (x = 0; x < ast_format_cap_count(p->prefcaps); x++) {
  11790. tmp_fmt = ast_format_cap_get_format(p->prefcaps, x);
  11791. if ((ast_format_get_type(tmp_fmt) != AST_MEDIA_TYPE_AUDIO) ||
  11792. (ast_format_cap_iscompatible_format(tmpcap, tmp_fmt) == AST_FORMAT_CMP_NOT_EQUAL)) {
  11793. ao2_ref(tmp_fmt, -1);
  11794. continue;
  11795. }
  11796. add_codec_to_sdp(p, tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size, &max_audio_packet_size);
  11797. ast_format_cap_append(alreadysent, tmp_fmt, 0);
  11798. ao2_ref(tmp_fmt, -1);
  11799. }
  11800. }
  11801. /* Now send any other common codecs */
  11802. for (x = 0; x < ast_format_cap_count(tmpcap); x++) {
  11803. tmp_fmt = ast_format_cap_get_format(tmpcap, x);
  11804. if (ast_format_cap_iscompatible_format(alreadysent, tmp_fmt) != AST_FORMAT_CMP_NOT_EQUAL) {
  11805. ao2_ref(tmp_fmt, -1);
  11806. continue;
  11807. }
  11808. if (ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_AUDIO) {
  11809. add_codec_to_sdp(p, tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size, &max_audio_packet_size);
  11810. } else if (needvideo && ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_VIDEO) {
  11811. add_vcodec_to_sdp(p, tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
  11812. } else if (needtext && ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_TEXT) {
  11813. add_tcodec_to_sdp(p, tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
  11814. }
  11815. ast_format_cap_append(alreadysent, tmp_fmt, 0);
  11816. ao2_ref(tmp_fmt, -1);
  11817. }
  11818. /* Finally our remaining audio/video codecs */
  11819. for (x = 0; x < ast_format_cap_count(p->caps); x++) {
  11820. tmp_fmt = ast_format_cap_get_format(p->caps, x);
  11821. if (ast_format_cap_iscompatible_format(alreadysent, tmp_fmt) != AST_FORMAT_CMP_NOT_EQUAL) {
  11822. ao2_ref(tmp_fmt, -1);
  11823. continue;
  11824. }
  11825. if (ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_AUDIO) {
  11826. add_codec_to_sdp(p, tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size, &max_audio_packet_size);
  11827. } else if (needvideo && ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_VIDEO) {
  11828. add_vcodec_to_sdp(p, tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
  11829. } else if (needtext && ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_TEXT) {
  11830. add_tcodec_to_sdp(p, tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
  11831. }
  11832. ast_format_cap_append(alreadysent, tmp_fmt, 0);
  11833. ao2_ref(tmp_fmt, -1);
  11834. }
  11835. /* Now add DTMF RFC2833 telephony-event as a codec */
  11836. for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
  11837. if (!(p->jointnoncodeccapability & x))
  11838. continue;
  11839. add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
  11840. }
  11841. ast_debug(3, "-- Done with adding codecs to SDP\n");
  11842. if (!p->owner || ast_channel_timingfd(p->owner) == -1) {
  11843. ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
  11844. }
  11845. if (min_audio_packet_size) {
  11846. ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
  11847. }
  11848. /* XXX don't think you can have ptime for video */
  11849. if (min_video_packet_size) {
  11850. ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
  11851. }
  11852. /* XXX don't think you can have ptime for text */
  11853. if (min_text_packet_size) {
  11854. ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
  11855. }
  11856. if (max_audio_packet_size) {
  11857. ast_str_append(&a_audio, 0, "a=maxptime:%d\r\n", max_audio_packet_size);
  11858. }
  11859. if (!doing_directmedia) {
  11860. if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
  11861. add_ice_to_sdp(p->rtp, &a_audio);
  11862. }
  11863. add_dtls_to_sdp(p->rtp, &a_audio);
  11864. }
  11865. }
  11866. if (add_t38) {
  11867. /* Our T.38 end is */
  11868. ast_udptl_get_us(p->udptl, &udptladdr);
  11869. /* We don't use directmedia for T.38, so keep the destination the same as our IP address. */
  11870. ast_sockaddr_copy(&udptldest, &p->ourip);
  11871. ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
  11872. if (debug) {
  11873. ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
  11874. }
  11875. /* We break with the "recommendation" and send our IP, in order that our
  11876. peer doesn't have to ast_gethostbyname() us */
  11877. ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
  11878. if (ast_sockaddr_cmp(&udptldest, &dest)) {
  11879. ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
  11880. (ast_sockaddr_is_ipv6(&udptldest) && !ast_sockaddr_is_ipv4_mapped(&udptldest)) ?
  11881. "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
  11882. }
  11883. ast_str_append(&a_modem, 0, "a=T38FaxVersion:%u\r\n", p->t38.our_parms.version);
  11884. ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%u\r\n", t38_get_rate(p->t38.our_parms.rate));
  11885. if (p->t38.our_parms.fill_bit_removal) {
  11886. ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
  11887. }
  11888. if (p->t38.our_parms.transcoding_mmr) {
  11889. ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
  11890. }
  11891. if (p->t38.our_parms.transcoding_jbig) {
  11892. ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
  11893. }
  11894. switch (p->t38.our_parms.rate_management) {
  11895. case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
  11896. ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
  11897. break;
  11898. case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
  11899. ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
  11900. break;
  11901. }
  11902. ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
  11903. switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
  11904. case UDPTL_ERROR_CORRECTION_NONE:
  11905. break;
  11906. case UDPTL_ERROR_CORRECTION_FEC:
  11907. ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
  11908. break;
  11909. case UDPTL_ERROR_CORRECTION_REDUNDANCY:
  11910. ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
  11911. break;
  11912. }
  11913. }
  11914. if (needaudio)
  11915. ast_str_append(&m_audio, 0, "\r\n");
  11916. if (needvideo)
  11917. ast_str_append(&m_video, 0, "\r\n");
  11918. if (needtext)
  11919. ast_str_append(&m_text, 0, "\r\n");
  11920. add_header(resp, "Content-Type", "application/sdp");
  11921. add_content(resp, version);
  11922. add_content(resp, owner);
  11923. add_content(resp, subject);
  11924. add_content(resp, connection);
  11925. /* only if video response is appropriate */
  11926. if (needvideo) {
  11927. add_content(resp, bandwidth);
  11928. }
  11929. add_content(resp, session_time);
  11930. /* if this is a response to an invite, order our offers properly */
  11931. if (!AST_LIST_EMPTY(&p->offered_media)) {
  11932. AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
  11933. switch (offer->type) {
  11934. case SDP_AUDIO:
  11935. if (needaudio) {
  11936. add_content(resp, ast_str_buffer(m_audio));
  11937. add_content(resp, ast_str_buffer(a_audio));
  11938. add_content(resp, hold);
  11939. if (a_crypto) {
  11940. add_content(resp, a_crypto);
  11941. }
  11942. } else {
  11943. add_content(resp, offer->decline_m_line);
  11944. }
  11945. break;
  11946. case SDP_VIDEO:
  11947. if (needvideo) { /* only if video response is appropriate */
  11948. add_content(resp, ast_str_buffer(m_video));
  11949. add_content(resp, ast_str_buffer(a_video));
  11950. add_content(resp, hold); /* Repeat hold for the video stream */
  11951. if (v_a_crypto) {
  11952. add_content(resp, v_a_crypto);
  11953. }
  11954. } else {
  11955. add_content(resp, offer->decline_m_line);
  11956. }
  11957. break;
  11958. case SDP_TEXT:
  11959. if (needtext) { /* only if text response is appropriate */
  11960. add_content(resp, ast_str_buffer(m_text));
  11961. add_content(resp, ast_str_buffer(a_text));
  11962. add_content(resp, hold); /* Repeat hold for the text stream */
  11963. if (t_a_crypto) {
  11964. add_content(resp, t_a_crypto);
  11965. }
  11966. } else {
  11967. add_content(resp, offer->decline_m_line);
  11968. }
  11969. break;
  11970. case SDP_IMAGE:
  11971. if (add_t38) {
  11972. add_content(resp, ast_str_buffer(m_modem));
  11973. add_content(resp, ast_str_buffer(a_modem));
  11974. } else {
  11975. add_content(resp, offer->decline_m_line);
  11976. }
  11977. break;
  11978. case SDP_UNKNOWN:
  11979. add_content(resp, offer->decline_m_line);
  11980. break;
  11981. }
  11982. }
  11983. } else {
  11984. /* generate new SDP from scratch, no offers */
  11985. if (needaudio) {
  11986. add_content(resp, ast_str_buffer(m_audio));
  11987. add_content(resp, ast_str_buffer(a_audio));
  11988. add_content(resp, hold);
  11989. if (a_crypto) {
  11990. add_content(resp, a_crypto);
  11991. }
  11992. }
  11993. if (needvideo) { /* only if video response is appropriate */
  11994. add_content(resp, ast_str_buffer(m_video));
  11995. add_content(resp, ast_str_buffer(a_video));
  11996. add_content(resp, hold); /* Repeat hold for the video stream */
  11997. if (v_a_crypto) {
  11998. add_content(resp, v_a_crypto);
  11999. }
  12000. }
  12001. if (needtext) { /* only if text response is appropriate */
  12002. add_content(resp, ast_str_buffer(m_text));
  12003. add_content(resp, ast_str_buffer(a_text));
  12004. add_content(resp, hold); /* Repeat hold for the text stream */
  12005. if (t_a_crypto) {
  12006. add_content(resp, t_a_crypto);
  12007. }
  12008. }
  12009. if (add_t38) {
  12010. add_content(resp, ast_str_buffer(m_modem));
  12011. add_content(resp, ast_str_buffer(a_modem));
  12012. }
  12013. }
  12014. /* Update lastrtprx when we send our SDP */
  12015. p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
  12016. /*
  12017. * We unlink this dialog and link again into the
  12018. * dialogs_rtpcheck container so its not in there twice.
  12019. */
  12020. ao2_lock(dialogs_rtpcheck);
  12021. ao2_t_unlink(dialogs_rtpcheck, p, "unlink pvt into dialogs_rtpcheck container");
  12022. ao2_t_link(dialogs_rtpcheck, p, "link pvt into dialogs_rtpcheck container");
  12023. ao2_unlock(dialogs_rtpcheck);
  12024. ast_debug(3, "Done building SDP. Settling with this capability: %s\n",
  12025. ast_format_cap_get_names(tmpcap, &codec_buf));
  12026. add_sdp_cleanup:
  12027. ast_free(a_text);
  12028. ast_free(a_video);
  12029. ast_free(a_audio);
  12030. ao2_cleanup(alreadysent);
  12031. ao2_cleanup(tmpcap);
  12032. return res;
  12033. }
  12034. /*! \brief Used for 200 OK and 183 early media */
  12035. static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
  12036. {
  12037. struct sip_request resp;
  12038. uint32_t seqno;
  12039. if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
  12040. ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
  12041. return -1;
  12042. }
  12043. respprep(&resp, p, msg, req);
  12044. if (p->udptl) {
  12045. add_sdp(&resp, p, 0, 0, 1);
  12046. } else
  12047. ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
  12048. if (retrans && !p->pendinginvite)
  12049. p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
  12050. return send_response(p, &resp, retrans, seqno);
  12051. }
  12052. /*! \brief copy SIP request (mostly used to save request for responses) */
  12053. static void copy_request(struct sip_request *dst, const struct sip_request *src)
  12054. {
  12055. /* XXX this function can encounter memory allocation errors, perhaps it
  12056. * should return a value */
  12057. struct ast_str *duplicate = dst->data;
  12058. struct ast_str *duplicate_content = dst->content;
  12059. /* copy the entire request then restore the original data and content
  12060. * members from the dst request */
  12061. *dst = *src;
  12062. dst->data = duplicate;
  12063. dst->content = duplicate_content;
  12064. /* copy the data into the dst request */
  12065. if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
  12066. return;
  12067. }
  12068. ast_str_copy_string(&dst->data, src->data);
  12069. /* copy the content into the dst request (if it exists) */
  12070. if (src->content) {
  12071. if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
  12072. return;
  12073. }
  12074. ast_str_copy_string(&dst->content, src->content);
  12075. }
  12076. }
  12077. static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
  12078. {
  12079. char uri[SIPBUFSIZE];
  12080. struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
  12081. struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
  12082. struct sip_cc_agent_pvt *agent_pvt;
  12083. if (!agent) {
  12084. /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
  12085. * agent? Oh well, we'll just warn and return without adding the header.
  12086. */
  12087. ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
  12088. return;
  12089. }
  12090. agent_pvt = agent->private_data;
  12091. if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
  12092. ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
  12093. } else {
  12094. generate_uri(p, uri, sizeof(uri));
  12095. ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
  12096. }
  12097. /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
  12098. * to be more accurate. This parameter has no bearing on the actual operation
  12099. * of the feature; it's just there for informational purposes.
  12100. */
  12101. ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
  12102. add_header(resp, "Call-Info", ast_str_buffer(header));
  12103. ao2_ref(agent, -1);
  12104. }
  12105. /*! \brief Used for 200 OK and 183 early media
  12106. \return Will return XMIT_ERROR for network errors.
  12107. */
  12108. 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)
  12109. {
  12110. struct sip_request resp;
  12111. uint32_t seqno;
  12112. if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
  12113. ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
  12114. return -1;
  12115. }
  12116. respprep(&resp, p, msg, req);
  12117. if (rpid == TRUE) {
  12118. add_rpid(&resp, p);
  12119. }
  12120. if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
  12121. add_cc_call_info_to_response(p, &resp);
  12122. }
  12123. if (p->rtp) {
  12124. if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  12125. ast_debug(1, "Setting framing from config on incoming call\n");
  12126. ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(p->rtp), ast_format_cap_get_framing(p->caps));
  12127. }
  12128. ast_rtp_instance_activate(p->rtp);
  12129. try_suggested_sip_codec(p);
  12130. if (p->t38.state == T38_ENABLED) {
  12131. add_sdp(&resp, p, oldsdp, TRUE, TRUE);
  12132. } else {
  12133. add_sdp(&resp, p, oldsdp, TRUE, FALSE);
  12134. }
  12135. } else
  12136. ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
  12137. if (reliable && !p->pendinginvite)
  12138. p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
  12139. add_required_respheader(&resp);
  12140. return send_response(p, &resp, reliable, seqno);
  12141. }
  12142. /*! \brief Parse first line of incoming SIP request */
  12143. static int determine_firstline_parts(struct sip_request *req)
  12144. {
  12145. char *e = ast_skip_blanks(req->data->str); /* there shouldn't be any */
  12146. char *local_rlpart1;
  12147. if (!*e)
  12148. return -1;
  12149. req->rlpart1 = e - req->data->str; /* method or protocol */
  12150. local_rlpart1 = e;
  12151. e = ast_skip_nonblanks(e);
  12152. if (*e)
  12153. *e++ = '\0';
  12154. /* Get URI or status code */
  12155. e = ast_skip_blanks(e);
  12156. if ( !*e )
  12157. return -1;
  12158. ast_trim_blanks(e);
  12159. if (!strcasecmp(local_rlpart1, "SIP/2.0") ) { /* We have a response */
  12160. if (strlen(e) < 3) /* status code is 3 digits */
  12161. return -1;
  12162. req->rlpart2 = e - req->data->str;
  12163. } else { /* We have a request */
  12164. if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
  12165. ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
  12166. e++;
  12167. if (!*e)
  12168. return -1;
  12169. }
  12170. req->rlpart2 = e - req->data->str; /* URI */
  12171. e = ast_skip_nonblanks(e);
  12172. if (*e)
  12173. *e++ = '\0';
  12174. e = ast_skip_blanks(e);
  12175. if (strcasecmp(e, "SIP/2.0") ) {
  12176. ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
  12177. return -1;
  12178. }
  12179. }
  12180. return 1;
  12181. }
  12182. /*! \brief Transmit reinvite with SDP
  12183. \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
  12184. INVITE that opened the SIP dialogue
  12185. We reinvite so that the audio stream (RTP) go directly between
  12186. the SIP UAs. SIP Signalling stays with * in the path.
  12187. If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
  12188. T38 UDPTL transmission on the channel
  12189. If oldsdp is TRUE then the SDP version number is not incremented. This
  12190. is needed for Session-Timers so we can send a re-invite to refresh the
  12191. SIP session without modifying the media session.
  12192. */
  12193. static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
  12194. {
  12195. struct sip_request req;
  12196. reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
  12197. add_header(&req, "Allow", ALLOWED_METHODS);
  12198. add_supported(p, &req);
  12199. if (sipdebug) {
  12200. if (oldsdp == TRUE)
  12201. add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
  12202. else
  12203. add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
  12204. }
  12205. if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
  12206. add_rpid(&req, p);
  12207. if (p->do_history) {
  12208. append_history(p, "ReInv", "Re-invite sent");
  12209. }
  12210. offered_media_list_destroy(p);
  12211. try_suggested_sip_codec(p);
  12212. if (t38version) {
  12213. add_sdp(&req, p, oldsdp, FALSE, TRUE);
  12214. } else {
  12215. add_sdp(&req, p, oldsdp, TRUE, FALSE);
  12216. }
  12217. /* Use this as the basis */
  12218. initialize_initreq(p, &req);
  12219. p->lastinvite = p->ocseq;
  12220. ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
  12221. p->ongoing_reinvite = 1;
  12222. return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  12223. }
  12224. /* \brief Remove URI parameters at end of URI, not in username part though */
  12225. static char *remove_uri_parameters(char *uri)
  12226. {
  12227. char *atsign;
  12228. atsign = strchr(uri, '@'); /* First, locate the at sign */
  12229. if (!atsign) {
  12230. atsign = uri; /* Ok hostname only, let's stick with the rest */
  12231. }
  12232. atsign = strchr(atsign, ';'); /* Locate semi colon */
  12233. if (atsign)
  12234. *atsign = '\0'; /* Kill at the semi colon */
  12235. return uri;
  12236. }
  12237. /*! \brief Check Contact: URI of SIP message */
  12238. static void extract_uri(struct sip_pvt *p, struct sip_request *req)
  12239. {
  12240. char stripped[SIPBUFSIZE];
  12241. char *c;
  12242. ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
  12243. c = get_in_brackets(stripped);
  12244. /* Cut the URI at the at sign after the @, not in the username part */
  12245. c = remove_uri_parameters(c);
  12246. if (!ast_strlen_zero(c)) {
  12247. ast_string_field_set(p, uri, c);
  12248. }
  12249. }
  12250. /*! \brief Build contact header - the contact header we send out */
  12251. static void build_contact(struct sip_pvt *p)
  12252. {
  12253. char tmp[SIPBUFSIZE];
  12254. char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), ast_uri_sip_user);
  12255. if (p->socket.type == AST_TRANSPORT_UDP) {
  12256. ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
  12257. ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
  12258. } else {
  12259. ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
  12260. ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
  12261. sip_get_transport(p->socket.type));
  12262. }
  12263. }
  12264. /*! \brief Initiate new SIP request to peer/user */
  12265. static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
  12266. {
  12267. struct ast_str *invite = ast_str_alloca(256);
  12268. char from[256];
  12269. char to[256];
  12270. char tmp_n[SIPBUFSIZE/2]; /* build a local copy of 'n' if needed */
  12271. char tmp_l[SIPBUFSIZE/2]; /* build a local copy of 'l' if needed */
  12272. const char *l = NULL; /* XXX what is this, exactly ? */
  12273. const char *n = NULL; /* XXX what is this, exactly ? */
  12274. const char *d = NULL; /* domain in from header */
  12275. const char *urioptions = "";
  12276. int ourport;
  12277. int cid_has_name = 1;
  12278. int cid_has_num = 1;
  12279. struct ast_party_id connected_id;
  12280. if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
  12281. const char *s = p->username; /* being a string field, cannot be NULL */
  12282. /* Test p->username against allowed characters in AST_DIGIT_ANY
  12283. If it matches the allowed characters list, then sipuser = ";user=phone"
  12284. If not, then sipuser = ""
  12285. */
  12286. /* + is allowed in first position in a tel: uri */
  12287. if (*s == '+')
  12288. s++;
  12289. for (; *s; s++) {
  12290. if (!strchr(AST_DIGIT_ANYNUM, *s) )
  12291. break;
  12292. }
  12293. /* If we have only digits, add ;user=phone to the uri */
  12294. if (!*s)
  12295. urioptions = ";user=phone";
  12296. }
  12297. snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
  12298. if (ast_strlen_zero(p->fromdomain)) {
  12299. d = ast_sockaddr_stringify_host_remote(&p->ourip);
  12300. }
  12301. if (p->owner) {
  12302. connected_id = ast_channel_connected_effective_id(p->owner);
  12303. if ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
  12304. if (connected_id.number.valid) {
  12305. l = connected_id.number.str;
  12306. }
  12307. if (connected_id.name.valid) {
  12308. n = connected_id.name.str;
  12309. }
  12310. } else {
  12311. /* Even if we are using RPID, we shouldn't leak information in the From if the user wants
  12312. * their callerid restricted */
  12313. l = "anonymous";
  12314. n = CALLERID_UNKNOWN;
  12315. d = FROMDOMAIN_INVALID;
  12316. }
  12317. }
  12318. /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
  12319. * XXX Right now, this logic works because the only place that mwi_from
  12320. * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
  12321. * we might end up putting the mwi_from setting into other types of NOTIFY
  12322. * messages as well.
  12323. */
  12324. if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
  12325. l = p->mwi_from;
  12326. }
  12327. if (ast_strlen_zero(l)) {
  12328. cid_has_num = 0;
  12329. l = default_callerid;
  12330. }
  12331. if (ast_strlen_zero(n)) {
  12332. cid_has_name = 0;
  12333. n = l;
  12334. }
  12335. /* Allow user to be overridden */
  12336. if (!ast_strlen_zero(p->fromuser))
  12337. l = p->fromuser;
  12338. else /* Save for any further attempts */
  12339. ast_string_field_set(p, fromuser, l);
  12340. /* Allow user to be overridden */
  12341. if (!ast_strlen_zero(p->fromname))
  12342. n = p->fromname;
  12343. else /* Save for any further attempts */
  12344. ast_string_field_set(p, fromname, n);
  12345. /* Allow domain to be overridden */
  12346. if (!ast_strlen_zero(p->fromdomain))
  12347. d = p->fromdomain;
  12348. else /* Save for any further attempts */
  12349. ast_string_field_set(p, fromdomain, d);
  12350. ast_copy_string(tmp_l, l, sizeof(tmp_l));
  12351. if (sip_cfg.pedanticsipchecking) {
  12352. ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
  12353. n = tmp_n;
  12354. ast_uri_encode(l, tmp_l, sizeof(tmp_l), ast_uri_sip_user);
  12355. }
  12356. ourport = (p->fromdomainport && (p->fromdomainport != STANDARD_SIP_PORT)) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
  12357. /* If a caller id name was specified, add a display name. */
  12358. if (cid_has_name || !cid_has_num) {
  12359. snprintf(from, sizeof(from), "\"%s\" ", n);
  12360. } else {
  12361. from[0] = '\0';
  12362. }
  12363. if (!sip_standard_port(p->socket.type, ourport)) {
  12364. size_t offset = strlen(from);
  12365. snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s:%d>;tag=%s", tmp_l, d, ourport, p->tag);
  12366. } else {
  12367. size_t offset = strlen(from);
  12368. snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s>;tag=%s", tmp_l, d, p->tag);
  12369. }
  12370. if (!ast_strlen_zero(explicit_uri)) {
  12371. ast_str_set(&invite, 0, "%s", explicit_uri);
  12372. } else {
  12373. /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
  12374. if (!ast_strlen_zero(p->fullcontact)) {
  12375. /* If we have full contact, trust it */
  12376. ast_str_append(&invite, 0, "%s", p->fullcontact);
  12377. } else {
  12378. /* Otherwise, use the username while waiting for registration */
  12379. ast_str_append(&invite, 0, "sip:");
  12380. if (!ast_strlen_zero(p->username)) {
  12381. n = p->username;
  12382. if (sip_cfg.pedanticsipchecking) {
  12383. ast_uri_encode(n, tmp_n, sizeof(tmp_n), ast_uri_sip_user);
  12384. n = tmp_n;
  12385. }
  12386. ast_str_append(&invite, 0, "%s@", n);
  12387. }
  12388. ast_str_append(&invite, 0, "%s", p->tohost);
  12389. if (p->portinuri) {
  12390. ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
  12391. }
  12392. ast_str_append(&invite, 0, "%s", urioptions);
  12393. }
  12394. }
  12395. /* If custom URI options have been provided, append them */
  12396. if (p->options && !ast_strlen_zero(p->options->uri_options))
  12397. ast_str_append(&invite, 0, ";%s", p->options->uri_options);
  12398. /* This is the request URI, which is the next hop of the call
  12399. which may or may not be the destination of the call
  12400. */
  12401. ast_string_field_set(p, uri, ast_str_buffer(invite));
  12402. if (!ast_strlen_zero(p->todnid)) {
  12403. /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
  12404. if (!strchr(p->todnid, '@')) {
  12405. /* We have no domain in the dnid */
  12406. snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
  12407. } else {
  12408. snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
  12409. }
  12410. } else {
  12411. if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
  12412. /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
  12413. snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
  12414. } else if (p->options && p->options->vxml_url) {
  12415. /* If there is a VXML URL append it to the SIP URL */
  12416. snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
  12417. } else {
  12418. snprintf(to, sizeof(to), "<%s>", p->uri);
  12419. }
  12420. }
  12421. init_req(req, sipmethod, p->uri);
  12422. /* now tmp_n is available so reuse it to build the CSeq */
  12423. snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
  12424. add_header(req, "Via", p->via);
  12425. add_max_forwards(p, req);
  12426. /* This will be a no-op most of the time. However, under certain circumstances,
  12427. * NOTIFY messages will use this function for preparing the request and should
  12428. * have Route headers present.
  12429. */
  12430. add_route(req, &p->route, 0);
  12431. add_header(req, "From", from);
  12432. add_header(req, "To", to);
  12433. ast_string_field_set(p, exten, l);
  12434. build_contact(p);
  12435. add_header(req, "Contact", p->our_contact);
  12436. add_header(req, "Call-ID", p->callid);
  12437. add_header(req, "CSeq", tmp_n);
  12438. if (!ast_strlen_zero(global_useragent)) {
  12439. add_header(req, "User-Agent", global_useragent);
  12440. }
  12441. }
  12442. /*! \brief Add "Diversion" header to outgoing message
  12443. *
  12444. * We need to add a Diversion header if the owner channel of
  12445. * this dialog has redirecting information associated with it.
  12446. *
  12447. * \param req The request/response to which we will add the header
  12448. * \param pvt The sip_pvt which represents the call-leg
  12449. */
  12450. static void add_diversion(struct sip_request *req, struct sip_pvt *pvt)
  12451. {
  12452. struct ast_party_id diverting_from;
  12453. const char *reason;
  12454. int found_in_table;
  12455. char header_text[256];
  12456. char encoded_number[SIPBUFSIZE/2];
  12457. /* We skip this entirely if the configuration doesn't allow diversion headers */
  12458. if (!sip_cfg.send_diversion) {
  12459. return;
  12460. }
  12461. if (!pvt->owner) {
  12462. return;
  12463. }
  12464. diverting_from = ast_channel_redirecting_effective_from(pvt->owner);
  12465. if (!diverting_from.number.valid
  12466. || ast_strlen_zero(diverting_from.number.str)) {
  12467. return;
  12468. }
  12469. if (sip_cfg.pedanticsipchecking) {
  12470. ast_uri_encode(diverting_from.number.str, encoded_number, sizeof(encoded_number), ast_uri_sip_user);
  12471. } else {
  12472. ast_copy_string(encoded_number, diverting_from.number.str, sizeof(encoded_number));
  12473. }
  12474. reason = sip_reason_code_to_str(&ast_channel_redirecting(pvt->owner)->reason, &found_in_table);
  12475. /* We at least have a number to place in the Diversion header, which is enough */
  12476. if (!diverting_from.name.valid
  12477. || ast_strlen_zero(diverting_from.name.str)) {
  12478. snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s%s%s",
  12479. encoded_number,
  12480. ast_sockaddr_stringify_host_remote(&pvt->ourip),
  12481. found_in_table ? "" : "\"",
  12482. reason,
  12483. found_in_table ? "" : "\"");
  12484. } else {
  12485. char escaped_name[SIPBUFSIZE/2];
  12486. if (sip_cfg.pedanticsipchecking) {
  12487. ast_escape_quoted(diverting_from.name.str, escaped_name, sizeof(escaped_name));
  12488. } else {
  12489. ast_copy_string(escaped_name, diverting_from.name.str, sizeof(escaped_name));
  12490. }
  12491. snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s%s%s",
  12492. escaped_name,
  12493. encoded_number,
  12494. ast_sockaddr_stringify_host_remote(&pvt->ourip),
  12495. found_in_table ? "" : "\"",
  12496. reason,
  12497. found_in_table ? "" : "\"");
  12498. }
  12499. add_header(req, "Diversion", header_text);
  12500. }
  12501. static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
  12502. {
  12503. struct sip_pvt *pvt;
  12504. int expires;
  12505. epa_entry->publish_type = publish_type;
  12506. if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL, NULL))) {
  12507. return -1;
  12508. }
  12509. sip_pvt_lock(pvt);
  12510. if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
  12511. sip_pvt_unlock(pvt);
  12512. dialog_unlink_all(pvt);
  12513. dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
  12514. return -1;
  12515. }
  12516. ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
  12517. ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
  12518. expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
  12519. pvt->expiry = expires;
  12520. /* Bump refcount for sip_pvt's reference */
  12521. ao2_ref(epa_entry, +1);
  12522. pvt->epa_entry = epa_entry;
  12523. transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
  12524. sip_pvt_unlock(pvt);
  12525. sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
  12526. dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
  12527. return 0;
  12528. }
  12529. /*!
  12530. * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
  12531. * \param p sip_pvt structure
  12532. * \param sipmethod
  12533. * \param sdp unknown
  12534. * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
  12535. * 2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
  12536. * \param explicit_uri
  12537. */
  12538. static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
  12539. {
  12540. struct sip_request req;
  12541. struct ast_variable *var;
  12542. if (init) {/* Bump branch even on initial requests */
  12543. p->branch ^= ast_random();
  12544. p->invite_branch = p->branch;
  12545. build_via(p);
  12546. }
  12547. if (init > 1) {
  12548. initreqprep(&req, p, sipmethod, explicit_uri);
  12549. } else {
  12550. /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
  12551. reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
  12552. }
  12553. if (p->options && p->options->auth) {
  12554. add_header(&req, p->options->authheader, p->options->auth);
  12555. }
  12556. add_date(&req);
  12557. if (sipmethod == SIP_REFER && p->refer) { /* Call transfer */
  12558. if (!ast_strlen_zero(p->refer->refer_to)) {
  12559. add_header(&req, "Refer-To", p->refer->refer_to);
  12560. }
  12561. if (!ast_strlen_zero(p->refer->referred_by)) {
  12562. add_header(&req, "Referred-By", p->refer->referred_by);
  12563. }
  12564. } else if (sipmethod == SIP_SUBSCRIBE) {
  12565. if (p->subscribed == MWI_NOTIFICATION) {
  12566. add_header(&req, "Event", "message-summary");
  12567. add_header(&req, "Accept", "application/simple-message-summary");
  12568. } else if (p->subscribed == CALL_COMPLETION) {
  12569. add_header(&req, "Event", "call-completion");
  12570. add_header(&req, "Accept", "application/call-completion");
  12571. }
  12572. add_expires(&req, p->expiry);
  12573. }
  12574. /* This new INVITE is part of an attended transfer. Make sure that the
  12575. other end knows and replace the current call with this new call */
  12576. if (p->options && !ast_strlen_zero(p->options->replaces)) {
  12577. add_header(&req, "Replaces", p->options->replaces);
  12578. add_header(&req, "Require", "replaces");
  12579. }
  12580. /* Add Session-Timers related headers */
  12581. if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE
  12582. || (st_get_mode(p, 0) == SESSION_TIMER_MODE_ACCEPT
  12583. && st_get_se(p, FALSE) != DEFAULT_MIN_SE)) {
  12584. char i2astr[10];
  12585. if (!p->stimer->st_interval) {
  12586. p->stimer->st_interval = st_get_se(p, TRUE);
  12587. }
  12588. p->stimer->st_active = TRUE;
  12589. if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
  12590. snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
  12591. add_header(&req, "Session-Expires", i2astr);
  12592. }
  12593. snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
  12594. add_header(&req, "Min-SE", i2astr);
  12595. }
  12596. add_header(&req, "Allow", ALLOWED_METHODS);
  12597. add_supported(p, &req);
  12598. if (p->owner && ((p->options && p->options->addsipheaders)
  12599. || (p->refer && global_refer_addheaders))) {
  12600. struct ast_channel *chan = p->owner; /* The owner channel */
  12601. struct varshead *headp;
  12602. ast_channel_lock(chan);
  12603. headp = ast_channel_varshead(chan);
  12604. if (!headp) {
  12605. ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
  12606. } else {
  12607. const struct ast_var_t *current;
  12608. AST_LIST_TRAVERSE(headp, current, entries) {
  12609. /* SIPADDHEADER: Add SIP header to outgoing call */
  12610. if (!strncmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
  12611. char *content, *end;
  12612. const char *header = ast_var_value(current);
  12613. char *headdup = ast_strdupa(header);
  12614. /* Strip of the starting " (if it's there) */
  12615. if (*headdup == '"') {
  12616. headdup++;
  12617. }
  12618. if ((content = strchr(headdup, ':'))) {
  12619. *content++ = '\0';
  12620. content = ast_skip_blanks(content); /* Skip white space */
  12621. /* Strip the ending " (if it's there) */
  12622. end = content + strlen(content) -1;
  12623. if (*end == '"') {
  12624. *end = '\0';
  12625. }
  12626. add_header(&req, headdup, content);
  12627. if (sipdebug) {
  12628. ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
  12629. }
  12630. }
  12631. }
  12632. }
  12633. }
  12634. ast_channel_unlock(chan);
  12635. }
  12636. if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
  12637. add_rpid(&req, p);
  12638. if (sipmethod == SIP_INVITE) {
  12639. add_diversion(&req, p);
  12640. }
  12641. if (sdp) {
  12642. offered_media_list_destroy(p);
  12643. if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
  12644. ast_debug(1, "T38 is in state %u on channel %s\n", p->t38.state, p->owner ? ast_channel_name(p->owner) : "<none>");
  12645. add_sdp(&req, p, FALSE, FALSE, TRUE);
  12646. } else if (p->rtp) {
  12647. try_suggested_sip_codec(p);
  12648. add_sdp(&req, p, FALSE, TRUE, FALSE);
  12649. }
  12650. } else if (sipmethod == SIP_NOTIFY && p->notify) {
  12651. for (var = p->notify->headers; var; var = var->next) {
  12652. add_header(&req, var->name, var->value);
  12653. }
  12654. if (ast_str_strlen(p->notify->content)) {
  12655. add_content(&req, ast_str_buffer(p->notify->content));
  12656. }
  12657. } else if (sipmethod == SIP_PUBLISH) {
  12658. switch (p->epa_entry->static_data->event) {
  12659. case CALL_COMPLETION:
  12660. add_header(&req, "Event", "call-completion");
  12661. add_expires(&req, p->expiry);
  12662. if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
  12663. add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
  12664. }
  12665. if (!ast_strlen_zero(p->epa_entry->body)) {
  12666. add_header(&req, "Content-Type", "application/pidf+xml");
  12667. add_content(&req, p->epa_entry->body);
  12668. }
  12669. default:
  12670. break;
  12671. }
  12672. }
  12673. if (!p->initreq.headers || init > 2) {
  12674. initialize_initreq(p, &req);
  12675. }
  12676. if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
  12677. p->lastinvite = p->ocseq;
  12678. }
  12679. return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
  12680. }
  12681. /*! \brief Send a subscription or resubscription for MWI */
  12682. static int sip_subscribe_mwi_do(const void *data)
  12683. {
  12684. struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
  12685. if (!mwi) {
  12686. return -1;
  12687. }
  12688. mwi->resub = -1;
  12689. __sip_subscribe_mwi_do(mwi);
  12690. ao2_t_ref(mwi, -1, "unref mwi to balance ast_sched_add");
  12691. return 0;
  12692. }
  12693. static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
  12694. {
  12695. struct sip_registry *reg = data;
  12696. const char *old_str;
  12697. /* This shouldn't happen, but just in case */
  12698. if (ast_sockaddr_isnull(new)) {
  12699. ast_debug(1, "Empty sockaddr change...ignoring!\n");
  12700. return;
  12701. }
  12702. if (!ast_sockaddr_port(new)) {
  12703. ast_sockaddr_set_port(new, reg->portno);
  12704. }
  12705. old_str = ast_strdupa(ast_sockaddr_stringify(old));
  12706. ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
  12707. ast_sockaddr_copy(&reg->us, new);
  12708. }
  12709. static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
  12710. {
  12711. struct sip_peer *peer = data;
  12712. const char *old_str;
  12713. /* This shouldn't happen, but just in case */
  12714. if (ast_sockaddr_isnull(new)) {
  12715. ast_debug(1, "Empty sockaddr change...ignoring!\n");
  12716. return;
  12717. }
  12718. if (!ast_sockaddr_isnull(&peer->addr)) {
  12719. ao2_unlink(peers_by_ip, peer);
  12720. }
  12721. if (!ast_sockaddr_port(new)) {
  12722. ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
  12723. }
  12724. old_str = ast_strdupa(ast_sockaddr_stringify(old));
  12725. ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
  12726. ao2_lock(peer);
  12727. ast_sockaddr_copy(&peer->addr, new);
  12728. ao2_unlock(peer);
  12729. ao2_link(peers_by_ip, peer);
  12730. }
  12731. static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
  12732. {
  12733. struct sip_subscription_mwi *mwi = data;
  12734. const char *old_str;
  12735. /* This shouldn't happen, but just in case */
  12736. if (ast_sockaddr_isnull(new)) {
  12737. ast_debug(1, "Empty sockaddr change...ignoring!\n");
  12738. return;
  12739. }
  12740. old_str = ast_strdupa(ast_sockaddr_stringify(old));
  12741. ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
  12742. ast_sockaddr_copy(&mwi->us, new);
  12743. }
  12744. /*! \brief Actually setup an MWI subscription or resubscribe */
  12745. static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
  12746. {
  12747. /* If we have no DNS manager let's do a lookup */
  12748. if (!mwi->dnsmgr) {
  12749. char transport[MAXHOSTNAMELEN];
  12750. snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
  12751. mwi->us.ss.ss_family = get_address_family_filter(mwi->transport); /* Filter address family */
  12752. ao2_t_ref(mwi, +1, "dnsmgr reference to mwi");
  12753. ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, mwi);
  12754. if (!mwi->dnsmgr) {
  12755. ao2_t_ref(mwi, -1, "dnsmgr disabled, remove reference");
  12756. }
  12757. }
  12758. /* If we already have a subscription up simply send a resubscription */
  12759. if (mwi->call) {
  12760. transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
  12761. return 0;
  12762. }
  12763. /* Create a dialog that we will use for the subscription */
  12764. if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
  12765. return -1;
  12766. }
  12767. ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
  12768. if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
  12769. ast_sockaddr_set_port(&mwi->us, mwi->portno);
  12770. }
  12771. /* Setup the destination of our subscription */
  12772. if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
  12773. dialog_unlink_all(mwi->call);
  12774. mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
  12775. return 0;
  12776. }
  12777. mwi->call->expiry = mwi_expiry;
  12778. if (!mwi->dnsmgr && mwi->portno) {
  12779. ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
  12780. ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
  12781. } else {
  12782. mwi->portno = ast_sockaddr_port(&mwi->call->sa);
  12783. }
  12784. /* Set various other information */
  12785. if (!ast_strlen_zero(mwi->authuser)) {
  12786. ast_string_field_set(mwi->call, peername, mwi->authuser);
  12787. ast_string_field_set(mwi->call, authname, mwi->authuser);
  12788. ast_string_field_set(mwi->call, fromuser, mwi->authuser);
  12789. } else {
  12790. ast_string_field_set(mwi->call, peername, mwi->username);
  12791. ast_string_field_set(mwi->call, authname, mwi->username);
  12792. ast_string_field_set(mwi->call, fromuser, mwi->username);
  12793. }
  12794. ast_string_field_set(mwi->call, username, mwi->username);
  12795. if (!ast_strlen_zero(mwi->secret)) {
  12796. ast_string_field_set(mwi->call, peersecret, mwi->secret);
  12797. }
  12798. set_socket_transport(&mwi->call->socket, mwi->transport);
  12799. mwi->call->socket.port = htons(mwi->portno);
  12800. ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
  12801. build_contact(mwi->call);
  12802. build_via(mwi->call);
  12803. /* Change the dialog callid. */
  12804. change_callid_pvt(mwi->call, NULL);
  12805. ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
  12806. /* Associate the call with us */
  12807. mwi->call->mwi = ao2_t_bump(mwi, "Reference mwi from it's call");
  12808. mwi->call->subscribed = MWI_NOTIFICATION;
  12809. /* Actually send the packet */
  12810. transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
  12811. return 0;
  12812. }
  12813. /*!
  12814. * \internal
  12815. * \brief Find the channel that is causing the RINGING update, ref'd
  12816. */
  12817. static struct ast_channel *find_ringing_channel(struct ao2_container *device_state_info, struct sip_pvt *p)
  12818. {
  12819. struct ao2_iterator citer;
  12820. struct ast_device_state_info *device_state;
  12821. struct ast_channel *c = NULL;
  12822. struct timeval tv = {0,};
  12823. /* iterate ringing devices and get the oldest of all causing channels */
  12824. citer = ao2_iterator_init(device_state_info, 0);
  12825. for (; (device_state = ao2_iterator_next(&citer)); ao2_ref(device_state, -1)) {
  12826. if (!device_state->causing_channel || (device_state->device_state != AST_DEVICE_RINGING &&
  12827. device_state->device_state != AST_DEVICE_RINGINUSE)) {
  12828. continue;
  12829. }
  12830. ast_channel_lock(device_state->causing_channel);
  12831. if (ast_tvzero(tv) || ast_tvcmp(ast_channel_creationtime(device_state->causing_channel), tv) < 0) {
  12832. c = device_state->causing_channel;
  12833. tv = ast_channel_creationtime(c);
  12834. }
  12835. ast_channel_unlock(device_state->causing_channel);
  12836. }
  12837. ao2_iterator_destroy(&citer);
  12838. return c ? ast_channel_ref(c) : NULL;
  12839. }
  12840. /* XXX Candidate for moving into its own file */
  12841. static int allow_notify_user_presence(struct sip_pvt *p)
  12842. {
  12843. return (strstr(p->useragent, "Digium")) ? 1 : 0;
  12844. }
  12845. /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
  12846. 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)
  12847. {
  12848. enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
  12849. const char *statestring = "terminated";
  12850. const char *pidfstate = "--";
  12851. const char *pidfnote ="Ready";
  12852. char hint[AST_MAX_EXTENSION];
  12853. switch (data->state) {
  12854. case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
  12855. statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
  12856. local_state = NOTIFY_INUSE;
  12857. pidfstate = "busy";
  12858. pidfnote = "Ringing";
  12859. break;
  12860. case AST_EXTENSION_RINGING:
  12861. statestring = "early";
  12862. local_state = NOTIFY_INUSE;
  12863. pidfstate = "busy";
  12864. pidfnote = "Ringing";
  12865. break;
  12866. case AST_EXTENSION_INUSE:
  12867. statestring = "confirmed";
  12868. local_state = NOTIFY_INUSE;
  12869. pidfstate = "busy";
  12870. pidfnote = "On the phone";
  12871. break;
  12872. case AST_EXTENSION_BUSY:
  12873. statestring = "confirmed";
  12874. local_state = NOTIFY_CLOSED;
  12875. pidfstate = "busy";
  12876. pidfnote = "On the phone";
  12877. break;
  12878. case AST_EXTENSION_UNAVAILABLE:
  12879. statestring = "terminated";
  12880. local_state = NOTIFY_CLOSED;
  12881. pidfstate = "away";
  12882. pidfnote = "Unavailable";
  12883. break;
  12884. case AST_EXTENSION_ONHOLD:
  12885. statestring = "confirmed";
  12886. local_state = NOTIFY_CLOSED;
  12887. pidfstate = "busy";
  12888. pidfnote = "On hold";
  12889. break;
  12890. case AST_EXTENSION_NOT_INUSE:
  12891. default:
  12892. /* Default setting */
  12893. break;
  12894. }
  12895. /* Check which device/devices we are watching and if they are registered */
  12896. if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
  12897. char *hint2;
  12898. char *individual_hint = NULL;
  12899. int hint_count = 0, unavailable_count = 0;
  12900. /* strip off any possible PRESENCE providers from hint */
  12901. if ((hint2 = strrchr(hint, ','))) {
  12902. *hint2 = '\0';
  12903. }
  12904. hint2 = hint;
  12905. while ((individual_hint = strsep(&hint2, "&"))) {
  12906. hint_count++;
  12907. if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
  12908. unavailable_count++;
  12909. }
  12910. /* If none of the hinted devices are registered, we will
  12911. * override notification and show no availability.
  12912. */
  12913. if (hint_count > 0 && hint_count == unavailable_count) {
  12914. local_state = NOTIFY_CLOSED;
  12915. pidfstate = "away";
  12916. pidfnote = "Not online";
  12917. }
  12918. }
  12919. switch (subscribed) {
  12920. case XPIDF_XML:
  12921. case CPIM_PIDF_XML:
  12922. ast_str_append(tmp, 0,
  12923. "<?xml version=\"1.0\"?>\n"
  12924. "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
  12925. "<presence>\n");
  12926. ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
  12927. ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
  12928. ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
  12929. ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
  12930. ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
  12931. ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
  12932. break;
  12933. case PIDF_XML: /* Eyebeam supports this format */
  12934. ast_str_append(tmp, 0,
  12935. "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
  12936. "<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);
  12937. ast_str_append(tmp, 0, "<pp:person><status>\n");
  12938. if (pidfstate[0] != '-') {
  12939. ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
  12940. }
  12941. ast_str_append(tmp, 0, "</status></pp:person>\n");
  12942. ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
  12943. ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
  12944. ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
  12945. if (pidfstate[0] == 'b') /* Busy? Still open ... */
  12946. ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
  12947. else
  12948. ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
  12949. if (allow_notify_user_presence(p) && (data->presence_state != AST_PRESENCE_INVALID)
  12950. && (data->presence_state != AST_PRESENCE_NOT_SET)) {
  12951. ast_str_append(tmp, 0, "</tuple>\n");
  12952. ast_str_append(tmp, 0, "<tuple id=\"digium-presence\">\n");
  12953. ast_str_append(tmp, 0, "<status>\n");
  12954. ast_str_append(tmp, 0, "<digium_presence type=\"%s\" subtype=\"%s\">%s</digium_presence>\n",
  12955. ast_presence_state2str(data->presence_state),
  12956. S_OR(data->presence_subtype, ""),
  12957. S_OR(data->presence_message, ""));
  12958. ast_str_append(tmp, 0, "</status>\n");
  12959. ast_test_suite_event_notify("DIGIUM_PRESENCE_SENT",
  12960. "PresenceState: %s\r\n"
  12961. "Subtype: %s\r\n"
  12962. "Message: %s",
  12963. ast_presence_state2str(data->presence_state),
  12964. S_OR(data->presence_subtype, ""),
  12965. S_OR(data->presence_message, ""));
  12966. }
  12967. ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
  12968. break;
  12969. case DIALOG_INFO_XML: /* SNOM subscribes in this format */
  12970. ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
  12971. 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);
  12972. if (data->state > 0 && (data->state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
  12973. /* Twice the extension length should be enough for XML encoding */
  12974. char local_display[AST_MAX_EXTENSION * 2];
  12975. char remote_display[AST_MAX_EXTENSION * 2];
  12976. char *local_target = ast_strdupa(mto);
  12977. /* It may seem odd to base the remote_target on the To header here,
  12978. * but testing by reporters on issue ASTERISK-16735 found that basing
  12979. * on the From header would cause ringing state hints to not work
  12980. * properly on certain SNOM devices. If you are using notifycid properly
  12981. * (i.e. in the same extension and context as the dialed call) then this
  12982. * should not be an issue since the data will be overwritten shortly
  12983. * with channel caller ID
  12984. */
  12985. char *remote_target = ast_strdupa(mto);
  12986. ast_xml_escape(exten, local_display, sizeof(local_display));
  12987. ast_xml_escape(exten, remote_display, sizeof(remote_display));
  12988. /* There are some limitations to how this works. The primary one is that the
  12989. callee must be dialing the same extension that is being monitored. Simply dialing
  12990. the hint'd device is not sufficient. */
  12991. if (sip_cfg.notifycid) {
  12992. struct ast_channel *callee;
  12993. callee = find_ringing_channel(data->device_state_info, p);
  12994. if (callee) {
  12995. static char *anonymous = "anonymous";
  12996. static char *invalid = "anonymous.invalid";
  12997. char *cid_num;
  12998. char *connected_num;
  12999. int need;
  13000. int cid_num_restricted, connected_num_restricted;
  13001. ast_channel_lock(callee);
  13002. cid_num_restricted = (ast_channel_caller(callee)->id.number.presentation &
  13003. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
  13004. cid_num = S_COR(ast_channel_caller(callee)->id.number.valid,
  13005. S_COR(cid_num_restricted, anonymous,
  13006. ast_channel_caller(callee)->id.number.str), "");
  13007. need = strlen(cid_num) + (cid_num_restricted ? strlen(invalid) :
  13008. strlen(p->fromdomain)) + sizeof("sip:@");
  13009. local_target = ast_alloca(need);
  13010. snprintf(local_target, need, "sip:%s@%s", cid_num,
  13011. cid_num_restricted ? invalid : p->fromdomain);
  13012. ast_xml_escape(S_COR(ast_channel_caller(callee)->id.name.valid,
  13013. S_COR((ast_channel_caller(callee)->id.name.presentation &
  13014. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
  13015. ast_channel_caller(callee)->id.name.str), ""),
  13016. local_display, sizeof(local_display));
  13017. connected_num_restricted = (ast_channel_connected(callee)->id.number.presentation &
  13018. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
  13019. connected_num = S_COR(ast_channel_connected(callee)->id.number.valid,
  13020. S_COR(connected_num_restricted, anonymous,
  13021. ast_channel_connected(callee)->id.number.str), "");
  13022. need = strlen(connected_num) + (connected_num_restricted ? strlen(invalid) :
  13023. strlen(p->fromdomain)) + sizeof("sip:@");
  13024. remote_target = ast_alloca(need);
  13025. snprintf(remote_target, need, "sip:%s@%s", connected_num,
  13026. connected_num_restricted ? invalid : p->fromdomain);
  13027. ast_xml_escape(S_COR(ast_channel_connected(callee)->id.name.valid,
  13028. S_COR((ast_channel_connected(callee)->id.name.presentation &
  13029. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
  13030. ast_channel_connected(callee)->id.name.str), ""),
  13031. remote_display, sizeof(remote_display));
  13032. ast_channel_unlock(callee);
  13033. callee = ast_channel_unref(callee);
  13034. }
  13035. /* We create a fake call-id which the phone will send back in an INVITE
  13036. Replaces header which we can grab and do some magic with. */
  13037. if (sip_cfg.pedanticsipchecking) {
  13038. ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
  13039. exten, p->callid, p->theirtag, p->tag);
  13040. } else {
  13041. ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
  13042. exten, p->callid);
  13043. }
  13044. ast_str_append(tmp, 0,
  13045. "<remote>\n"
  13046. /* See the limitations of this above. Luckily the phone seems to still be
  13047. happy when these values are not correct. */
  13048. "<identity display=\"%s\">%s</identity>\n"
  13049. "<target uri=\"%s\"/>\n"
  13050. "</remote>\n"
  13051. "<local>\n"
  13052. "<identity display=\"%s\">%s</identity>\n"
  13053. "<target uri=\"%s\"/>\n"
  13054. "</local>\n",
  13055. remote_display, remote_target, remote_target, local_display, local_target, local_target);
  13056. } else {
  13057. ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
  13058. }
  13059. } else {
  13060. ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
  13061. }
  13062. ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
  13063. if (data->state == AST_EXTENSION_ONHOLD) {
  13064. ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
  13065. "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
  13066. "</target>\n</local>\n", mto);
  13067. }
  13068. ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
  13069. break;
  13070. case NONE:
  13071. default:
  13072. break;
  13073. }
  13074. }
  13075. static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
  13076. {
  13077. struct sip_request req;
  13078. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  13079. char uri[SIPBUFSIZE];
  13080. char state_str[64];
  13081. char subscription_state_hdr[64];
  13082. if (state < CC_QUEUED || state > CC_READY) {
  13083. ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%u)\n", state);
  13084. return -1;
  13085. }
  13086. reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
  13087. snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
  13088. add_header(&req, "Event", "call-completion");
  13089. add_header(&req, "Content-Type", "application/call-completion");
  13090. snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
  13091. add_header(&req, "Subscription-State", subscription_state_hdr);
  13092. if (state == CC_READY) {
  13093. generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
  13094. snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
  13095. }
  13096. add_content(&req, state_str);
  13097. if (state == CC_READY) {
  13098. add_content(&req, uri);
  13099. }
  13100. return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
  13101. }
  13102. /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
  13103. static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout)
  13104. {
  13105. struct ast_str *tmp = ast_str_alloca(4000);
  13106. char from[256], to[256];
  13107. char *c, *mfrom, *mto;
  13108. struct sip_request req;
  13109. const struct cfsubscription_types *subscriptiontype;
  13110. /* If the subscription has not yet been accepted do not send a NOTIFY */
  13111. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  13112. return 0;
  13113. }
  13114. memset(from, 0, sizeof(from));
  13115. memset(to, 0, sizeof(to));
  13116. subscriptiontype = find_subscription_type(p->subscribed);
  13117. ast_copy_string(from, sip_get_header(&p->initreq, "From"), sizeof(from));
  13118. c = get_in_brackets(from);
  13119. if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
  13120. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  13121. return -1;
  13122. }
  13123. mfrom = remove_uri_parameters(c);
  13124. ast_copy_string(to, sip_get_header(&p->initreq, "To"), sizeof(to));
  13125. c = get_in_brackets(to);
  13126. if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
  13127. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  13128. return -1;
  13129. }
  13130. mto = remove_uri_parameters(c);
  13131. reqprep(&req, p, SIP_NOTIFY, 0, 1);
  13132. switch(data->state) {
  13133. case AST_EXTENSION_DEACTIVATED:
  13134. if (timeout)
  13135. add_header(&req, "Subscription-State", "terminated;reason=timeout");
  13136. else {
  13137. add_header(&req, "Subscription-State", "terminated;reason=probation");
  13138. add_header(&req, "Retry-After", "60");
  13139. }
  13140. break;
  13141. case AST_EXTENSION_REMOVED:
  13142. add_header(&req, "Subscription-State", "terminated;reason=noresource");
  13143. break;
  13144. default:
  13145. if (p->expiry)
  13146. add_header(&req, "Subscription-State", "active");
  13147. else /* Expired */
  13148. add_header(&req, "Subscription-State", "terminated;reason=timeout");
  13149. }
  13150. switch (p->subscribed) {
  13151. case XPIDF_XML:
  13152. case CPIM_PIDF_XML:
  13153. add_header(&req, "Event", subscriptiontype->event);
  13154. state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
  13155. add_header(&req, "Content-Type", subscriptiontype->mediatype);
  13156. p->dialogver++;
  13157. break;
  13158. case PIDF_XML: /* Eyebeam supports this format */
  13159. add_header(&req, "Event", subscriptiontype->event);
  13160. state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
  13161. add_header(&req, "Content-Type", subscriptiontype->mediatype);
  13162. p->dialogver++;
  13163. break;
  13164. case DIALOG_INFO_XML: /* SNOM subscribes in this format */
  13165. add_header(&req, "Event", subscriptiontype->event);
  13166. state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
  13167. add_header(&req, "Content-Type", subscriptiontype->mediatype);
  13168. p->dialogver++;
  13169. break;
  13170. case NONE:
  13171. default:
  13172. break;
  13173. }
  13174. add_content(&req, ast_str_buffer(tmp));
  13175. p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
  13176. /* Send as XMIT_CRITICAL as we may never receive a 200 OK Response which clears p->pendinginvite.
  13177. *
  13178. * extensionstate_update() uses p->pendinginvite for queuing control.
  13179. * Updates stall if pendinginvite <> 0.
  13180. *
  13181. * The most appropriate solution is to remove the subscription when the NOTIFY transaction fails.
  13182. * The client will re-subscribe after restarting or maxexpiry timeout.
  13183. */
  13184. /* RFC6665 4.2.2. Sending State Information to Subscribers
  13185. * If the NOTIFY request fails due to expiration of SIP Timer F (transaction timeout),
  13186. * the notifier SHOULD remove the subscription.
  13187. */
  13188. return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  13189. }
  13190. /*! \brief Notify user of messages waiting in voicemail (RFC3842)
  13191. \note - Notification only works for registered peers with mailbox= definitions
  13192. in sip.conf
  13193. - We use the SIP Event package message-summary
  13194. MIME type defaults to "application/simple-message-summary";
  13195. */
  13196. static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
  13197. {
  13198. struct sip_request req;
  13199. struct ast_str *out = ast_str_alloca(500);
  13200. int ourport = (p->fromdomainport && (p->fromdomainport != STANDARD_SIP_PORT)) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
  13201. const char *domain;
  13202. const char *exten = S_OR(vmexten, default_vmexten);
  13203. initreqprep(&req, p, SIP_NOTIFY, NULL);
  13204. add_header(&req, "Event", "message-summary");
  13205. add_header(&req, "Content-Type", default_notifymime);
  13206. ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
  13207. /* domain initialization occurs here because initreqprep changes ast_sockaddr_stringify string. */
  13208. domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
  13209. if (!sip_standard_port(p->socket.type, ourport)) {
  13210. if (p->socket.type == AST_TRANSPORT_UDP) {
  13211. ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
  13212. } else {
  13213. ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, sip_get_transport(p->socket.type));
  13214. }
  13215. } else {
  13216. if (p->socket.type == AST_TRANSPORT_UDP) {
  13217. ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
  13218. } else {
  13219. ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, sip_get_transport(p->socket.type));
  13220. }
  13221. }
  13222. /* Cisco has a bug in the SIP stack where it can't accept the
  13223. (0/0) notification. This can temporarily be disabled in
  13224. sip.conf with the "buggymwi" option */
  13225. ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
  13226. newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
  13227. if (p->subscribed) {
  13228. if (p->expiry) {
  13229. add_header(&req, "Subscription-State", "active");
  13230. } else { /* Expired */
  13231. add_header(&req, "Subscription-State", "terminated;reason=timeout");
  13232. }
  13233. }
  13234. add_content(&req, ast_str_buffer(out));
  13235. if (!p->initreq.headers) {
  13236. initialize_initreq(p, &req);
  13237. }
  13238. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13239. }
  13240. /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
  13241. static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
  13242. {
  13243. struct sip_request req;
  13244. char tmp[SIPBUFSIZE/2];
  13245. reqprep(&req, p, SIP_NOTIFY, 0, 1);
  13246. snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
  13247. add_header(&req, "Event", tmp);
  13248. add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
  13249. add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
  13250. add_header(&req, "Allow", ALLOWED_METHODS);
  13251. add_supported(p, &req);
  13252. snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
  13253. add_content(&req, tmp);
  13254. if (!p->initreq.headers) {
  13255. initialize_initreq(p, &req);
  13256. }
  13257. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13258. }
  13259. static int manager_sipnotify(struct mansession *s, const struct message *m)
  13260. {
  13261. const char *channame = astman_get_header(m, "Channel");
  13262. struct ast_variable *vars = astman_get_variables_order(m, ORDER_NATURAL);
  13263. struct sip_pvt *p;
  13264. struct ast_variable *header, *var;
  13265. if (ast_strlen_zero(channame)) {
  13266. astman_send_error(s, m, "SIPNotify requires a channel name");
  13267. return 0;
  13268. }
  13269. if (!strncasecmp(channame, "sip/", 4)) {
  13270. channame += 4;
  13271. }
  13272. if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
  13273. astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
  13274. return 0;
  13275. }
  13276. if (create_addr(p, channame, NULL, 0)) {
  13277. /* Maybe they're not registered, etc. */
  13278. dialog_unlink_all(p);
  13279. dialog_unref(p, "unref dialog inside for loop" );
  13280. /* sip_destroy(p); */
  13281. astman_send_error(s, m, "Could not create address");
  13282. return 0;
  13283. }
  13284. /* Notify is outgoing call */
  13285. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  13286. sip_notify_alloc(p);
  13287. p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
  13288. for (var = vars; var; var = var->next) {
  13289. if (!strcasecmp(var->name, "Content")) {
  13290. if (ast_str_strlen(p->notify->content))
  13291. ast_str_append(&p->notify->content, 0, "\r\n");
  13292. ast_str_append(&p->notify->content, 0, "%s", var->value);
  13293. } else if (!strcasecmp(var->name, "Content-Length")) {
  13294. ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
  13295. } else {
  13296. header->next = ast_variable_new(var->name, var->value, "");
  13297. header = header->next;
  13298. }
  13299. }
  13300. sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
  13301. transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
  13302. dialog_unref(p, "bump down the count of p since we're done with it.");
  13303. astman_send_ack(s, m, "Notify Sent");
  13304. ast_variables_destroy(vars);
  13305. return 0;
  13306. }
  13307. /*! \brief Send a provisional response indicating that a call was redirected
  13308. */
  13309. static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
  13310. {
  13311. struct sip_request resp;
  13312. if (ast_channel_state(p->owner) == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  13313. return;
  13314. }
  13315. respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
  13316. add_diversion(&resp, p);
  13317. send_response(p, &resp, XMIT_UNRELIABLE, 0);
  13318. }
  13319. /*! \brief Notify peer that the connected line has changed */
  13320. static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
  13321. {
  13322. struct ast_party_id connected_id = ast_channel_connected_effective_id(p->owner);
  13323. if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
  13324. return;
  13325. }
  13326. if (!connected_id.number.valid
  13327. || ast_strlen_zero(connected_id.number.str)) {
  13328. return;
  13329. }
  13330. append_history(p, "ConnectedLine", "%s party is now %s <%s>",
  13331. ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
  13332. S_COR(connected_id.name.valid, connected_id.name.str, ""),
  13333. S_COR(connected_id.number.valid, connected_id.number.str, ""));
  13334. if (ast_channel_state(p->owner) == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  13335. struct sip_request req;
  13336. if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
  13337. reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
  13338. add_header(&req, "Allow", ALLOWED_METHODS);
  13339. add_supported(p, &req);
  13340. add_rpid(&req, p);
  13341. add_sdp(&req, p, FALSE, TRUE, FALSE);
  13342. initialize_initreq(p, &req);
  13343. p->lastinvite = p->ocseq;
  13344. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  13345. p->invitestate = INV_CALLING;
  13346. send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  13347. } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) {
  13348. reqprep(&req, p, SIP_UPDATE, 0, 1);
  13349. add_rpid(&req, p);
  13350. add_header(&req, "X-Asterisk-rpid-update", "Yes");
  13351. send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  13352. } else {
  13353. /* We cannot send the update yet, so we have to wait until we can */
  13354. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  13355. }
  13356. } else {
  13357. ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  13358. if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
  13359. struct sip_request resp;
  13360. if ((ast_channel_state(p->owner) == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
  13361. ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  13362. respprep(&resp, p, "180 Ringing", &p->initreq);
  13363. add_rpid(&resp, p);
  13364. send_response(p, &resp, XMIT_UNRELIABLE, 0);
  13365. ast_set_flag(&p->flags[0], SIP_RINGING);
  13366. } else if (ast_channel_state(p->owner) == AST_STATE_RINGING) {
  13367. ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  13368. respprep(&resp, p, "183 Session Progress", &p->initreq);
  13369. add_rpid(&resp, p);
  13370. send_response(p, &resp, XMIT_UNRELIABLE, 0);
  13371. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  13372. } else {
  13373. 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)));
  13374. }
  13375. }
  13376. }
  13377. }
  13378. static const struct _map_x_s regstatestrings[] = {
  13379. { REG_STATE_FAILED, "Failed" },
  13380. { REG_STATE_UNREGISTERED, "Unregistered"},
  13381. { REG_STATE_REGSENT, "Request Sent"},
  13382. { REG_STATE_AUTHSENT, "Auth. Sent"},
  13383. { REG_STATE_REGISTERED, "Registered"},
  13384. { REG_STATE_REJECTED, "Rejected"},
  13385. { REG_STATE_TIMEOUT, "Timeout"},
  13386. { REG_STATE_NOAUTH, "No Authentication"},
  13387. { -1, NULL } /* terminator */
  13388. };
  13389. /*! \brief Convert registration state status to string */
  13390. static const char *regstate2str(enum sipregistrystate regstate)
  13391. {
  13392. return map_x_s(regstatestrings, regstate, "Unknown");
  13393. }
  13394. static void sip_publish_registry(const char *username, const char *domain, const char *status)
  13395. {
  13396. ast_system_publish_registry("SIP", username, domain, status, NULL);
  13397. }
  13398. /*! \brief Update registration with SIP Proxy.
  13399. * Called from the scheduler when the previous registration expires,
  13400. * so we don't have to cancel the pending event.
  13401. * We assume the reference so the sip_registry is valid, since it
  13402. * is stored in the scheduled event anyways.
  13403. */
  13404. static int sip_reregister(const void *data)
  13405. {
  13406. /* if we are here, we know that we need to reregister. */
  13407. struct sip_registry *r = (struct sip_registry *) data;
  13408. /* if we couldn't get a reference to the registry object, punt */
  13409. if (!r) {
  13410. return 0;
  13411. }
  13412. if (r->call && r->call->do_history) {
  13413. append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
  13414. }
  13415. /* Since registry's are only added/removed by the the monitor thread, this
  13416. may be overkill to reference/dereference at all here */
  13417. if (sipdebug) {
  13418. ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
  13419. }
  13420. r->expire = -1;
  13421. r->expiry = r->configured_expiry;
  13422. __sip_do_register(r);
  13423. ao2_t_ref(r, -1, "unref the re-register scheduled event");
  13424. return 0;
  13425. }
  13426. /*! \brief Register with SIP proxy
  13427. \return see \ref __sip_xmit
  13428. */
  13429. static int __sip_do_register(struct sip_registry *r)
  13430. {
  13431. int res;
  13432. res = transmit_register(r, SIP_REGISTER, NULL, NULL);
  13433. return res;
  13434. }
  13435. /*! \brief Registration timeout, register again
  13436. * Registered as a timeout handler during transmit_register(),
  13437. * to retransmit the packet if a reply does not come back.
  13438. * This is called by the scheduler so the event is not pending anymore when
  13439. * we are called.
  13440. */
  13441. static int sip_reg_timeout(const void *data)
  13442. {
  13443. /* if we are here, our registration timed out, so we'll just do it over */
  13444. struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
  13445. struct sip_pvt *p;
  13446. /* if we couldn't get a reference to the registry object, punt */
  13447. if (!r) {
  13448. return 0;
  13449. }
  13450. if (r->dnsmgr) {
  13451. /* If the registration has timed out, maybe the IP changed. Force a refresh. */
  13452. ast_dnsmgr_refresh(r->dnsmgr);
  13453. }
  13454. /* If the initial tranmission failed, we may not have an existing dialog,
  13455. * so it is possible that r->call == NULL.
  13456. * Otherwise destroy it, as we have a timeout so we don't want it.
  13457. */
  13458. if (r->call) {
  13459. /* Unlink us, destroy old call. Locking is not relevant here because all this happens
  13460. in the single SIP manager thread. */
  13461. p = r->call;
  13462. sip_pvt_lock(p);
  13463. pvt_set_needdestroy(p, "registration timeout");
  13464. /* Pretend to ACK anything just in case */
  13465. __sip_pretend_ack(p);
  13466. sip_pvt_unlock(p);
  13467. /* decouple the two objects */
  13468. /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
  13469. ao2_t_replace(p->registry, NULL, "p->registry unreffed");
  13470. r->call = dialog_unref(r->call, "unrefing r->call");
  13471. }
  13472. /* If we have a limit, stop registration and give up */
  13473. r->timeout = -1;
  13474. if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
  13475. /* Ok, enough is enough. Don't try any more */
  13476. /* We could add an external notification here...
  13477. steal it from app_voicemail :-) */
  13478. ast_log(LOG_NOTICE, " -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
  13479. r->regstate = REG_STATE_FAILED;
  13480. } else {
  13481. r->regstate = REG_STATE_UNREGISTERED;
  13482. transmit_register(r, SIP_REGISTER, NULL, NULL);
  13483. ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
  13484. }
  13485. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  13486. ao2_t_ref(r, -1, "unreffing registry_unref r");
  13487. return 0;
  13488. }
  13489. static const char *sip_sanitized_host(const char *host)
  13490. {
  13491. struct ast_sockaddr addr = { { 0, 0, }, };
  13492. /* peer/sip_pvt->tohost and sip_registry->hostname should never have a port
  13493. * in them, so we use PARSE_PORT_FORBID here. If this lookup fails, we return
  13494. * the original host which is most likely a host name and not an IP. */
  13495. if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
  13496. return host;
  13497. }
  13498. return ast_sockaddr_stringify_host_remote(&addr);
  13499. }
  13500. /*! \brief Transmit register to SIP proxy or UA
  13501. * auth = NULL on the initial registration (from sip_reregister())
  13502. */
  13503. static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
  13504. {
  13505. struct sip_request req;
  13506. char from[256];
  13507. char to[256];
  13508. char tmp[80];
  13509. char addr[80];
  13510. struct sip_pvt *p;
  13511. struct sip_peer *peer = NULL;
  13512. int res;
  13513. int portno = 0;
  13514. /* exit if we are already in process with this registrar ?*/
  13515. if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
  13516. if (r) {
  13517. ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
  13518. }
  13519. return 0;
  13520. }
  13521. if (r->dnsmgr == NULL) {
  13522. char transport[MAXHOSTNAMELEN];
  13523. peer = sip_find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
  13524. snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static sip_get_transport function */
  13525. r->us.ss.ss_family = get_address_family_filter(r->transport); /* Filter address family */
  13526. /* No point in doing a DNS lookup of the register hostname if we're just going to
  13527. * end up using an outbound proxy. obproxy_get is safe to call with either of r->call
  13528. * or peer NULL. Since we're only concerned with its existence, we're not going to
  13529. * bother getting a ref to the proxy*/
  13530. if (!obproxy_get(r->call, peer)) {
  13531. ao2_t_ref(r, +1, "add reg ref for dnsmgr");
  13532. ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
  13533. if (!r->dnsmgr) {
  13534. /*dnsmgr refresh disabled, no reference added! */
  13535. ao2_t_ref(r, -1, "remove reg ref, dnsmgr disabled");
  13536. }
  13537. }
  13538. if (peer) {
  13539. peer = sip_unref_peer(peer, "removing peer ref for dnsmgr_lookup");
  13540. }
  13541. }
  13542. if (r->call) { /* We have a registration */
  13543. if (!auth) {
  13544. ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
  13545. return 0;
  13546. } else {
  13547. p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
  13548. ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
  13549. }
  13550. } else {
  13551. /* Build callid for registration if we haven't registered before */
  13552. if (!r->callid_valid) {
  13553. build_callid_registry(r, &internip, default_fromdomain);
  13554. build_localtag_registry(r);
  13555. r->callid_valid = TRUE;
  13556. }
  13557. /* Allocate SIP dialog for registration */
  13558. if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL, NULL))) {
  13559. ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
  13560. return 0;
  13561. }
  13562. /* reset tag to consistent value from registry */
  13563. ast_string_field_set(p, tag, r->localtag);
  13564. if (p->do_history) {
  13565. append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
  13566. }
  13567. p->socket.type = r->transport;
  13568. /* Use port number specified if no SRV record was found */
  13569. if (!ast_sockaddr_isnull(&r->us)) {
  13570. if (!ast_sockaddr_port(&r->us) && r->portno) {
  13571. ast_sockaddr_set_port(&r->us, r->portno);
  13572. }
  13573. /* It is possible that DNS was unavailable at the time the peer was created.
  13574. * Here, if we've updated the address in the registry via manually calling
  13575. * ast_dnsmgr_lookup_cb() above, then we call the same function that dnsmgr would
  13576. * call if it was updating a peer's address */
  13577. if ((peer = sip_find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
  13578. if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
  13579. on_dns_update_peer(&peer->addr, &r->us, peer);
  13580. }
  13581. peer = sip_unref_peer(peer, "unref after sip_find_peer");
  13582. }
  13583. }
  13584. /* Find address to hostname */
  13585. if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
  13586. /* we have what we hope is a temporary network error,
  13587. * probably DNS. We need to reschedule a registration try */
  13588. dialog_unlink_all(p);
  13589. p = dialog_unref(p, "unref dialog after unlink_all");
  13590. if (r->timeout > -1) {
  13591. AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
  13592. ao2_t_ref(_data, -1, "del for REPLACE of registry ptr"),
  13593. ao2_t_ref(r, -1, "object ptr dec when SCHED_REPLACE add failed"),
  13594. ao2_t_ref(r, +1, "add for REPLACE registry ptr"));
  13595. ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
  13596. } else {
  13597. r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, ao2_t_bump(r, "add for REPLACE registry ptr"));
  13598. 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);
  13599. }
  13600. r->regattempts++;
  13601. return 0;
  13602. }
  13603. /* Copy back Call-ID in case create_addr changed it */
  13604. ast_string_field_set(r, callid, p->callid);
  13605. if (!r->dnsmgr && r->portno) {
  13606. ast_sockaddr_set_port(&p->sa, r->portno);
  13607. ast_sockaddr_set_port(&p->recv, r->portno);
  13608. }
  13609. if (!ast_strlen_zero(p->fromdomain)) {
  13610. portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
  13611. } else if (!ast_strlen_zero(r->regdomain)) {
  13612. portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
  13613. } else {
  13614. portno = ast_sockaddr_port(&p->sa);
  13615. }
  13616. ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
  13617. r->call = dialog_ref(p, "copying dialog into registry r->call"); /* Save pointer to SIP dialog */
  13618. p->registry = ao2_t_bump(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
  13619. if (!ast_strlen_zero(r->secret)) { /* Secret (password) */
  13620. ast_string_field_set(p, peersecret, r->secret);
  13621. }
  13622. if (!ast_strlen_zero(r->md5secret))
  13623. ast_string_field_set(p, peermd5secret, r->md5secret);
  13624. /* User name in this realm
  13625. - if authuser is set, use that, otherwise use username */
  13626. if (!ast_strlen_zero(r->authuser)) {
  13627. ast_string_field_set(p, peername, r->authuser);
  13628. ast_string_field_set(p, authname, r->authuser);
  13629. } else if (!ast_strlen_zero(r->username)) {
  13630. ast_string_field_set(p, peername, r->username);
  13631. ast_string_field_set(p, authname, r->username);
  13632. ast_string_field_set(p, fromuser, r->username);
  13633. }
  13634. if (!ast_strlen_zero(r->username)) {
  13635. ast_string_field_set(p, username, r->username);
  13636. }
  13637. /* Save extension in packet */
  13638. if (!ast_strlen_zero(r->callback)) {
  13639. ast_string_field_set(p, exten, r->callback);
  13640. }
  13641. /* Set transport and port so the correct contact is built */
  13642. set_socket_transport(&p->socket, r->transport);
  13643. if (r->transport == AST_TRANSPORT_TLS || r->transport == AST_TRANSPORT_TCP) {
  13644. p->socket.port =
  13645. htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
  13646. }
  13647. /*
  13648. check which address we should use in our contact header
  13649. based on whether the remote host is on the external or
  13650. internal network so we can register through nat
  13651. */
  13652. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  13653. build_contact(p);
  13654. }
  13655. /* set up a timeout */
  13656. if (auth == NULL) {
  13657. if (r->timeout > -1) {
  13658. ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
  13659. }
  13660. AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
  13661. ao2_t_ref(_data, -1, "reg ptr unrefed from del in SCHED_REPLACE"),
  13662. ao2_t_ref(r, -1, "reg ptr unrefed from add failure in SCHED_REPLACE"),
  13663. ao2_t_ref(r, +1, "reg ptr reffed from add in SCHED_REPLACE"));
  13664. ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
  13665. }
  13666. snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
  13667. if (!ast_strlen_zero(p->theirtag)) {
  13668. snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
  13669. } else {
  13670. snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
  13671. }
  13672. /* Fromdomain is what we are registering to, regardless of actual
  13673. host name from SRV */
  13674. if (portno && portno != STANDARD_SIP_PORT) {
  13675. snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
  13676. } else {
  13677. snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
  13678. }
  13679. ast_string_field_set(p, uri, addr);
  13680. p->branch ^= ast_random();
  13681. init_req(&req, sipmethod, addr);
  13682. /* Add to CSEQ */
  13683. snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
  13684. p->ocseq = r->ocseq;
  13685. build_via(p);
  13686. add_header(&req, "Via", p->via);
  13687. add_max_forwards(p, &req);
  13688. add_header(&req, "From", from);
  13689. add_header(&req, "To", to);
  13690. add_header(&req, "Call-ID", p->callid);
  13691. add_header(&req, "CSeq", tmp);
  13692. add_supported(p, &req);
  13693. if (!ast_strlen_zero(global_useragent))
  13694. add_header(&req, "User-Agent", global_useragent);
  13695. if (auth) { /* Add auth header */
  13696. add_header(&req, authheader, auth);
  13697. } else if (!ast_strlen_zero(r->nonce)) {
  13698. char digest[1024];
  13699. /* We have auth data to reuse, build a digest header.
  13700. * Note, this is not always useful because some parties do not
  13701. * like nonces to be reused (for good reasons!) so they will
  13702. * challenge us anyways.
  13703. */
  13704. if (sipdebug) {
  13705. ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
  13706. }
  13707. ast_string_field_set(p, realm, r->realm);
  13708. ast_string_field_set(p, nonce, r->nonce);
  13709. ast_string_field_set(p, domain, r->authdomain);
  13710. ast_string_field_set(p, opaque, r->opaque);
  13711. ast_string_field_set(p, qop, r->qop);
  13712. p->noncecount = ++r->noncecount;
  13713. memset(digest, 0, sizeof(digest));
  13714. if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
  13715. add_header(&req, "Authorization", digest);
  13716. } else {
  13717. ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
  13718. }
  13719. }
  13720. add_expires(&req, r->expiry);
  13721. add_header(&req, "Contact", p->our_contact);
  13722. initialize_initreq(p, &req);
  13723. if (sip_debug_test_pvt(p)) {
  13724. ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  13725. }
  13726. r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
  13727. r->regattempts++; /* Another attempt */
  13728. ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
  13729. res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  13730. dialog_unref(p, "p is finished here at the end of transmit_register");
  13731. return res;
  13732. }
  13733. /*!
  13734. * \brief Transmit with SIP MESSAGE method
  13735. * \note The p->msg_headers and p->msg_body are already setup.
  13736. */
  13737. static int transmit_message(struct sip_pvt *p, int init, int auth)
  13738. {
  13739. struct sip_request req;
  13740. if (init) {
  13741. initreqprep(&req, p, SIP_MESSAGE, NULL);
  13742. initialize_initreq(p, &req);
  13743. } else {
  13744. reqprep(&req, p, SIP_MESSAGE, 0, 1);
  13745. }
  13746. if (auth) {
  13747. return transmit_request_with_auth(p, SIP_MESSAGE, p->ocseq, XMIT_RELIABLE, 0);
  13748. } else {
  13749. add_text(&req, p);
  13750. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13751. }
  13752. }
  13753. /*! \brief Allocate SIP refer structure */
  13754. static int sip_refer_alloc(struct sip_pvt *p)
  13755. {
  13756. p->refer = ast_calloc_with_stringfields(1, struct sip_refer, 512);
  13757. return p->refer ? 1 : 0;
  13758. }
  13759. /*! \brief Allocate SIP refer structure */
  13760. static int sip_notify_alloc(struct sip_pvt *p)
  13761. {
  13762. p->notify = ast_calloc(1, sizeof(struct sip_notify));
  13763. if (p->notify) {
  13764. p->notify->content = ast_str_create(128);
  13765. }
  13766. return p->notify ? 1 : 0;
  13767. }
  13768. /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
  13769. \note this is currently broken as we have no way of telling the dialplan
  13770. engine whether a transfer succeeds or fails.
  13771. \todo Fix the transfer() dialplan function so that a transfer may fail
  13772. */
  13773. static int transmit_refer(struct sip_pvt *p, const char *dest)
  13774. {
  13775. char from[256];
  13776. const char *of;
  13777. char *c;
  13778. char referto[256];
  13779. int use_tls=FALSE;
  13780. if (sipdebug) {
  13781. ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
  13782. }
  13783. /* Are we transfering an inbound or outbound call ? */
  13784. if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  13785. of = sip_get_header(&p->initreq, "To");
  13786. } else {
  13787. of = sip_get_header(&p->initreq, "From");
  13788. }
  13789. ast_copy_string(from, of, sizeof(from));
  13790. of = get_in_brackets(from);
  13791. ast_string_field_set(p, from, of);
  13792. if (!strncasecmp(of, "sip:", 4)) {
  13793. of += 4;
  13794. } else if (!strncasecmp(of, "sips:", 5)) {
  13795. of += 5;
  13796. use_tls = TRUE;
  13797. } else {
  13798. ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
  13799. }
  13800. /* Get just the username part */
  13801. if (strchr(dest, '@')) {
  13802. c = NULL;
  13803. } else if ((c = strchr(of, '@'))) {
  13804. *c++ = '\0';
  13805. }
  13806. if (c) {
  13807. snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
  13808. } else {
  13809. snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
  13810. }
  13811. /* save in case we get 407 challenge */
  13812. sip_refer_alloc(p);
  13813. ast_string_field_set(p->refer, refer_to, referto);
  13814. ast_string_field_set(p->refer, referred_by, p->our_contact);
  13815. p->refer->status = REFER_SENT; /* Set refer status */
  13816. return transmit_invite(p, SIP_REFER, FALSE, 0, NULL);
  13817. /* We should propably wait for a NOTIFY here until we ack the transfer */
  13818. /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
  13819. /*! \todo In theory, we should hang around and wait for a reply, before
  13820. returning to the dial plan here. Don't know really how that would
  13821. affect the transfer() app or the pbx, but, well, to make this
  13822. useful we should have a STATUS code on transfer().
  13823. */
  13824. }
  13825. /*! \brief Send SIP INFO advice of charge message */
  13826. static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
  13827. {
  13828. struct sip_request req;
  13829. struct ast_str *str = ast_str_alloca(512);
  13830. const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
  13831. enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
  13832. reqprep(&req, p, SIP_INFO, 0, 1);
  13833. if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
  13834. ast_str_append(&str, 0, "type=active;");
  13835. } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
  13836. ast_str_append(&str, 0, "type=terminated;");
  13837. } else {
  13838. /* unsupported message type */
  13839. return -1;
  13840. }
  13841. switch (charging) {
  13842. case AST_AOC_CHARGE_FREE:
  13843. ast_str_append(&str, 0, "free-of-charge;");
  13844. break;
  13845. case AST_AOC_CHARGE_CURRENCY:
  13846. ast_str_append(&str, 0, "charging;");
  13847. ast_str_append(&str, 0, "charging-info=currency;");
  13848. ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
  13849. ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
  13850. if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
  13851. ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
  13852. }
  13853. break;
  13854. case AST_AOC_CHARGE_UNIT:
  13855. ast_str_append(&str, 0, "charging;");
  13856. ast_str_append(&str, 0, "charging-info=pulse;");
  13857. if (unit_entry) {
  13858. ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
  13859. }
  13860. break;
  13861. default:
  13862. ast_str_append(&str, 0, "not-available;");
  13863. };
  13864. add_header(&req, "AOC", ast_str_buffer(str));
  13865. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13866. }
  13867. /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
  13868. static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
  13869. {
  13870. struct sip_request req;
  13871. reqprep(&req, p, SIP_INFO, 0, 1);
  13872. add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
  13873. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13874. }
  13875. /*! \brief Send SIP INFO with video update request */
  13876. static int transmit_info_with_vidupdate(struct sip_pvt *p)
  13877. {
  13878. struct sip_request req;
  13879. reqprep(&req, p, SIP_INFO, 0, 1);
  13880. add_vidupdate(&req);
  13881. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  13882. }
  13883. /*! \brief Transmit generic SIP request
  13884. returns XMIT_ERROR if transmit failed with a critical error (don't retry)
  13885. */
  13886. static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
  13887. {
  13888. struct sip_request resp;
  13889. reqprep(&resp, p, sipmethod, seqno, newbranch);
  13890. if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
  13891. add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
  13892. }
  13893. if (sipmethod == SIP_ACK) {
  13894. p->invitestate = INV_CONFIRMED;
  13895. }
  13896. return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
  13897. }
  13898. /*! \brief return the request and response header for a 401 or 407 code */
  13899. void sip_auth_headers(enum sip_auth_type code, char **header, char **respheader)
  13900. {
  13901. if (code == WWW_AUTH) { /* 401 */
  13902. *header = "WWW-Authenticate";
  13903. *respheader = "Authorization";
  13904. } else if (code == PROXY_AUTH) { /* 407 */
  13905. *header = "Proxy-Authenticate";
  13906. *respheader = "Proxy-Authorization";
  13907. } else {
  13908. ast_verbose("-- wrong response code %u\n", code);
  13909. *header = *respheader = "Invalid";
  13910. }
  13911. }
  13912. /*! \brief Transmit SIP request, auth added */
  13913. static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
  13914. {
  13915. struct sip_request resp;
  13916. reqprep(&resp, p, sipmethod, seqno, newbranch);
  13917. if (!ast_strlen_zero(p->realm)) {
  13918. char digest[1024];
  13919. memset(digest, 0, sizeof(digest));
  13920. if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
  13921. char *dummy, *response;
  13922. enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
  13923. sip_auth_headers(code, &dummy, &response);
  13924. add_header(&resp, response, digest);
  13925. } else {
  13926. ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
  13927. }
  13928. }
  13929. switch (sipmethod) {
  13930. case SIP_BYE:
  13931. {
  13932. char buf[20];
  13933. /*
  13934. * We are hanging up. If we know a cause for that, send it in
  13935. * clear text to make debugging easier.
  13936. */
  13937. if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
  13938. snprintf(buf, sizeof(buf), "Q.850;cause=%d", p->hangupcause & 0x7f);
  13939. add_header(&resp, "Reason", buf);
  13940. }
  13941. add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
  13942. snprintf(buf, sizeof(buf), "%d", p->hangupcause);
  13943. add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
  13944. break;
  13945. }
  13946. case SIP_MESSAGE:
  13947. add_text(&resp, p);
  13948. break;
  13949. default:
  13950. break;
  13951. }
  13952. return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
  13953. }
  13954. /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
  13955. static void destroy_association(struct sip_peer *peer)
  13956. {
  13957. int realtimeregs = ast_check_realtime("sipregs");
  13958. char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
  13959. if (!sip_cfg.ignore_regexpire) {
  13960. if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
  13961. ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
  13962. } else {
  13963. ast_db_del("SIP/Registry", peer->name);
  13964. ast_db_del("SIP/RegistryPath", peer->name);
  13965. ast_db_del("SIP/PeerMethods", peer->name);
  13966. }
  13967. }
  13968. }
  13969. static void set_socket_transport(struct sip_socket *socket, int transport)
  13970. {
  13971. /* if the transport type changes, clear all socket data */
  13972. if (socket->type != transport) {
  13973. socket->fd = -1;
  13974. socket->type = transport;
  13975. if (socket->tcptls_session) {
  13976. ao2_ref(socket->tcptls_session, -1);
  13977. socket->tcptls_session = NULL;
  13978. } else if (socket->ws_session) {
  13979. ast_websocket_unref(socket->ws_session);
  13980. socket->ws_session = NULL;
  13981. }
  13982. }
  13983. }
  13984. /*! \brief Expire registration of SIP peer */
  13985. static int expire_register(const void *data)
  13986. {
  13987. struct sip_peer *peer = (struct sip_peer *)data;
  13988. if (!peer) { /* Hmmm. We have no peer. Weird. */
  13989. return 0;
  13990. }
  13991. peer->expire = -1;
  13992. peer->portinuri = 0;
  13993. destroy_association(peer); /* remove registration data from storage */
  13994. set_socket_transport(&peer->socket, peer->default_outbound_transport);
  13995. if (peer->socket.tcptls_session) {
  13996. ao2_ref(peer->socket.tcptls_session, -1);
  13997. peer->socket.tcptls_session = NULL;
  13998. } else if (peer->socket.ws_session) {
  13999. ast_websocket_unref(peer->socket.ws_session);
  14000. peer->socket.ws_session = NULL;
  14001. }
  14002. if (peer->endpoint) {
  14003. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  14004. ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_OFFLINE);
  14005. blob = ast_json_pack("{s: s, s: s}",
  14006. "peer_status", "Unregistered",
  14007. "cause", "Expired");
  14008. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  14009. }
  14010. register_peer_exten(peer, FALSE); /* Remove regexten */
  14011. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  14012. /* Do we need to release this peer from memory?
  14013. Only for realtime peers and autocreated peers
  14014. */
  14015. if (peer->is_realtime) {
  14016. ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
  14017. }
  14018. if (peer->selfdestruct ||
  14019. ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
  14020. ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
  14021. }
  14022. if (!ast_sockaddr_isnull(&peer->addr)) {
  14023. /* We still need to unlink the peer from the peers_by_ip table,
  14024. * otherwise we end up with multiple copies hanging around each
  14025. * time a registration expires and the peer re-registers. */
  14026. ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
  14027. }
  14028. /* Only clear the addr after we check for destruction. The addr must remain
  14029. * in order to unlink from the peers_by_ip container correctly */
  14030. memset(&peer->addr, 0, sizeof(peer->addr));
  14031. sip_unref_peer(peer, "removing peer ref for expire_register");
  14032. return 0;
  14033. }
  14034. /*! \brief Poke peer (send qualify to check if peer is alive and well) */
  14035. static int sip_poke_peer_s(const void *data)
  14036. {
  14037. struct sip_peer *peer = (struct sip_peer *)data;
  14038. struct sip_peer *foundpeer;
  14039. peer->pokeexpire = -1;
  14040. foundpeer = ao2_find(peers, peer, OBJ_POINTER);
  14041. if (!foundpeer) {
  14042. sip_unref_peer(peer, "removing poke peer ref");
  14043. return 0;
  14044. } else if (foundpeer->name != peer->name) {
  14045. sip_unref_peer(foundpeer, "removing above peer ref");
  14046. sip_unref_peer(peer, "removing poke peer ref");
  14047. return 0;
  14048. }
  14049. sip_unref_peer(foundpeer, "removing above peer ref");
  14050. sip_poke_peer(peer, 0);
  14051. sip_unref_peer(peer, "removing poke peer ref");
  14052. return 0;
  14053. }
  14054. /*! \brief Get registration details from Asterisk DB */
  14055. static void reg_source_db(struct sip_peer *peer)
  14056. {
  14057. char data[256];
  14058. char path[SIPBUFSIZE * 2];
  14059. struct ast_sockaddr sa;
  14060. int expire;
  14061. char full_addr[128];
  14062. AST_DECLARE_APP_ARGS(args,
  14063. AST_APP_ARG(addr);
  14064. AST_APP_ARG(port);
  14065. AST_APP_ARG(expiry_str);
  14066. AST_APP_ARG(username);
  14067. AST_APP_ARG(contact);
  14068. );
  14069. /* If read-only RT backend, then refresh from local DB cache */
  14070. if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
  14071. return;
  14072. }
  14073. if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
  14074. return;
  14075. }
  14076. AST_NONSTANDARD_RAW_ARGS(args, data, ':');
  14077. snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
  14078. if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
  14079. return;
  14080. }
  14081. if (args.expiry_str) {
  14082. expire = atoi(args.expiry_str);
  14083. } else {
  14084. return;
  14085. }
  14086. if (args.username) {
  14087. ast_string_field_set(peer, username, args.username);
  14088. }
  14089. if (args.contact) {
  14090. ast_string_field_set(peer, fullcontact, args.contact);
  14091. }
  14092. ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
  14093. peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
  14094. ast_sockaddr_copy(&peer->addr, &sa);
  14095. if (peer->maxms) {
  14096. /* Don't poke peer immediately, just schedule it within qualifyfreq */
  14097. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
  14098. ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
  14099. sip_poke_peer_s, peer,
  14100. sip_unref_peer(_data, "removing poke peer ref"),
  14101. sip_unref_peer(peer, "removing poke peer ref"),
  14102. sip_ref_peer(peer, "adding poke peer ref"));
  14103. }
  14104. AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
  14105. sip_unref_peer(_data, "remove registration ref"),
  14106. sip_unref_peer(peer, "remove registration ref"),
  14107. sip_ref_peer(peer, "add registration ref"));
  14108. register_peer_exten(peer, TRUE);
  14109. if (!ast_db_get("SIP/RegistryPath", peer->name, path, sizeof(path))) {
  14110. build_path(NULL, peer, NULL, path);
  14111. }
  14112. }
  14113. /*! \brief Save contact header for 200 OK on INVITE */
  14114. static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
  14115. {
  14116. char contact[SIPBUFSIZE];
  14117. char *c;
  14118. /* Look for brackets */
  14119. ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
  14120. c = get_in_brackets(contact);
  14121. /* Save full contact to call pvt for later bye or re-invite */
  14122. ast_string_field_set(pvt, fullcontact, c);
  14123. /* Save URI for later ACKs, BYE or RE-invites */
  14124. ast_string_field_set(pvt, okcontacturi, c);
  14125. /* We should return false for URI:s we can't handle,
  14126. like tel:, mailto:,ldap: etc */
  14127. return TRUE;
  14128. }
  14129. /*! \brief parse uri in a way that allows semicolon stripping if legacy mode is enabled
  14130. *
  14131. * \note This calls parse_uri which has the unexpected property that passing more
  14132. * arguments results in more splitting. Most common is to leave out the pass
  14133. * argument, causing user to contain user:pass if available.
  14134. */
  14135. static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
  14136. {
  14137. int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
  14138. if (sip_cfg.legacy_useroption_parsing) { /* if legacy mode is active, strip semis from the user field */
  14139. char *p;
  14140. if ((p = strchr(uri, (int)';'))) {
  14141. *p = '\0';
  14142. }
  14143. }
  14144. return ret;
  14145. }
  14146. static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
  14147. {
  14148. char *hostport, *transport;
  14149. char contact_buf[256];
  14150. char *contact;
  14151. /* Work on a copy */
  14152. ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
  14153. contact = contact_buf;
  14154. /*
  14155. * We have only the part in <brackets> here so we just need to parse a SIP URI.
  14156. *
  14157. * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
  14158. * We still need to be able to send to the remote agent through the proxy.
  14159. */
  14160. if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
  14161. &transport)) {
  14162. ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
  14163. }
  14164. /* XXX This could block for a long time XXX */
  14165. /* We should only do this if it's a name, not an IP */
  14166. /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
  14167. to find transport, port address and hostname. If there's a port number, we have to
  14168. assume that the hostport part is a host name and only look for an A/AAAA record in DNS.
  14169. */
  14170. /* If we took in an invalid URI, hostport may not have been initialized */
  14171. /* ast_sockaddr_resolve requires an initialized hostport string. */
  14172. if (ast_strlen_zero(hostport)) {
  14173. ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
  14174. return -1;
  14175. }
  14176. if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
  14177. ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
  14178. "resolve in DNS) : '%s'\n", hostport);
  14179. return -1;
  14180. }
  14181. /* set port */
  14182. if (!ast_sockaddr_port(addr)) {
  14183. ast_sockaddr_set_port(addr,
  14184. (get_transport_str2enum(transport) ==
  14185. AST_TRANSPORT_TLS ||
  14186. !strncasecmp(fullcontact, "sips", 4)) ?
  14187. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  14188. }
  14189. return 0;
  14190. }
  14191. /*! \brief Change the other partys IP address based on given contact */
  14192. static int set_address_from_contact(struct sip_pvt *pvt)
  14193. {
  14194. if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
  14195. /* NAT: Don't trust the contact field. Just use what they came to us
  14196. with. */
  14197. /*! \todo We need to save the TRANSPORT here too */
  14198. pvt->sa = pvt->recv;
  14199. return 0;
  14200. }
  14201. return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == AST_TRANSPORT_TLS ? 1 : 0);
  14202. }
  14203. /*! \brief Parse contact header and save registration (peer registration) */
  14204. static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
  14205. {
  14206. char contact[SIPBUFSIZE];
  14207. char data[SIPBUFSIZE];
  14208. const char *expires = sip_get_header(req, "Expires");
  14209. int expire = atoi(expires);
  14210. char *curi = NULL, *hostport = NULL, *transport = NULL;
  14211. int transport_type;
  14212. const char *useragent;
  14213. struct ast_sockaddr oldsin, testsa;
  14214. char *firstcuri = NULL;
  14215. int start = 0;
  14216. int wildcard_found = 0;
  14217. int single_binding_found = 0;
  14218. ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
  14219. if (ast_strlen_zero(expires)) { /* No expires header, try look in Contact: */
  14220. char *s = strcasestr(contact, ";expires=");
  14221. if (s) {
  14222. expires = strsep(&s, ";"); /* trim ; and beyond */
  14223. if (sscanf(expires + 9, "%30d", &expire) != 1) {
  14224. expire = default_expiry;
  14225. }
  14226. } else {
  14227. /* Nothing has been specified */
  14228. expire = default_expiry;
  14229. }
  14230. }
  14231. if (expire > max_expiry) {
  14232. expire = max_expiry;
  14233. }
  14234. if (expire < min_expiry && expire != 0) {
  14235. expire = min_expiry;
  14236. }
  14237. pvt->expiry = expire;
  14238. copy_socket_data(&pvt->socket, &req->socket);
  14239. do {
  14240. /* Look for brackets */
  14241. curi = contact;
  14242. if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
  14243. strsep(&curi, ";"); /* This is Header options, not URI options */
  14244. curi = get_in_brackets(contact);
  14245. if (!firstcuri) {
  14246. firstcuri = ast_strdupa(curi);
  14247. }
  14248. if (!strcasecmp(curi, "*")) {
  14249. wildcard_found = 1;
  14250. } else {
  14251. single_binding_found = 1;
  14252. }
  14253. if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
  14254. /* Contact header parameter "*" detected, so punt if: Expires header is missing,
  14255. * Expires value is not zero, or another Contact header is present. */
  14256. return PARSE_REGISTER_FAILED;
  14257. }
  14258. ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
  14259. } while (!ast_strlen_zero(contact));
  14260. curi = firstcuri;
  14261. /* if they did not specify Contact: or Expires:, they are querying
  14262. what we currently have stored as their contact address, so return
  14263. it
  14264. */
  14265. if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
  14266. /* If we have an active registration, tell them when the registration is going to expire */
  14267. if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
  14268. pvt->expiry = ast_sched_when(sched, peer->expire);
  14269. }
  14270. return PARSE_REGISTER_QUERY;
  14271. } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
  14272. /* This means remove all registrations and return OK */
  14273. AST_SCHED_DEL_UNREF(sched, peer->expire,
  14274. sip_unref_peer(peer, "remove register expire ref"));
  14275. ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
  14276. expire_register(sip_ref_peer(peer,"add ref for explicit expire_register"));
  14277. return PARSE_REGISTER_UPDATE;
  14278. }
  14279. /* Store whatever we got as a contact from the client */
  14280. ast_string_field_set(peer, fullcontact, curi);
  14281. /* For the 200 OK, we should use the received contact */
  14282. ast_string_field_build(pvt, our_contact, "<%s>", curi);
  14283. /* Make sure it's a SIP URL */
  14284. if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
  14285. ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
  14286. }
  14287. /* handle the transport type specified in Contact header. */
  14288. if (!(transport_type = get_transport_str2enum(transport))) {
  14289. transport_type = pvt->socket.type;
  14290. }
  14291. /* if the peer's socket type is different than the Registration
  14292. * transport type, change it. If it got this far, it is a
  14293. * supported type, but check just in case */
  14294. if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
  14295. set_socket_transport(&peer->socket, transport_type);
  14296. }
  14297. oldsin = peer->addr;
  14298. /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
  14299. if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
  14300. ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
  14301. }
  14302. if ((transport_type != AST_TRANSPORT_WS) && (transport_type != AST_TRANSPORT_WSS) &&
  14303. (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT))) {
  14304. /* use the data provided in the Contact header for call routing */
  14305. ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
  14306. /* XXX This could block for a long time XXX */
  14307. /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
  14308. if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
  14309. ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
  14310. ast_string_field_set(peer, fullcontact, "");
  14311. ast_string_field_set(pvt, our_contact, "");
  14312. return PARSE_REGISTER_FAILED;
  14313. }
  14314. /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
  14315. The hostport part is actually a host. */
  14316. peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
  14317. if (!ast_sockaddr_port(&testsa)) {
  14318. ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
  14319. }
  14320. ast_sockaddr_copy(&peer->addr, &testsa);
  14321. } else {
  14322. /* Don't trust the contact field. Just use what they came to us
  14323. with */
  14324. ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
  14325. peer->addr = pvt->recv;
  14326. }
  14327. /* Check that they're allowed to register at this IP */
  14328. if (ast_apply_acl(sip_cfg.contact_acl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW ||
  14329. ast_apply_acl(peer->contactacl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW) {
  14330. ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
  14331. ast_sockaddr_stringify_addr(&peer->addr));
  14332. ast_string_field_set(peer, fullcontact, "");
  14333. ast_string_field_set(pvt, our_contact, "");
  14334. return PARSE_REGISTER_DENIED;
  14335. }
  14336. /* if the Contact header information copied into peer->addr matches the
  14337. * received address, and the transport types are the same, then copy socket
  14338. * data into the peer struct */
  14339. if ((peer->socket.type == pvt->socket.type) &&
  14340. !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
  14341. copy_socket_data(&peer->socket, &pvt->socket);
  14342. }
  14343. /* Now that our address has been updated put ourselves back into the container for lookups */
  14344. if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  14345. ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
  14346. }
  14347. /* Save SIP options profile */
  14348. peer->sipoptions = pvt->sipoptions;
  14349. if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
  14350. ast_string_field_set(peer, username, curi);
  14351. }
  14352. AST_SCHED_DEL_UNREF(sched, peer->expire,
  14353. sip_unref_peer(peer, "remove register expire ref"));
  14354. if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  14355. peer->expire = -1;
  14356. } else {
  14357. peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
  14358. sip_ref_peer(peer, "add registration ref"));
  14359. if (peer->expire == -1) {
  14360. sip_unref_peer(peer, "remote registration ref");
  14361. }
  14362. }
  14363. if (!build_path(pvt, peer, req, NULL)) {
  14364. /* Tell the dialog to use the Path header in the response */
  14365. ast_set2_flag(&pvt->flags[0], 1, SIP_USEPATH);
  14366. }
  14367. snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
  14368. expire, peer->username, peer->fullcontact);
  14369. /* We might not immediately be able to reconnect via TCP, but try caching it anyhow */
  14370. if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate) {
  14371. if (!sip_route_empty(&peer->path)) {
  14372. struct ast_str *r = sip_route_list(&peer->path, 0, 0);
  14373. if (r) {
  14374. ast_db_put("SIP/RegistryPath", peer->name, ast_str_buffer(r));
  14375. ast_free(r);
  14376. }
  14377. }
  14378. ast_db_put("SIP/Registry", peer->name, data);
  14379. }
  14380. if (peer->endpoint) {
  14381. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  14382. ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_ONLINE);
  14383. blob = ast_json_pack("{s: s, s: s}",
  14384. "peer_status", "Registered",
  14385. "address", ast_sockaddr_stringify(&peer->addr));
  14386. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  14387. }
  14388. /* Is this a new IP address for us? */
  14389. if (ast_sockaddr_cmp(&peer->addr, &oldsin)) {
  14390. ast_verb(3, "Registered SIP '%s' at %s\n", peer->name,
  14391. ast_sockaddr_stringify(&peer->addr));
  14392. }
  14393. sip_pvt_unlock(pvt);
  14394. sip_poke_peer(peer, 0);
  14395. sip_pvt_lock(pvt);
  14396. register_peer_exten(peer, 1);
  14397. /* Save User agent */
  14398. useragent = sip_get_header(req, "User-Agent");
  14399. if (strcasecmp(useragent, peer->useragent)) {
  14400. ast_string_field_set(peer, useragent, useragent);
  14401. ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
  14402. }
  14403. return PARSE_REGISTER_UPDATE;
  14404. }
  14405. /*! \brief Build route list from Record-Route header
  14406. *
  14407. * \param p
  14408. * \param req
  14409. * \param backwards
  14410. * \param resp the SIP response code or 0 for a request
  14411. *
  14412. */
  14413. static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
  14414. {
  14415. int start = 0;
  14416. const char *header;
  14417. /* Once a persistent route is set, don't fool with it */
  14418. if (!sip_route_empty(&p->route) && p->route_persistent) {
  14419. ast_debug(1, "build_route: Retaining previous route: <%s>\n", sip_route_first_uri(&p->route));
  14420. return;
  14421. }
  14422. sip_route_clear(&p->route);
  14423. /* We only want to create the route set the first time this is called except
  14424. it is called from a provisional response.*/
  14425. if ((resp < 100) || (resp > 199)) {
  14426. p->route_persistent = 1;
  14427. }
  14428. /* Build a tailq, then assign it to p->route when done.
  14429. * If backwards, we add entries from the head so they end up
  14430. * in reverse order. However, we do need to maintain a correct
  14431. * tail pointer because the contact is always at the end.
  14432. */
  14433. /* 1st we pass through all the hops in any Record-Route headers */
  14434. for (;;) {
  14435. header = __get_header(req, "Record-Route", &start);
  14436. if (*header == '\0') {
  14437. break;
  14438. }
  14439. sip_route_process_header(&p->route, header, backwards);
  14440. }
  14441. /* Only append the contact if we are dealing with a strict router or have no route */
  14442. if (sip_route_empty(&p->route) || sip_route_is_strict(&p->route)) {
  14443. /* 2nd append the Contact: if there is one */
  14444. /* Can be multiple Contact headers, comma separated values - we just take the first */
  14445. int len;
  14446. header = sip_get_header(req, "Contact");
  14447. if (strchr(header, '<')) {
  14448. get_in_brackets_const(header, &header, &len);
  14449. } else {
  14450. len = strlen(header);
  14451. }
  14452. if (header && len) {
  14453. sip_route_add(&p->route, header, len, 0);
  14454. }
  14455. }
  14456. /* For debugging dump what we ended up with */
  14457. if (sip_debug_test_pvt(p)) {
  14458. sip_route_dump(&p->route);
  14459. }
  14460. }
  14461. /*! \brief Build route list from Path header
  14462. * RFC 3327 requires that the Path header contains SIP URIs with lr paramter.
  14463. * Thus, we do not care about strict routing SIP routers
  14464. */
  14465. static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, const char *pathbuf)
  14466. {
  14467. sip_route_clear(&peer->path);
  14468. if (!ast_test_flag(&peer->flags[0], SIP_USEPATH)) {
  14469. ast_debug(2, "build_path: do not use Path headers\n");
  14470. return -1;
  14471. }
  14472. ast_debug(2, "build_path: try to build pre-loaded route-set by parsing Path headers\n");
  14473. if (req) {
  14474. int start = 0;
  14475. const char *header;
  14476. for (;;) {
  14477. header = __get_header(req, "Path", &start);
  14478. if (*header == '\0') {
  14479. break;
  14480. }
  14481. sip_route_process_header(&peer->path, header, 0);
  14482. }
  14483. } else if (pathbuf) {
  14484. sip_route_process_header(&peer->path, pathbuf, 0);
  14485. }
  14486. /* Caches result for any dialog->route copied from peer->path */
  14487. sip_route_is_strict(&peer->path);
  14488. /* For debugging dump what we ended up with */
  14489. if (p && sip_debug_test_pvt(p)) {
  14490. sip_route_dump(&peer->path);
  14491. }
  14492. return 0;
  14493. }
  14494. /*! \brief builds the sip_pvt's nonce field which is used for the authentication
  14495. * challenge. When forceupdate is not set, the nonce is only updated if
  14496. * the current one is stale. In this case, a stalenonce is one which
  14497. * has already received a response, if a nonce has not received a response
  14498. * it is not always necessary or beneficial to create a new one. */
  14499. static void build_nonce(struct sip_pvt *p, int forceupdate)
  14500. {
  14501. if (p->stalenonce || forceupdate || ast_strlen_zero(p->nonce)) {
  14502. ast_string_field_build(p, nonce, "%08lx", (unsigned long)ast_random()); /* Create nonce for challenge */
  14503. p->stalenonce = 0;
  14504. }
  14505. }
  14506. /*! \brief Takes the digest response and parses it */
  14507. void sip_digest_parser(char *c, struct digestkeys *keys)
  14508. {
  14509. struct digestkeys *i = i;
  14510. while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
  14511. for (i = keys; i->key != NULL; i++) {
  14512. const char *separator = ","; /* default */
  14513. if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
  14514. continue;
  14515. }
  14516. /* Found. Skip keyword, take text in quotes or up to the separator. */
  14517. c += strlen(i->key);
  14518. if (*c == '"') { /* in quotes. Skip first and look for last */
  14519. c++;
  14520. separator = "\"";
  14521. }
  14522. i->s = c;
  14523. strsep(&c, separator);
  14524. break;
  14525. }
  14526. if (i->key == NULL) { /* not found, jump after space or comma */
  14527. strsep(&c, " ,");
  14528. }
  14529. }
  14530. }
  14531. /*! \brief Check user authorization from peer definition
  14532. Some actions, like REGISTER and INVITEs from peers require
  14533. authentication (if peer have secret set)
  14534. \return 0 on success, non-zero on error
  14535. */
  14536. static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
  14537. const char *secret, const char *md5secret, int sipmethod,
  14538. const char *uri, enum xmittype reliable)
  14539. {
  14540. const char *response;
  14541. char *reqheader, *respheader;
  14542. const char *authtoken;
  14543. char a1_hash[256];
  14544. char resp_hash[256]="";
  14545. char *c;
  14546. int is_bogus_peer = 0;
  14547. int wrongnonce = FALSE;
  14548. int good_response;
  14549. const char *usednonce = p->nonce;
  14550. struct ast_str *buf;
  14551. int res;
  14552. /* table of recognised keywords, and their value in the digest */
  14553. struct digestkeys keys[] = {
  14554. [K_RESP] = { "response=", "" },
  14555. [K_URI] = { "uri=", "" },
  14556. [K_USER] = { "username=", "" },
  14557. [K_NONCE] = { "nonce=", "" },
  14558. [K_LAST] = { NULL, NULL}
  14559. };
  14560. /* Always OK if no secret */
  14561. if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)) {
  14562. return AUTH_SUCCESSFUL;
  14563. }
  14564. /* Always auth with WWW-auth since we're NOT a proxy */
  14565. /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
  14566. response = "401 Unauthorized";
  14567. /*
  14568. * Note the apparent swap of arguments below, compared to other
  14569. * usages of sip_auth_headers().
  14570. */
  14571. sip_auth_headers(WWW_AUTH, &respheader, &reqheader);
  14572. authtoken = sip_get_header(req, reqheader);
  14573. if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
  14574. /* This is a retransmitted invite/register/etc, don't reconstruct authentication
  14575. information */
  14576. if (!reliable) {
  14577. /* Resend message if this was NOT a reliable delivery. Otherwise the
  14578. retransmission should get it */
  14579. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
  14580. /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
  14581. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14582. }
  14583. return AUTH_CHALLENGE_SENT;
  14584. } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
  14585. /* We have no auth, so issue challenge and request authentication */
  14586. build_nonce(p, 1); /* Create nonce for challenge */
  14587. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
  14588. /* Schedule auto destroy in 32 seconds */
  14589. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14590. return AUTH_CHALLENGE_SENT;
  14591. }
  14592. /* --- We have auth, so check it */
  14593. /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
  14594. an example in the spec of just what it is you're doing a hash on. */
  14595. if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
  14596. return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
  14597. }
  14598. /* Make a copy of the response and parse it */
  14599. res = ast_str_set(&buf, 0, "%s", authtoken);
  14600. if (res == AST_DYNSTR_BUILD_FAILED) {
  14601. return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
  14602. }
  14603. c = buf->str;
  14604. sip_digest_parser(c, keys);
  14605. /* We cannot rely on the bogus_peer having a bad md5 value. Someone could
  14606. * use it to construct valid auth. */
  14607. if (md5secret && strcmp(md5secret, BOGUS_PEER_MD5SECRET) == 0) {
  14608. is_bogus_peer = 1;
  14609. }
  14610. /* Verify that digest username matches the username we auth as */
  14611. if (strcmp(username, keys[K_USER].s) && !is_bogus_peer) {
  14612. ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
  14613. username, keys[K_USER].s);
  14614. /* Oops, we're trying something here */
  14615. return AUTH_USERNAME_MISMATCH;
  14616. }
  14617. /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
  14618. * If this check fails, send 401 with new nonce */
  14619. if (strcasecmp(p->nonce, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
  14620. wrongnonce = TRUE;
  14621. usednonce = keys[K_NONCE].s;
  14622. } else {
  14623. p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
  14624. }
  14625. if (!ast_strlen_zero(md5secret)) {
  14626. ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
  14627. } else {
  14628. char a1[256];
  14629. snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
  14630. ast_md5_hash(a1_hash, a1);
  14631. }
  14632. /* compute the expected response to compare with what we received */
  14633. {
  14634. char a2[256];
  14635. char a2_hash[256];
  14636. char resp[256];
  14637. snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
  14638. S_OR(keys[K_URI].s, uri));
  14639. ast_md5_hash(a2_hash, a2);
  14640. snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
  14641. ast_md5_hash(resp_hash, resp);
  14642. }
  14643. good_response = keys[K_RESP].s &&
  14644. !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash)) &&
  14645. !is_bogus_peer; /* lastly, check that the peer isn't the fake peer */
  14646. if (wrongnonce) {
  14647. if (good_response) {
  14648. if (sipdebug)
  14649. ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", sip_get_header(req, "From"));
  14650. /* We got working auth token, based on stale nonce . */
  14651. build_nonce(p, 0);
  14652. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, TRUE);
  14653. } else {
  14654. /* Everything was wrong, so give the device one more try with a new challenge */
  14655. if (!req->ignore) {
  14656. if (sipdebug) {
  14657. ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", sip_get_header(req, "To"));
  14658. }
  14659. build_nonce(p, 1);
  14660. } else {
  14661. if (sipdebug) {
  14662. ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", sip_get_header(req, "To"));
  14663. }
  14664. }
  14665. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
  14666. }
  14667. /* Schedule auto destroy in 32 seconds */
  14668. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14669. return AUTH_CHALLENGE_SENT;
  14670. }
  14671. if (good_response) {
  14672. append_history(p, "AuthOK", "Auth challenge successful for %s", username);
  14673. return AUTH_SUCCESSFUL;
  14674. }
  14675. /* Ok, we have a bad username/secret pair */
  14676. /* Tell the UAS not to re-send this authentication data, because
  14677. it will continue to fail
  14678. */
  14679. return AUTH_SECRET_FAILED;
  14680. }
  14681. /*! \brief Change onhold state of a peer using a pvt structure */
  14682. static void sip_peer_hold(struct sip_pvt *p, int hold)
  14683. {
  14684. if (!p->relatedpeer) {
  14685. return;
  14686. }
  14687. /* If they put someone on hold, increment the value... otherwise decrement it */
  14688. ast_atomic_fetchadd_int(&p->relatedpeer->onhold, (hold ? +1 : -1));
  14689. /* Request device state update */
  14690. 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),
  14691. "SIP/%s", p->relatedpeer->name);
  14692. return;
  14693. }
  14694. /*! \brief Receive MWI events that we have subscribed to */
  14695. static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
  14696. {
  14697. char *peer_name = userdata;
  14698. struct sip_peer *peer = sip_find_peer(peer_name, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
  14699. if (stasis_subscription_final_message(sub, msg)) {
  14700. if (peer) {
  14701. /* configuration reloaded */
  14702. return;
  14703. }
  14704. ast_free(peer_name);
  14705. return;
  14706. }
  14707. if (peer && ast_mwi_state_type() == stasis_message_type(msg)) {
  14708. sip_send_mwi_to_peer(peer, 0);
  14709. }
  14710. ao2_cleanup(peer);
  14711. }
  14712. static void network_change_stasis_subscribe(void)
  14713. {
  14714. if (!network_change_sub) {
  14715. network_change_sub = stasis_subscribe(ast_system_topic(),
  14716. network_change_stasis_cb, NULL);
  14717. }
  14718. }
  14719. static void network_change_stasis_unsubscribe(void)
  14720. {
  14721. network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
  14722. }
  14723. static void acl_change_stasis_subscribe(void)
  14724. {
  14725. if (!acl_change_sub) {
  14726. acl_change_sub = stasis_subscribe(ast_security_topic(),
  14727. acl_change_stasis_cb, NULL);
  14728. }
  14729. }
  14730. static void acl_change_event_stasis_unsubscribe(void)
  14731. {
  14732. acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
  14733. }
  14734. static int network_change_sched_cb(const void *data)
  14735. {
  14736. network_change_sched_id = -1;
  14737. sip_send_all_registers();
  14738. sip_send_all_mwi_subscriptions();
  14739. return 0;
  14740. }
  14741. static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
  14742. {
  14743. /* This callback is only concerned with network change messages from the system topic. */
  14744. if (stasis_message_type(message) != ast_network_change_type()) {
  14745. return;
  14746. }
  14747. ast_verb(1, "SIP, got a network change message, renewing all SIP registrations.\n");
  14748. if (network_change_sched_id == -1) {
  14749. network_change_sched_id = ast_sched_add(sched, 1000, network_change_sched_cb, NULL);
  14750. }
  14751. }
  14752. static void cb_extensionstate_destroy(int id, void *data)
  14753. {
  14754. struct sip_pvt *p = data;
  14755. dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
  14756. }
  14757. /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
  14758. \note If you add an "hint" priority to the extension in the dial plan,
  14759. you will get notifications on device state changes */
  14760. static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force)
  14761. {
  14762. sip_pvt_lock(p);
  14763. switch (data->state) {
  14764. case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
  14765. case AST_EXTENSION_REMOVED: /* Extension is gone */
  14766. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
  14767. ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, data->state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
  14768. p->subscribed = NONE;
  14769. append_history(p, "Subscribestatus", "%s", data->state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
  14770. break;
  14771. default: /* Tell user */
  14772. if (force) {
  14773. /* we must skip the next two checks for a queued state change or resubscribe */
  14774. } else if ((p->laststate == data->state && (~data->state & AST_EXTENSION_RINGING)) &&
  14775. (p->last_presence_state == data->presence_state &&
  14776. !strcmp(p->last_presence_subtype, data->presence_subtype) &&
  14777. !strcmp(p->last_presence_message, data->presence_message))) {
  14778. /* don't notify unchanged state or unchanged early-state causing parties again */
  14779. sip_pvt_unlock(p);
  14780. return 0;
  14781. } else if (data->state & AST_EXTENSION_RINGING) {
  14782. /* check if another channel than last time is ringing now to be notified */
  14783. struct ast_channel *ringing = find_ringing_channel(data->device_state_info, p);
  14784. if (ringing) {
  14785. if (!ast_tvcmp(ast_channel_creationtime(ringing), p->last_ringing_channel_time)) {
  14786. /* we assume here that no two channels have the exact same creation time */
  14787. ao2_ref(ringing, -1);
  14788. sip_pvt_unlock(p);
  14789. return 0;
  14790. } else {
  14791. p->last_ringing_channel_time = ast_channel_creationtime(ringing);
  14792. ao2_ref(ringing, -1);
  14793. }
  14794. }
  14795. /* If no ringing channel was found, it doesn't necessarily indicate anything bad.
  14796. * Likely, a device state change occurred for a custom device state, which does not
  14797. * correspond to any channel. In such a case, just go ahead and pass the notification
  14798. * along.
  14799. */
  14800. }
  14801. /* ref before unref because the new could be the same as the old one. Don't risk destruction! */
  14802. if (data->device_state_info) {
  14803. ao2_ref(data->device_state_info, 1);
  14804. }
  14805. ao2_cleanup(p->last_device_state_info);
  14806. p->last_device_state_info = data->device_state_info;
  14807. p->laststate = data->state;
  14808. p->last_presence_state = data->presence_state;
  14809. ast_string_field_set(p, last_presence_subtype, S_OR(data->presence_subtype, ""));
  14810. ast_string_field_set(p, last_presence_message, S_OR(data->presence_message, ""));
  14811. break;
  14812. }
  14813. if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
  14814. if (!p->pendinginvite) {
  14815. transmit_state_notify(p, data, 1, FALSE);
  14816. if (p->last_device_state_info) {
  14817. /* We don't need the saved ref anymore, don't keep channels ref'd. */
  14818. ao2_ref(p->last_device_state_info, -1);
  14819. p->last_device_state_info = NULL;
  14820. }
  14821. } else {
  14822. /* We already have a NOTIFY sent that is not answered. Queue the state up.
  14823. if many state changes happen meanwhile, we will only send a notification of the last one */
  14824. ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
  14825. }
  14826. }
  14827. if (!force) {
  14828. 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,
  14829. ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
  14830. }
  14831. sip_pvt_unlock(p);
  14832. return 0;
  14833. }
  14834. /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
  14835. \note If you add an "hint" priority to the extension in the dial plan,
  14836. you will get notifications on device state changes */
  14837. static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data)
  14838. {
  14839. struct sip_pvt *p = data;
  14840. struct state_notify_data notify_data = {
  14841. .state = info->exten_state,
  14842. .device_state_info = info->device_state_info,
  14843. .presence_state = info->presence_state,
  14844. .presence_subtype = info->presence_subtype,
  14845. .presence_message = info->presence_message,
  14846. };
  14847. if ((info->reason == AST_HINT_UPDATE_PRESENCE) && !(allow_notify_user_presence(p))) {
  14848. /* ignore a presence triggered update if we know the useragent doesn't care */
  14849. return 0;
  14850. }
  14851. return extensionstate_update(context, exten, &notify_data, p, FALSE);
  14852. }
  14853. /*! \brief Send a fake 401 Unauthorized response when the administrator
  14854. wants to hide the names of local devices from fishers
  14855. */
  14856. static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable)
  14857. {
  14858. /* We have to emulate EXACTLY what we'd get with a good peer
  14859. * and a bad password, or else we leak information. */
  14860. const char *response = "401 Unauthorized";
  14861. const char *reqheader = "Authorization";
  14862. const char *respheader = "WWW-Authenticate";
  14863. const char *authtoken;
  14864. struct ast_str *buf;
  14865. char *c;
  14866. /* table of recognised keywords, and their value in the digest */
  14867. enum keys { K_NONCE, K_LAST };
  14868. struct x {
  14869. const char *key;
  14870. const char *s;
  14871. } *i, keys[] = {
  14872. [K_NONCE] = { "nonce=", "" },
  14873. [K_LAST] = { NULL, NULL}
  14874. };
  14875. authtoken = sip_get_header(req, reqheader);
  14876. if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
  14877. /* This is a retransmitted invite/register/etc, don't reconstruct authentication
  14878. * information */
  14879. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
  14880. /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
  14881. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14882. return;
  14883. } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
  14884. /* We have no auth, so issue challenge and request authentication */
  14885. build_nonce(p, 1);
  14886. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
  14887. /* Schedule auto destroy in 32 seconds */
  14888. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14889. return;
  14890. }
  14891. if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
  14892. __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
  14893. return;
  14894. }
  14895. /* Make a copy of the response and parse it */
  14896. if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
  14897. __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
  14898. return;
  14899. }
  14900. c = buf->str;
  14901. while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
  14902. for (i = keys; i->key != NULL; i++) {
  14903. const char *separator = ","; /* default */
  14904. if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
  14905. continue;
  14906. }
  14907. /* Found. Skip keyword, take text in quotes or up to the separator. */
  14908. c += strlen(i->key);
  14909. if (*c == '"') { /* in quotes. Skip first and look for last */
  14910. c++;
  14911. separator = "\"";
  14912. }
  14913. i->s = c;
  14914. strsep(&c, separator);
  14915. break;
  14916. }
  14917. if (i->key == NULL) { /* not found, jump after space or comma */
  14918. strsep(&c, " ,");
  14919. }
  14920. }
  14921. /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
  14922. if (strcasecmp(p->nonce, keys[K_NONCE].s)) {
  14923. if (!req->ignore) {
  14924. build_nonce(p, 1);
  14925. }
  14926. transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
  14927. /* Schedule auto destroy in 32 seconds */
  14928. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14929. } else {
  14930. __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
  14931. }
  14932. }
  14933. /*!
  14934. * Terminate the uri at the first ';' or space.
  14935. * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
  14936. * but don't do it for the time being. Remember the uri format is:
  14937. * (User-parameters was added after RFC 3261)
  14938. *\verbatim
  14939. *
  14940. * sip:user:password;user-parameters@host:port;uri-parameters?headers
  14941. * sips:user:password;user-parameters@host:port;uri-parameters?headers
  14942. *
  14943. *\endverbatim
  14944. * \todo As this function does not support user-parameters, it's considered broken
  14945. * and needs fixing.
  14946. */
  14947. static char *terminate_uri(char *uri)
  14948. {
  14949. char *t = uri;
  14950. while (*t && *t > ' ' && *t != ';') {
  14951. t++;
  14952. }
  14953. *t = '\0';
  14954. return uri;
  14955. }
  14956. /*! \brief Terminate a host:port at the ':'
  14957. * \param hostport The address of the hostport string
  14958. *
  14959. * \note In the case of a bracket-enclosed IPv6 address, the hostport variable
  14960. * will contain the non-bracketed host as a result of calling this function.
  14961. */
  14962. static void extract_host_from_hostport(char **hostport)
  14963. {
  14964. char *dont_care;
  14965. ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
  14966. }
  14967. /*!
  14968. * \internal
  14969. * \brief Helper function to update a peer's lastmsgssent value
  14970. */
  14971. static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
  14972. {
  14973. if (!locked) {
  14974. ao2_lock(peer);
  14975. }
  14976. peer->lastmsgssent = value;
  14977. if (!locked) {
  14978. ao2_unlock(peer);
  14979. }
  14980. }
  14981. /*!
  14982. * \brief Verify registration of user
  14983. *
  14984. * \details
  14985. * - Registration is done in several steps, first a REGISTER without auth
  14986. * to get a challenge (nonce) then a second one with auth
  14987. * - Registration requests are only matched with peers that are marked as "dynamic"
  14988. */
  14989. static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
  14990. struct sip_request *req, const char *uri)
  14991. {
  14992. enum check_auth_result res = AUTH_NOT_FOUND;
  14993. struct sip_peer *peer;
  14994. char tmp[256];
  14995. char *c, *name, *unused_password, *domain;
  14996. char *uri2 = ast_strdupa(uri);
  14997. int send_mwi = 0;
  14998. terminate_uri(uri2);
  14999. ast_copy_string(tmp, sip_get_header(req, "To"), sizeof(tmp));
  15000. c = get_in_brackets(tmp);
  15001. c = remove_uri_parameters(c);
  15002. if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
  15003. ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
  15004. return -1;
  15005. }
  15006. SIP_PEDANTIC_DECODE(name);
  15007. SIP_PEDANTIC_DECODE(domain);
  15008. extract_host_from_hostport(&domain);
  15009. if (ast_strlen_zero(domain)) {
  15010. /* <sip:name@[EMPTY]>, never good */
  15011. transmit_response(p, "404 Not found", &p->initreq);
  15012. return AUTH_UNKNOWN_DOMAIN;
  15013. }
  15014. if (ast_strlen_zero(name)) {
  15015. /* <sip:[EMPTY][@]hostport>, unsure whether valid for
  15016. * registration. RFC 3261, 10.2 states:
  15017. * "The To header field and the Request-URI field typically
  15018. * differ, as the former contains a user name."
  15019. * But, Asterisk has always treated the domain-only uri as a
  15020. * username: we allow admins to create accounts described by
  15021. * domain name. */
  15022. name = domain;
  15023. }
  15024. /* This here differs from 1.4 and 1.6: the domain matching ACLs were
  15025. * skipped if it was a domain-only URI (used as username). Here we treat
  15026. * <sip:hostport> as <sip:host@hostport> and won't forget to test the
  15027. * domain ACLs against host. */
  15028. if (!AST_LIST_EMPTY(&domain_list)) {
  15029. if (!check_sip_domain(domain, NULL, 0)) {
  15030. if (sip_cfg.alwaysauthreject) {
  15031. transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
  15032. } else {
  15033. transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
  15034. }
  15035. return AUTH_UNKNOWN_DOMAIN;
  15036. }
  15037. }
  15038. ast_string_field_set(p, exten, name);
  15039. build_contact(p);
  15040. if (req->ignore) {
  15041. /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
  15042. const char *expires = sip_get_header(req, "Expires");
  15043. int expire = atoi(expires);
  15044. if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
  15045. if ((expires = strcasestr(sip_get_header(req, "Contact"), ";expires="))) {
  15046. expire = atoi(expires + 9);
  15047. }
  15048. }
  15049. if (!ast_strlen_zero(expires) && expire == 0) {
  15050. transmit_response_with_date(p, "200 OK", req);
  15051. return 0;
  15052. }
  15053. }
  15054. peer = sip_find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
  15055. /* If we don't want username disclosure, use the bogus_peer when a user
  15056. * is not found. */
  15057. if (!peer && sip_cfg.alwaysauthreject && sip_cfg.autocreatepeer == AUTOPEERS_DISABLED) {
  15058. peer = bogus_peer;
  15059. sip_ref_peer(peer, "register_verify: ref the bogus_peer");
  15060. }
  15061. if (!(peer && ast_apply_acl(peer->acl, addr, "SIP Peer ACL: "))) {
  15062. /* Peer fails ACL check */
  15063. if (peer) {
  15064. sip_unref_peer(peer, "register_verify: sip_unref_peer: from sip_find_peer operation");
  15065. peer = NULL;
  15066. res = AUTH_ACL_FAILED;
  15067. } else {
  15068. res = AUTH_NOT_FOUND;
  15069. }
  15070. }
  15071. if (peer) {
  15072. ao2_lock(peer);
  15073. if (!peer->host_dynamic) {
  15074. ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
  15075. res = AUTH_PEER_NOT_DYNAMIC;
  15076. } else {
  15077. set_peer_nat(p, peer);
  15078. ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
  15079. if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE))) {
  15080. if (sip_cancel_destroy(p))
  15081. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  15082. if (check_request_transport(peer, req)) {
  15083. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  15084. transmit_response_with_date(p, "403 Forbidden", req);
  15085. res = AUTH_BAD_TRANSPORT;
  15086. } else {
  15087. /* We have a successful registration attempt with proper authentication,
  15088. now, update the peer */
  15089. switch (parse_register_contact(p, peer, req)) {
  15090. case PARSE_REGISTER_DENIED:
  15091. ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
  15092. transmit_response_with_date(p, "603 Denied", req);
  15093. res = 0;
  15094. break;
  15095. case PARSE_REGISTER_FAILED:
  15096. ast_log(LOG_WARNING, "Failed to parse contact info\n");
  15097. transmit_response_with_date(p, "400 Bad Request", req);
  15098. res = 0;
  15099. break;
  15100. case PARSE_REGISTER_QUERY:
  15101. ast_string_field_set(p, fullcontact, peer->fullcontact);
  15102. transmit_response_with_date(p, "200 OK", req);
  15103. res = 0;
  15104. send_mwi = 1;
  15105. break;
  15106. case PARSE_REGISTER_UPDATE:
  15107. ast_string_field_set(p, fullcontact, peer->fullcontact);
  15108. /* If expiry is 0, peer has been unregistered already */
  15109. if (p->expiry != 0) {
  15110. update_peer(peer, p->expiry);
  15111. }
  15112. /* Say OK and ask subsystem to retransmit msg counter */
  15113. transmit_response_with_date(p, "200 OK", req);
  15114. send_mwi = 1;
  15115. res = 0;
  15116. break;
  15117. }
  15118. }
  15119. }
  15120. }
  15121. ao2_unlock(peer);
  15122. }
  15123. if (!peer && sip_cfg.autocreatepeer != AUTOPEERS_DISABLED) {
  15124. /* Create peer if we have autocreate mode enabled */
  15125. peer = temp_peer(name);
  15126. if (peer) {
  15127. ao2_t_link(peers, peer, "link peer into peer table");
  15128. if (!ast_sockaddr_isnull(&peer->addr)) {
  15129. ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
  15130. }
  15131. ao2_lock(peer);
  15132. if (sip_cancel_destroy(p))
  15133. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  15134. switch (parse_register_contact(p, peer, req)) {
  15135. case PARSE_REGISTER_DENIED:
  15136. ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
  15137. transmit_response_with_date(p, "403 Forbidden", req);
  15138. res = 0;
  15139. break;
  15140. case PARSE_REGISTER_FAILED:
  15141. ast_log(LOG_WARNING, "Failed to parse contact info\n");
  15142. transmit_response_with_date(p, "400 Bad Request", req);
  15143. res = 0;
  15144. break;
  15145. case PARSE_REGISTER_QUERY:
  15146. ast_string_field_set(p, fullcontact, peer->fullcontact);
  15147. transmit_response_with_date(p, "200 OK", req);
  15148. send_mwi = 1;
  15149. res = 0;
  15150. break;
  15151. case PARSE_REGISTER_UPDATE:
  15152. ast_string_field_set(p, fullcontact, peer->fullcontact);
  15153. /* Say OK and ask subsystem to retransmit msg counter */
  15154. transmit_response_with_date(p, "200 OK", req);
  15155. if (peer->endpoint) {
  15156. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  15157. ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_ONLINE);
  15158. blob = ast_json_pack("{s: s, s: s}",
  15159. "peer_status", "Registered",
  15160. "address", ast_sockaddr_stringify(addr));
  15161. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  15162. }
  15163. send_mwi = 1;
  15164. res = 0;
  15165. break;
  15166. }
  15167. ao2_unlock(peer);
  15168. }
  15169. }
  15170. if (!res) {
  15171. if (send_mwi) {
  15172. sip_pvt_unlock(p);
  15173. sip_send_mwi_to_peer(peer, 0);
  15174. sip_pvt_lock(p);
  15175. } else {
  15176. update_peer_lastmsgssent(peer, -1, 0);
  15177. }
  15178. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  15179. }
  15180. if (res < 0) {
  15181. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  15182. switch (res) {
  15183. case AUTH_SECRET_FAILED:
  15184. /* Wrong password in authentication. Go away, don't try again until you fixed it */
  15185. transmit_response(p, "403 Forbidden", &p->initreq);
  15186. if (global_authfailureevents) {
  15187. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  15188. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  15189. blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
  15190. "peer_status", "Rejected",
  15191. "cause", "AUTH_SECRET_FAILED",
  15192. "address", peer_addr,
  15193. "port", peer_port);
  15194. }
  15195. break;
  15196. case AUTH_USERNAME_MISMATCH:
  15197. /* Username and digest username does not match.
  15198. Asterisk uses the From: username for authentication. We need the
  15199. devices to use the same authentication user name until we support
  15200. proper authentication by digest auth name */
  15201. case AUTH_NOT_FOUND:
  15202. case AUTH_PEER_NOT_DYNAMIC:
  15203. case AUTH_ACL_FAILED:
  15204. if (sip_cfg.alwaysauthreject) {
  15205. transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
  15206. if (global_authfailureevents) {
  15207. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  15208. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  15209. blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
  15210. "peer_status", "Rejected",
  15211. "cause", res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
  15212. "address", peer_addr,
  15213. "port", peer_port);
  15214. }
  15215. } else {
  15216. /* URI not found */
  15217. if (res == AUTH_PEER_NOT_DYNAMIC) {
  15218. transmit_response(p, "403 Forbidden", &p->initreq);
  15219. if (global_authfailureevents) {
  15220. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  15221. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  15222. blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
  15223. "peer_status", "Rejected",
  15224. "cause", "AUTH_PEER_NOT_DYNAMIC",
  15225. "address", peer_addr,
  15226. "port", peer_port);
  15227. }
  15228. } else {
  15229. transmit_response(p, "404 Not found", &p->initreq);
  15230. if (global_authfailureevents) {
  15231. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  15232. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  15233. blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
  15234. "peer_status", "Rejected",
  15235. "cause", (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
  15236. "address", peer_addr,
  15237. "port", peer_port);
  15238. }
  15239. }
  15240. }
  15241. break;
  15242. case AUTH_BAD_TRANSPORT:
  15243. default:
  15244. break;
  15245. }
  15246. if (peer && peer->endpoint) {
  15247. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  15248. }
  15249. }
  15250. if (peer) {
  15251. sip_unref_peer(peer, "register_verify: sip_unref_peer: tossing stack peer pointer at end of func");
  15252. }
  15253. return res;
  15254. }
  15255. /*! \brief Translate referring cause */
  15256. static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
  15257. if (!strcmp(reason, "unknown")) {
  15258. ast_string_field_set(p, redircause, "UNKNOWN");
  15259. } else if (!strcmp(reason, "user-busy")) {
  15260. ast_string_field_set(p, redircause, "BUSY");
  15261. } else if (!strcmp(reason, "no-answer")) {
  15262. ast_string_field_set(p, redircause, "NOANSWER");
  15263. } else if (!strcmp(reason, "unavailable")) {
  15264. ast_string_field_set(p, redircause, "UNREACHABLE");
  15265. } else if (!strcmp(reason, "unconditional")) {
  15266. ast_string_field_set(p, redircause, "UNCONDITIONAL");
  15267. } else if (!strcmp(reason, "time-of-day")) {
  15268. ast_string_field_set(p, redircause, "UNKNOWN");
  15269. } else if (!strcmp(reason, "do-not-disturb")) {
  15270. ast_string_field_set(p, redircause, "UNKNOWN");
  15271. } else if (!strcmp(reason, "deflection")) {
  15272. ast_string_field_set(p, redircause, "UNKNOWN");
  15273. } else if (!strcmp(reason, "follow-me")) {
  15274. ast_string_field_set(p, redircause, "UNKNOWN");
  15275. } else if (!strcmp(reason, "out-of-service")) {
  15276. ast_string_field_set(p, redircause, "UNREACHABLE");
  15277. } else if (!strcmp(reason, "away")) {
  15278. ast_string_field_set(p, redircause, "UNREACHABLE");
  15279. } else {
  15280. ast_string_field_set(p, redircause, "UNKNOWN");
  15281. }
  15282. }
  15283. /*! \brief Parse the parts of the P-Asserted-Identity header
  15284. * on an incoming packet. Returns 1 if a valid header is found
  15285. * and it is different from the current caller id.
  15286. */
  15287. static int get_pai(struct sip_pvt *p, struct sip_request *req)
  15288. {
  15289. char pai[256];
  15290. char privacy[64];
  15291. char *cid_num = NULL;
  15292. char *cid_name = NULL;
  15293. char emptyname[1] = "";
  15294. int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  15295. char *uri = NULL;
  15296. int is_anonymous = 0, do_update = 1, no_name = 0;
  15297. ast_copy_string(pai, sip_get_header(req, "P-Asserted-Identity"), sizeof(pai));
  15298. if (ast_strlen_zero(pai)) {
  15299. return 0;
  15300. }
  15301. /* use the reqresp_parser function get_name_and_number*/
  15302. if (get_name_and_number(pai, &cid_name, &cid_num)) {
  15303. return 0;
  15304. }
  15305. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
  15306. ast_shrink_phone_number(cid_num);
  15307. }
  15308. uri = get_in_brackets(pai);
  15309. if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
  15310. callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  15311. /*XXX Assume no change in cid_num. Perhaps it should be
  15312. * blanked?
  15313. */
  15314. ast_free(cid_num);
  15315. is_anonymous = 1;
  15316. cid_num = (char *)p->cid_num;
  15317. }
  15318. ast_copy_string(privacy, sip_get_header(req, "Privacy"), sizeof(privacy));
  15319. if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
  15320. callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  15321. }
  15322. if (!cid_name) {
  15323. no_name = 1;
  15324. cid_name = (char *)emptyname;
  15325. }
  15326. /* Only return true if the supplied caller id is different */
  15327. if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
  15328. do_update = 0;
  15329. } else {
  15330. ast_string_field_set(p, cid_num, cid_num);
  15331. ast_string_field_set(p, cid_name, cid_name);
  15332. p->callingpres = callingpres;
  15333. if (p->owner) {
  15334. ast_set_callerid(p->owner, cid_num, cid_name, NULL);
  15335. ast_channel_caller(p->owner)->id.name.presentation = callingpres;
  15336. ast_channel_caller(p->owner)->id.number.presentation = callingpres;
  15337. }
  15338. }
  15339. /* get_name_and_number allocates memory for cid_num and cid_name so we have to free it */
  15340. if (!is_anonymous) {
  15341. ast_free(cid_num);
  15342. }
  15343. if (!no_name) {
  15344. ast_free(cid_name);
  15345. }
  15346. return do_update;
  15347. }
  15348. /*! \brief Get name, number and presentation from remote party id header,
  15349. * returns true if a valid header was found and it was different from the
  15350. * current caller id.
  15351. */
  15352. static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
  15353. {
  15354. char tmp[256];
  15355. struct sip_request *req;
  15356. char *cid_num = "";
  15357. char *cid_name = "";
  15358. int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  15359. char *privacy = "";
  15360. char *screen = "";
  15361. char *start, *end;
  15362. if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
  15363. return 0;
  15364. req = oreq;
  15365. if (!req)
  15366. req = &p->initreq;
  15367. ast_copy_string(tmp, sip_get_header(req, "Remote-Party-ID"), sizeof(tmp));
  15368. if (ast_strlen_zero(tmp)) {
  15369. return get_pai(p, req);
  15370. }
  15371. /*
  15372. * RPID is not:
  15373. * rpid = (name-addr / addr-spec) *(SEMI rpi-token)
  15374. * But it is:
  15375. * rpid = [display-name] LAQUOT addr-spec RAQUOT *(SEMI rpi-token)
  15376. * Ergo, calling parse_name_andor_addr() on it wouldn't be
  15377. * correct because that would allow addr-spec style too.
  15378. */
  15379. start = tmp;
  15380. /* Quoted (note that we're not dealing with escapes properly) */
  15381. if (*start == '"') {
  15382. *start++ = '\0';
  15383. end = strchr(start, '"');
  15384. if (!end)
  15385. return 0;
  15386. *end++ = '\0';
  15387. cid_name = start;
  15388. start = ast_skip_blanks(end);
  15389. /* Unquoted */
  15390. } else {
  15391. cid_name = start;
  15392. start = end = strchr(start, '<');
  15393. if (!start) {
  15394. return 0;
  15395. }
  15396. /* trim blanks if there are any. the mandatory NUL is done below */
  15397. while (--end >= cid_name && *end < 33) {
  15398. *end = '\0';
  15399. }
  15400. }
  15401. if (*start != '<')
  15402. return 0;
  15403. *start++ = '\0';
  15404. end = strchr(start, '@');
  15405. if (!end)
  15406. return 0;
  15407. *end++ = '\0';
  15408. if (strncasecmp(start, "sip:", 4))
  15409. return 0;
  15410. cid_num = start + 4;
  15411. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
  15412. ast_shrink_phone_number(cid_num);
  15413. start = end;
  15414. end = strchr(start, '>');
  15415. if (!end)
  15416. return 0;
  15417. *end++ = '\0';
  15418. if (*end) {
  15419. start = end;
  15420. if (*start != ';')
  15421. return 0;
  15422. *start++ = '\0';
  15423. while (!ast_strlen_zero(start)) {
  15424. end = strchr(start, ';');
  15425. if (end)
  15426. *end++ = '\0';
  15427. if (!strncasecmp(start, "privacy=", 8))
  15428. privacy = start + 8;
  15429. else if (!strncasecmp(start, "screen=", 7))
  15430. screen = start + 7;
  15431. start = end;
  15432. }
  15433. if (!strcasecmp(privacy, "full")) {
  15434. if (!strcasecmp(screen, "yes"))
  15435. callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
  15436. else if (!strcasecmp(screen, "no"))
  15437. callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  15438. } else {
  15439. if (!strcasecmp(screen, "yes"))
  15440. callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
  15441. else if (!strcasecmp(screen, "no"))
  15442. callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  15443. }
  15444. }
  15445. /* Only return true if the supplied caller id is different */
  15446. if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
  15447. return 0;
  15448. ast_string_field_set(p, cid_num, cid_num);
  15449. ast_string_field_set(p, cid_name, cid_name);
  15450. p->callingpres = callingpres;
  15451. if (p->owner) {
  15452. ast_set_callerid(p->owner, cid_num, cid_name, NULL);
  15453. ast_channel_caller(p->owner)->id.name.presentation = callingpres;
  15454. ast_channel_caller(p->owner)->id.number.presentation = callingpres;
  15455. }
  15456. return 1;
  15457. }
  15458. /*! \brief Get referring dnis
  15459. *
  15460. * \param p dialog information
  15461. * \param oreq The request to retrieve RDNIS from
  15462. * \param[out] name The name of the party redirecting the call.
  15463. * \param[out] number The number of the party redirecting the call.
  15464. * \param[out] reason_code The numerical code corresponding to the reason for the redirection.
  15465. * \param[out] reason_str A string describing the reason for redirection. Will never be zero-length
  15466. *
  15467. * \retval -1 Could not retrieve RDNIS information
  15468. * \retval 0 RDNIS successfully retrieved
  15469. */
  15470. static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason_code, char **reason_str)
  15471. {
  15472. char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
  15473. char *params, *reason_param = NULL;
  15474. struct sip_request *req;
  15475. req = oreq ? oreq : &p->initreq;
  15476. ast_copy_string(tmp, sip_get_header(req, "Diversion"), sizeof(tmp));
  15477. if (ast_strlen_zero(tmp))
  15478. return -1;
  15479. if ((params = strchr(tmp, '>'))) {
  15480. params = strchr(params, ';');
  15481. }
  15482. exten = get_in_brackets(tmp);
  15483. if (!strncasecmp(exten, "sip:", 4)) {
  15484. exten += 4;
  15485. } else if (!strncasecmp(exten, "sips:", 5)) {
  15486. exten += 5;
  15487. } else {
  15488. ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
  15489. return -1;
  15490. }
  15491. /* Get diversion-reason param if present */
  15492. if (params) {
  15493. *params = '\0'; /* Cut off parameters */
  15494. params++;
  15495. while (*params == ';' || *params == ' ')
  15496. params++;
  15497. /* Check if we have a reason parameter */
  15498. if ((reason_param = strcasestr(params, "reason="))) {
  15499. char *end;
  15500. reason_param+=7;
  15501. if ((end = strchr(reason_param, ';'))) {
  15502. *end = '\0';
  15503. }
  15504. /* Remove enclosing double-quotes */
  15505. if (*reason_param == '"')
  15506. reason_param = ast_strip_quoted(reason_param, "\"", "\"");
  15507. if (!ast_strlen_zero(reason_param)) {
  15508. sip_set_redirstr(p, reason_param);
  15509. if (p->owner) {
  15510. pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
  15511. pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
  15512. }
  15513. }
  15514. }
  15515. }
  15516. rdomain = exten;
  15517. rexten = strsep(&rdomain, "@"); /* trim anything after @ */
  15518. if (p->owner)
  15519. pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
  15520. if (sip_debug_test_pvt(p)) {
  15521. ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
  15522. }
  15523. /*ast_string_field_set(p, rdnis, rexten);*/
  15524. if (*tmp == '\"') {
  15525. char *end_quote;
  15526. rname = tmp + 1;
  15527. end_quote = strchr(rname, '\"');
  15528. if (end_quote) {
  15529. *end_quote = '\0';
  15530. }
  15531. }
  15532. if (number) {
  15533. *number = ast_strdup(rexten);
  15534. }
  15535. if (name && rname) {
  15536. *name = ast_strdup(rname);
  15537. }
  15538. if (!ast_strlen_zero(reason_param)) {
  15539. if (reason_code) {
  15540. *reason_code = sip_reason_str_to_code(reason_param);
  15541. }
  15542. if (reason_str) {
  15543. *reason_str = ast_strdup(reason_param);
  15544. }
  15545. }
  15546. return 0;
  15547. }
  15548. /*!
  15549. * \brief Find out who the call is for.
  15550. *
  15551. * \details
  15552. * We use the request uri as a destination.
  15553. * This code assumes authentication has been done, so that the
  15554. * device (peer/user) context is already set.
  15555. *
  15556. * \return 0 on success (found a matching extension), non-zero on failure
  15557. *
  15558. * \note If the incoming uri is a SIPS: uri, we are required to carry this across
  15559. * the dialplan, so that the outbound call also is a sips: call or encrypted
  15560. * IAX2 call. If that's not available, the call should FAIL.
  15561. */
  15562. static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
  15563. {
  15564. char tmp[256] = "", *uri, *unused_password, *domain;
  15565. RAII_VAR(char *, tmpf, NULL, ast_free);
  15566. char *from = NULL;
  15567. struct sip_request *req;
  15568. char *decoded_uri;
  15569. RAII_VAR(struct ast_features_pickup_config *, pickup_cfg, ast_get_chan_features_pickup_config(p->owner), ao2_cleanup);
  15570. const char *pickupexten;
  15571. if (!pickup_cfg) {
  15572. ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
  15573. pickupexten = "";
  15574. } else {
  15575. /* Don't need to duplicate since channel is locked for the duration of this function */
  15576. pickupexten = pickup_cfg->pickupexten;
  15577. }
  15578. req = oreq;
  15579. if (!req) {
  15580. req = &p->initreq;
  15581. }
  15582. /* Find the request URI */
  15583. if (req->rlpart2) {
  15584. ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlpart2), sizeof(tmp));
  15585. }
  15586. uri = ast_strdupa(get_in_brackets(tmp));
  15587. if (parse_uri_legacy_check(uri, "sip:,sips:,tel:", &uri, &unused_password, &domain, NULL)) {
  15588. ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
  15589. return SIP_GET_DEST_INVALID_URI;
  15590. }
  15591. SIP_PEDANTIC_DECODE(domain);
  15592. SIP_PEDANTIC_DECODE(uri);
  15593. extract_host_from_hostport(&domain);
  15594. if (strncasecmp(get_in_brackets(tmp), "tel:", 4)) {
  15595. ast_string_field_set(p, domain, domain);
  15596. } else {
  15597. ast_string_field_set(p, tel_phone_context, domain);
  15598. }
  15599. if (ast_strlen_zero(uri)) {
  15600. /*
  15601. * Either there really was no extension found or the request
  15602. * URI had encoded nulls that made the string "empty". Use "s"
  15603. * as the extension.
  15604. */
  15605. uri = "s";
  15606. }
  15607. /* Now find the From: caller ID and name */
  15608. /* XXX Why is this done in get_destination? Isn't it already done?
  15609. Needs to be checked
  15610. */
  15611. tmpf = ast_strdup(sip_get_header(req, "From"));
  15612. if (!ast_strlen_zero(tmpf)) {
  15613. from = get_in_brackets(tmpf);
  15614. if (parse_uri_legacy_check(from, "sip:,sips:,tel:", &from, NULL, &domain, NULL)) {
  15615. ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
  15616. return SIP_GET_DEST_INVALID_URI;
  15617. }
  15618. SIP_PEDANTIC_DECODE(from);
  15619. SIP_PEDANTIC_DECODE(domain);
  15620. extract_host_from_hostport(&domain);
  15621. ast_string_field_set(p, fromdomain, domain);
  15622. }
  15623. if (!AST_LIST_EMPTY(&domain_list)) {
  15624. char domain_context[AST_MAX_EXTENSION];
  15625. domain_context[0] = '\0';
  15626. if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
  15627. if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
  15628. ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
  15629. return SIP_GET_DEST_REFUSED;
  15630. }
  15631. }
  15632. /* If we don't have a peer (i.e. we're a guest call),
  15633. * overwrite the original context */
  15634. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
  15635. ast_string_field_set(p, context, domain_context);
  15636. }
  15637. }
  15638. /* If the request coming in is a subscription and subscribecontext has been specified use it */
  15639. if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
  15640. ast_string_field_set(p, context, p->subscribecontext);
  15641. }
  15642. if (sip_debug_test_pvt(p)) {
  15643. ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
  15644. }
  15645. /* Since extensions.conf can have unescaped characters, try matching a
  15646. * decoded uri in addition to the non-decoded uri. */
  15647. decoded_uri = ast_strdupa(uri);
  15648. ast_uri_decode(decoded_uri, ast_uri_sip_user);
  15649. /* If this is a subscription we actually just need to see if a hint exists for the extension */
  15650. if (req->method == SIP_SUBSCRIBE) {
  15651. char hint[AST_MAX_EXTENSION];
  15652. int which = 0;
  15653. if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
  15654. (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
  15655. if (!oreq) {
  15656. ast_string_field_set(p, exten, which ? decoded_uri : uri);
  15657. }
  15658. return SIP_GET_DEST_EXTEN_FOUND;
  15659. } else {
  15660. return SIP_GET_DEST_EXTEN_NOT_FOUND;
  15661. }
  15662. } else {
  15663. struct ast_cc_agent *agent;
  15664. /* Check the dialplan for the username part of the request URI,
  15665. the domain will be stored in the SIPDOMAIN variable
  15666. Return 0 if we have a matching extension */
  15667. if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
  15668. if (!oreq) {
  15669. ast_string_field_set(p, exten, uri);
  15670. }
  15671. return SIP_GET_DEST_EXTEN_FOUND;
  15672. }
  15673. if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
  15674. || !strcmp(decoded_uri, pickupexten)) {
  15675. if (!oreq) {
  15676. ast_string_field_set(p, exten, decoded_uri);
  15677. }
  15678. return SIP_GET_DEST_EXTEN_FOUND;
  15679. }
  15680. if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
  15681. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  15682. /* This is a CC recall. We can set p's extension to the exten from
  15683. * the original INVITE
  15684. */
  15685. ast_string_field_set(p, exten, agent_pvt->original_exten);
  15686. /* And we need to let the CC core know that the caller is attempting
  15687. * his recall
  15688. */
  15689. ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
  15690. agent->device_name);
  15691. if (cc_recall_core_id) {
  15692. *cc_recall_core_id = agent->core_id;
  15693. }
  15694. ao2_ref(agent, -1);
  15695. return SIP_GET_DEST_EXTEN_FOUND;
  15696. }
  15697. }
  15698. if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
  15699. && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
  15700. || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
  15701. || !strncmp(decoded_uri, pickupexten, strlen(decoded_uri)))) {
  15702. /* Overlap dialing is enabled and we need more digits to match an extension. */
  15703. return SIP_GET_DEST_EXTEN_MATCHMORE;
  15704. }
  15705. return SIP_GET_DEST_EXTEN_NOT_FOUND;
  15706. }
  15707. /*! \brief Find a companion dialog based on Replaces information
  15708. *
  15709. * This information may come from a Refer-To header in a REFER or from
  15710. * a Replaces header in an INVITE.
  15711. *
  15712. * This function will find the appropriate sip_pvt and increment the refcount
  15713. * of both the sip_pvt and its owner channel. These two references are returned
  15714. * in the out parameters
  15715. *
  15716. * \param callid Callid to search for
  15717. * \param totag to-tag parameter from Replaces
  15718. * \param fromtag from-tag parameter from Replaces
  15719. * \param[out] out_pvt The found sip_pvt.
  15720. * \param[out] out_chan The found sip_pvt's owner channel.
  15721. * \retval 0 Success
  15722. * \retval non-zero Failure
  15723. */
  15724. static int get_sip_pvt_from_replaces(const char *callid, const char *totag,
  15725. const char *fromtag, struct sip_pvt **out_pvt, struct ast_channel **out_chan)
  15726. {
  15727. struct sip_pvt *sip_pvt_ptr;
  15728. struct sip_pvt tmp_dialog = {
  15729. .callid = callid,
  15730. };
  15731. if (totag) {
  15732. ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
  15733. }
  15734. /* Search dialogs and find the match */
  15735. sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
  15736. if (sip_pvt_ptr) {
  15737. /* Go ahead and lock it (and its owner) before returning */
  15738. SCOPED_LOCK(lock, sip_pvt_ptr, sip_pvt_lock, sip_pvt_unlock);
  15739. if (sip_cfg.pedanticsipchecking) {
  15740. unsigned char frommismatch = 0, tomismatch = 0;
  15741. if (ast_strlen_zero(fromtag)) {
  15742. ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
  15743. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
  15744. return -1;
  15745. }
  15746. if (ast_strlen_zero(totag)) {
  15747. ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
  15748. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
  15749. return -1;
  15750. }
  15751. /* RFC 3891
  15752. * > 3. User Agent Server Behavior: Receiving a Replaces Header
  15753. * > The Replaces header contains information used to match an existing
  15754. * > SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE
  15755. * > with a Replaces header, the User Agent (UA) attempts to match this
  15756. * > information with a confirmed or early dialog. The User Agent Server
  15757. * > (UAS) matches the to-tag and from-tag parameters as if they were tags
  15758. * > present in an incoming request. In other words, the to-tag parameter
  15759. * > is compared to the local tag, and the from-tag parameter is compared
  15760. * > to the remote tag.
  15761. *
  15762. * Thus, the totag is always compared to the local tag, regardless if
  15763. * this our call is an incoming or outgoing call.
  15764. */
  15765. frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
  15766. tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
  15767. /* Don't check from if the dialog is not established, due to multi forking the from
  15768. * can change when the call is not answered yet.
  15769. */
  15770. if ((frommismatch && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) || tomismatch) {
  15771. if (frommismatch) {
  15772. ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
  15773. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
  15774. fromtag, sip_pvt_ptr->theirtag);
  15775. }
  15776. if (tomismatch) {
  15777. ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
  15778. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
  15779. totag, sip_pvt_ptr->tag);
  15780. }
  15781. return -1;
  15782. }
  15783. }
  15784. if (totag)
  15785. ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
  15786. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
  15787. sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
  15788. *out_pvt = sip_pvt_ptr;
  15789. if (out_chan) {
  15790. *out_chan = sip_pvt_ptr->owner ? ast_channel_ref(sip_pvt_ptr->owner) : NULL;
  15791. }
  15792. }
  15793. return 0;
  15794. }
  15795. /*! \brief Call transfer support (the REFER method)
  15796. * Extracts Refer headers into pvt dialog structure
  15797. *
  15798. * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
  15799. * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
  15800. * flag.
  15801. */
  15802. static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
  15803. {
  15804. const char *p_referred_by = NULL;
  15805. char *h_refer_to = NULL;
  15806. char *h_referred_by = NULL;
  15807. char *refer_to;
  15808. const char *p_refer_to;
  15809. char *referred_by_uri = NULL;
  15810. char *ptr;
  15811. struct sip_request *req = NULL;
  15812. const char *transfer_context = NULL;
  15813. struct sip_refer *refer;
  15814. req = outgoing_req;
  15815. refer = transferer->refer;
  15816. if (!req) {
  15817. req = &transferer->initreq;
  15818. }
  15819. p_refer_to = sip_get_header(req, "Refer-To");
  15820. if (ast_strlen_zero(p_refer_to)) {
  15821. ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
  15822. return -2; /* Syntax error */
  15823. }
  15824. h_refer_to = ast_strdupa(p_refer_to);
  15825. refer_to = get_in_brackets(h_refer_to);
  15826. if (!strncasecmp(refer_to, "sip:", 4)) {
  15827. refer_to += 4; /* Skip sip: */
  15828. } else if (!strncasecmp(refer_to, "sips:", 5)) {
  15829. refer_to += 5;
  15830. } else {
  15831. ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
  15832. return -3;
  15833. }
  15834. /* Get referred by header if it exists */
  15835. p_referred_by = sip_get_header(req, "Referred-By");
  15836. /* Give useful transfer information to the dialplan */
  15837. if (transferer->owner) {
  15838. RAII_VAR(struct ast_channel *, peer, NULL, ast_channel_cleanup);
  15839. RAII_VAR(struct ast_channel *, owner_relock, NULL, ast_channel_cleanup);
  15840. RAII_VAR(struct ast_channel *, owner_ref, NULL, ast_channel_cleanup);
  15841. /* Grab a reference to transferer->owner to prevent it from going away */
  15842. owner_ref = ast_channel_ref(transferer->owner);
  15843. /* Established locking order here is bridge, channel, pvt
  15844. * and the bridge will be locked during ast_channel_bridge_peer */
  15845. ast_channel_unlock(owner_ref);
  15846. sip_pvt_unlock(transferer);
  15847. peer = ast_channel_bridge_peer(owner_ref);
  15848. if (peer) {
  15849. pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT",
  15850. S_OR(transferer->context, NULL));
  15851. pbx_builtin_setvar_helper(peer, "__SIPREFERREDBYHDR",
  15852. S_OR(p_referred_by, NULL));
  15853. ast_channel_unlock(peer);
  15854. }
  15855. owner_relock = sip_pvt_lock_full(transferer);
  15856. if (!owner_relock) {
  15857. ast_debug(3, "Unable to reacquire owner channel lock, channel is gone\n");
  15858. return -5;
  15859. }
  15860. }
  15861. if (!ast_strlen_zero(p_referred_by)) {
  15862. h_referred_by = ast_strdupa(p_referred_by);
  15863. referred_by_uri = get_in_brackets(h_referred_by);
  15864. if (!strncasecmp(referred_by_uri, "sip:", 4)) {
  15865. referred_by_uri += 4; /* Skip sip: */
  15866. } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
  15867. referred_by_uri += 5; /* Skip sips: */
  15868. } else {
  15869. ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
  15870. referred_by_uri = NULL;
  15871. }
  15872. }
  15873. /* Check for arguments in the refer_to header */
  15874. if ((ptr = strcasestr(refer_to, "replaces="))) {
  15875. char *to = NULL, *from = NULL, *callid;
  15876. /* This is an attended transfer */
  15877. refer->attendedtransfer = 1;
  15878. callid = ast_strdupa(ptr + 9);
  15879. ast_uri_decode(callid, ast_uri_sip_user);
  15880. if ((ptr = strchr(callid, ';'))) { /* Find options */
  15881. *ptr++ = '\0';
  15882. }
  15883. ast_string_field_set(refer, replaces_callid, callid);
  15884. if (ptr) {
  15885. /* Find the different tags before we destroy the string */
  15886. to = strcasestr(ptr, "to-tag=");
  15887. from = strcasestr(ptr, "from-tag=");
  15888. }
  15889. /* Grab the to header */
  15890. if (to) {
  15891. ptr = to + 7;
  15892. if ((to = strchr(ptr, '&'))) {
  15893. *to = '\0';
  15894. }
  15895. if ((to = strchr(ptr, ';'))) {
  15896. *to = '\0';
  15897. }
  15898. ast_string_field_set(refer, replaces_callid_totag, ptr);
  15899. }
  15900. if (from) {
  15901. ptr = from + 9;
  15902. if ((from = strchr(ptr, '&'))) {
  15903. *from = '\0';
  15904. }
  15905. if ((from = strchr(ptr, ';'))) {
  15906. *from = '\0';
  15907. }
  15908. ast_string_field_set(refer, replaces_callid_fromtag, ptr);
  15909. }
  15910. if (!strcmp(refer->replaces_callid, transferer->callid) &&
  15911. (!sip_cfg.pedanticsipchecking ||
  15912. (!strcmp(refer->replaces_callid_fromtag, transferer->theirtag) &&
  15913. !strcmp(refer->replaces_callid_totag, transferer->tag)))) {
  15914. ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
  15915. return -4;
  15916. }
  15917. if (!sip_cfg.pedanticsipchecking) {
  15918. ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", refer->replaces_callid);
  15919. } else {
  15920. 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>");
  15921. }
  15922. }
  15923. if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
  15924. char *urioption = NULL, *domain;
  15925. int bracket = 0;
  15926. *ptr++ = '\0';
  15927. if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
  15928. *urioption++ = '\0';
  15929. }
  15930. domain = ptr;
  15931. /* Remove :port */
  15932. for (; *ptr != '\0'; ++ptr) {
  15933. if (*ptr == ':' && bracket == 0) {
  15934. *ptr = '\0';
  15935. break;
  15936. } else if (*ptr == '[') {
  15937. ++bracket;
  15938. } else if (*ptr == ']') {
  15939. --bracket;
  15940. }
  15941. }
  15942. SIP_PEDANTIC_DECODE(domain);
  15943. SIP_PEDANTIC_DECODE(urioption);
  15944. /* Save the domain for the dial plan */
  15945. ast_string_field_set(refer, refer_to_domain, domain);
  15946. if (urioption) {
  15947. ast_string_field_set(refer, refer_to_urioption, urioption);
  15948. }
  15949. }
  15950. if ((ptr = strchr(refer_to, ';'))) /* Remove options */
  15951. *ptr = '\0';
  15952. SIP_PEDANTIC_DECODE(refer_to);
  15953. ast_string_field_set(refer, refer_to, refer_to);
  15954. if (referred_by_uri) {
  15955. if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
  15956. *ptr = '\0';
  15957. SIP_PEDANTIC_DECODE(referred_by_uri);
  15958. ast_string_field_build(refer, referred_by, "<sip:%s>", referred_by_uri);
  15959. } else {
  15960. ast_string_field_set(refer, referred_by, "");
  15961. }
  15962. /* Determine transfer context */
  15963. if (transferer->owner) {
  15964. /* By default, use the context in the channel sending the REFER */
  15965. transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
  15966. if (ast_strlen_zero(transfer_context)) {
  15967. transfer_context = ast_channel_macrocontext(transferer->owner);
  15968. }
  15969. }
  15970. if (ast_strlen_zero(transfer_context)) {
  15971. transfer_context = S_OR(transferer->context, sip_cfg.default_context);
  15972. }
  15973. ast_string_field_set(refer, refer_to_context, transfer_context);
  15974. /* Either an existing extension or the parking extension */
  15975. if (refer->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL)) {
  15976. if (sip_debug_test_pvt(transferer)) {
  15977. ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, S_OR(referred_by_uri, "Unknown"));
  15978. }
  15979. /* We are ready to transfer to the extension */
  15980. return 0;
  15981. }
  15982. if (sip_debug_test_pvt(transferer))
  15983. ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
  15984. /* Failure, we can't find this extension */
  15985. return -1;
  15986. }
  15987. /*! \brief Call transfer support (old way, deprecated by the IETF)
  15988. * \note does not account for SIPS: uri requirements, nor check transport
  15989. */
  15990. static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
  15991. {
  15992. char tmp[256] = "", *c, *a;
  15993. struct sip_request *req = oreq ? oreq : &p->initreq;
  15994. struct sip_refer *refer = NULL;
  15995. const char *transfer_context = NULL;
  15996. if (!p->refer && !sip_refer_alloc(p))
  15997. return -1;
  15998. refer = p->refer;
  15999. ast_copy_string(tmp, sip_get_header(req, "Also"), sizeof(tmp));
  16000. c = get_in_brackets(tmp);
  16001. if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
  16002. ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
  16003. return -1;
  16004. }
  16005. SIP_PEDANTIC_DECODE(c);
  16006. SIP_PEDANTIC_DECODE(a);
  16007. if (!ast_strlen_zero(a)) {
  16008. ast_string_field_set(refer, refer_to_domain, a);
  16009. }
  16010. if (sip_debug_test_pvt(p))
  16011. ast_verbose("Looking for %s in %s\n", c, p->context);
  16012. /* Determine transfer context */
  16013. if (p->owner) {
  16014. /* By default, use the context in the channel sending the REFER */
  16015. transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
  16016. if (ast_strlen_zero(transfer_context)) {
  16017. transfer_context = ast_channel_macrocontext(p->owner);
  16018. }
  16019. }
  16020. if (ast_strlen_zero(transfer_context)) {
  16021. transfer_context = S_OR(p->context, sip_cfg.default_context);
  16022. }
  16023. if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
  16024. /* This is a blind transfer */
  16025. ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
  16026. ast_string_field_set(refer, refer_to, c);
  16027. ast_string_field_set(refer, referred_by, "");
  16028. ast_string_field_set(refer, refer_contact, "");
  16029. /* Set new context */
  16030. ast_string_field_set(p, context, transfer_context);
  16031. return 0;
  16032. } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
  16033. return 1;
  16034. }
  16035. return -1;
  16036. }
  16037. /*! \brief Set the peers nat flags if they are using auto_* settings */
  16038. static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer)
  16039. {
  16040. if (!p || !peer) {
  16041. return;
  16042. }
  16043. if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
  16044. if (p->natdetected) {
  16045. ast_set_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
  16046. } else {
  16047. ast_clear_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
  16048. }
  16049. }
  16050. if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
  16051. if (p->natdetected) {
  16052. ast_set_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
  16053. } else {
  16054. ast_clear_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
  16055. }
  16056. }
  16057. }
  16058. /*! \brief Check and see if the requesting UA is likely to be behind a NAT.
  16059. *
  16060. * If the requesting NAT is behind NAT, set the * natdetected flag so that
  16061. * later, peers with nat=auto_* can use the value. Also, set the flags so
  16062. * that Asterisk responds identically whether or not a peer exists so as
  16063. * not to leak peer name information.
  16064. */
  16065. static void check_for_nat(const struct ast_sockaddr *addr, struct sip_pvt *p)
  16066. {
  16067. if (!addr || !p) {
  16068. return;
  16069. }
  16070. if (ast_sockaddr_cmp_addr(addr, &p->recv)) {
  16071. char *tmp_str = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  16072. ast_debug(3, "NAT detected for %s / %s\n", tmp_str, ast_sockaddr_stringify_addr(&p->recv));
  16073. p->natdetected = 1;
  16074. if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
  16075. ast_set_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
  16076. }
  16077. if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
  16078. ast_set_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
  16079. }
  16080. } else {
  16081. p->natdetected = 0;
  16082. if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
  16083. ast_clear_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
  16084. }
  16085. if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
  16086. ast_clear_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
  16087. }
  16088. }
  16089. }
  16090. /*! \brief check Via: header for hostname, port and rport request/answer */
  16091. static void check_via(struct sip_pvt *p, const struct sip_request *req)
  16092. {
  16093. char via[512];
  16094. char *c, *maddr;
  16095. struct ast_sockaddr tmp = { { 0, } };
  16096. uint16_t port;
  16097. ast_copy_string(via, sip_get_header(req, "Via"), sizeof(via));
  16098. /* If this is via WebSocket we don't use the Via header contents at all */
  16099. if (!strncasecmp(via, "SIP/2.0/WS", 10)) {
  16100. return;
  16101. }
  16102. /* Work on the leftmost value of the topmost Via header */
  16103. c = strchr(via, ',');
  16104. if (c)
  16105. *c = '\0';
  16106. /* Check for rport */
  16107. c = strstr(via, ";rport");
  16108. if (c && (c[6] != '=')) { /* rport query, not answer */
  16109. ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
  16110. ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
  16111. }
  16112. /* Check for maddr */
  16113. maddr = strstr(via, "maddr=");
  16114. if (maddr) {
  16115. maddr += 6;
  16116. c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
  16117. "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
  16118. *c = '\0';
  16119. }
  16120. c = strchr(via, ';');
  16121. if (c)
  16122. *c = '\0';
  16123. c = strchr(via, ' ');
  16124. if (c) {
  16125. *c = '\0';
  16126. c = ast_skip_blanks(c+1);
  16127. if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
  16128. ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
  16129. return;
  16130. }
  16131. if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
  16132. p->sa = p->recv;
  16133. }
  16134. if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
  16135. ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
  16136. port = STANDARD_SIP_PORT;
  16137. } else if (!(port = ast_sockaddr_port(&tmp))) {
  16138. port = STANDARD_SIP_PORT;
  16139. ast_sockaddr_set_port(&tmp, port);
  16140. }
  16141. ast_sockaddr_set_port(&p->sa, port);
  16142. check_for_nat(&tmp, p);
  16143. if (sip_debug_test_pvt(p)) {
  16144. ast_verbose("Sending to %s (%s)\n",
  16145. ast_sockaddr_stringify(sip_real_dst(p)),
  16146. sip_nat_mode(p));
  16147. }
  16148. }
  16149. }
  16150. /*! \brief Validate device authentication */
  16151. static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
  16152. struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
  16153. struct sip_peer **authpeer,
  16154. enum xmittype reliable, char *calleridname, char *uri2)
  16155. {
  16156. enum check_auth_result res;
  16157. int debug = sip_debug_test_addr(addr);
  16158. struct sip_peer *peer;
  16159. if (sipmethod == SIP_SUBSCRIBE) {
  16160. /* For subscribes, match on device name only; for other methods,
  16161. * match on IP address-port of the incoming request.
  16162. */
  16163. peer = sip_find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
  16164. } else {
  16165. /* First find devices based on username (avoid all type=peer's) */
  16166. peer = sip_find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
  16167. /* Then find devices based on IP */
  16168. if (!peer) {
  16169. char *uri_tmp, *callback = NULL, *dummy;
  16170. uri_tmp = ast_strdupa(uri2);
  16171. parse_uri(uri_tmp, "sip:,sips:,tel:", &callback, &dummy, &dummy, &dummy);
  16172. if (!ast_strlen_zero(callback) && (peer = sip_find_peer_by_ip_and_exten(&p->recv, callback, p->socket.type))) {
  16173. ; /* found, fall through */
  16174. } else {
  16175. peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
  16176. }
  16177. }
  16178. }
  16179. if (!peer) {
  16180. if (debug) {
  16181. ast_verbose("No matching peer for '%s' from '%s'\n",
  16182. of, ast_sockaddr_stringify(&p->recv));
  16183. }
  16184. /* If you don't mind, we can return 404s for devices that do
  16185. * not exist: username disclosure. If we allow guests, there
  16186. * is no way around that. */
  16187. if (sip_cfg.allowguest || !sip_cfg.alwaysauthreject) {
  16188. return AUTH_DONT_KNOW;
  16189. }
  16190. /* If you do mind, we use a peer that will never authenticate.
  16191. * This ensures that we follow the same code path as regular
  16192. * auth: less chance for username disclosure. */
  16193. peer = bogus_peer;
  16194. sip_ref_peer(peer, "sip_ref_peer: check_peer_ok: must ref bogus_peer so unreffing it does not fail");
  16195. }
  16196. /* build_peer, called through sip_find_peer, is not able to check the
  16197. * sip_pvt->natdetected flag in order to determine if the peer is behind
  16198. * NAT or not when SIP_PAGE3_NAT_AUTO_RPORT or SIP_PAGE3_NAT_AUTO_COMEDIA
  16199. * are set on the peer. So we check for that here and set the peer's
  16200. * address accordingly.
  16201. */
  16202. set_peer_nat(p, peer);
  16203. if (p->natdetected && ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
  16204. ast_sockaddr_copy(&peer->addr, &p->recv);
  16205. }
  16206. if (!ast_apply_acl(peer->acl, addr, "SIP Peer ACL: ")) {
  16207. ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
  16208. sip_unref_peer(peer, "sip_unref_peer: check_peer_ok: from sip_find_peer call, early return of AUTH_ACL_FAILED");
  16209. return AUTH_ACL_FAILED;
  16210. }
  16211. if (debug && peer != bogus_peer) {
  16212. ast_verbose("Found peer '%s' for '%s' from %s\n",
  16213. peer->name, of, ast_sockaddr_stringify(&p->recv));
  16214. }
  16215. /* Set Frame packetization */
  16216. if (p->rtp) {
  16217. ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(p->rtp), ast_format_cap_get_framing(peer->caps));
  16218. p->autoframing = peer->autoframing;
  16219. }
  16220. /* Take the peer */
  16221. ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
  16222. ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  16223. ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  16224. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
  16225. p->t38_maxdatagram = peer->t38_maxdatagram;
  16226. set_t38_capabilities(p);
  16227. }
  16228. ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &p->dtls_cfg);
  16229. /* Copy SIP extensions profile to peer */
  16230. /* XXX is this correct before a successful auth ? */
  16231. if (p->sipoptions)
  16232. peer->sipoptions = p->sipoptions;
  16233. do_setnat(p);
  16234. ast_string_field_set(p, peersecret, peer->secret);
  16235. ast_string_field_set(p, peermd5secret, peer->md5secret);
  16236. ast_string_field_set(p, subscribecontext, peer->subscribecontext);
  16237. ast_string_field_set(p, mohinterpret, peer->mohinterpret);
  16238. ast_string_field_set(p, mohsuggest, peer->mohsuggest);
  16239. if (!ast_strlen_zero(peer->parkinglot)) {
  16240. ast_string_field_set(p, parkinglot, peer->parkinglot);
  16241. }
  16242. ast_string_field_set(p, engine, peer->engine);
  16243. p->disallowed_methods = peer->disallowed_methods;
  16244. set_pvt_allowed_methods(p, req);
  16245. ast_cc_copy_config_params(p->cc_params, peer->cc_params);
  16246. if (peer->callingpres) /* Peer calling pres setting will override RPID */
  16247. p->callingpres = peer->callingpres;
  16248. if (peer->maxms && peer->lastms)
  16249. p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
  16250. else
  16251. p->timer_t1 = peer->timer_t1;
  16252. /* Set timer B to control transaction timeouts */
  16253. if (peer->timer_b)
  16254. p->timer_b = peer->timer_b;
  16255. else
  16256. p->timer_b = 64 * p->timer_t1;
  16257. p->allowtransfer = peer->allowtransfer;
  16258. if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
  16259. /* Pretend there is no required authentication */
  16260. ast_string_field_set(p, peersecret, NULL);
  16261. ast_string_field_set(p, peermd5secret, NULL);
  16262. }
  16263. if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable))) {
  16264. /* If we have a call limit, set flag */
  16265. if (peer->call_limit)
  16266. ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
  16267. ast_string_field_set(p, peername, peer->name);
  16268. ast_string_field_set(p, authname, peer->name);
  16269. ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &p->dtls_cfg);
  16270. if (sipmethod == SIP_INVITE) {
  16271. /* destroy old channel vars and copy in new ones. */
  16272. ast_variables_destroy(p->chanvars);
  16273. p->chanvars = copy_vars(peer->chanvars);
  16274. }
  16275. if (authpeer) {
  16276. ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
  16277. (*authpeer) = peer; /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
  16278. }
  16279. if (!ast_strlen_zero(peer->username)) {
  16280. ast_string_field_set(p, username, peer->username);
  16281. /* Use the default username for authentication on outbound calls */
  16282. /* XXX this takes the name from the caller... can we override ? */
  16283. ast_string_field_set(p, authname, peer->username);
  16284. }
  16285. if (!get_rpid(p, req)) {
  16286. if (!ast_strlen_zero(peer->cid_num)) {
  16287. char *tmp = ast_strdupa(peer->cid_num);
  16288. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
  16289. ast_shrink_phone_number(tmp);
  16290. ast_string_field_set(p, cid_num, tmp);
  16291. }
  16292. if (!ast_strlen_zero(peer->cid_name))
  16293. ast_string_field_set(p, cid_name, peer->cid_name);
  16294. if (peer->callingpres)
  16295. p->callingpres = peer->callingpres;
  16296. }
  16297. if (!ast_strlen_zero(peer->cid_tag)) {
  16298. ast_string_field_set(p, cid_tag, peer->cid_tag);
  16299. }
  16300. ast_string_field_set(p, fullcontact, peer->fullcontact);
  16301. if (!ast_strlen_zero(peer->context)) {
  16302. ast_string_field_set(p, context, peer->context);
  16303. }
  16304. if (!ast_strlen_zero(peer->messagecontext)) {
  16305. ast_string_field_set(p, messagecontext, peer->messagecontext);
  16306. }
  16307. if (!ast_strlen_zero(peer->mwi_from)) {
  16308. ast_string_field_set(p, mwi_from, peer->mwi_from);
  16309. }
  16310. ast_string_field_set(p, peersecret, peer->secret);
  16311. ast_string_field_set(p, peermd5secret, peer->md5secret);
  16312. ast_string_field_set(p, language, peer->language);
  16313. ast_string_field_set(p, accountcode, peer->accountcode);
  16314. p->amaflags = peer->amaflags;
  16315. p->callgroup = peer->callgroup;
  16316. p->pickupgroup = peer->pickupgroup;
  16317. ast_unref_namedgroups(p->named_callgroups);
  16318. p->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);
  16319. ast_unref_namedgroups(p->named_pickupgroups);
  16320. p->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
  16321. ast_format_cap_remove_by_type(p->caps, AST_MEDIA_TYPE_UNKNOWN);
  16322. ast_format_cap_append_from_cap(p->caps, peer->caps, AST_MEDIA_TYPE_UNKNOWN);
  16323. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  16324. ast_format_cap_append_from_cap(p->jointcaps, peer->caps, AST_MEDIA_TYPE_UNKNOWN);
  16325. ast_copy_string(p->zone, peer->zone, sizeof(p->zone));
  16326. if (peer->maxforwards > 0) {
  16327. p->maxforwards = peer->maxforwards;
  16328. }
  16329. if (ast_format_cap_count(p->peercaps)) {
  16330. struct ast_format_cap *joint;
  16331. joint = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  16332. if (joint) {
  16333. ast_format_cap_get_compatible(p->jointcaps, p->peercaps, joint);
  16334. ao2_ref(p->jointcaps, -1);
  16335. p->jointcaps = joint;
  16336. }
  16337. }
  16338. p->maxcallbitrate = peer->maxcallbitrate;
  16339. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
  16340. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
  16341. p->noncodeccapability |= AST_RTP_DTMF;
  16342. else
  16343. p->noncodeccapability &= ~AST_RTP_DTMF;
  16344. p->jointnoncodeccapability = p->noncodeccapability;
  16345. p->rtptimeout = peer->rtptimeout;
  16346. p->rtpholdtimeout = peer->rtpholdtimeout;
  16347. p->rtpkeepalive = peer->rtpkeepalive;
  16348. if (!dialog_initialize_rtp(p)) {
  16349. if (p->rtp) {
  16350. ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(p->rtp), ast_format_cap_get_framing(peer->caps));
  16351. p->autoframing = peer->autoframing;
  16352. }
  16353. } else {
  16354. res = AUTH_RTP_FAILED;
  16355. }
  16356. }
  16357. sip_unref_peer(peer, "check_peer_ok: sip_unref_peer: tossing temp ptr to peer from sip_find_peer");
  16358. return res;
  16359. }
  16360. /*! \brief Check if matching user or peer is defined
  16361. Match user on From: user name and peer on IP/port
  16362. This is used on first invite (not re-invites) and subscribe requests
  16363. \return 0 on success, non-zero on failure
  16364. */
  16365. static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
  16366. int sipmethod, const char *uri, enum xmittype reliable,
  16367. struct ast_sockaddr *addr, struct sip_peer **authpeer)
  16368. {
  16369. char *of, *name, *unused_password, *domain;
  16370. RAII_VAR(char *, ofbuf, NULL, ast_free); /* beware, everyone starts pointing to this */
  16371. RAII_VAR(char *, namebuf, NULL, ast_free);
  16372. enum check_auth_result res = AUTH_DONT_KNOW;
  16373. char calleridname[256];
  16374. char *uri2 = ast_strdupa(uri);
  16375. terminate_uri(uri2); /* trim extra stuff */
  16376. ofbuf = ast_strdup(sip_get_header(req, "From"));
  16377. /* XXX here tries to map the username for invite things */
  16378. /* strip the display-name portion off the beginning of the FROM header. */
  16379. if (!(of = (char *) get_calleridname(ofbuf, calleridname, sizeof(calleridname)))) {
  16380. ast_log(LOG_ERROR, "FROM header can not be parsed\n");
  16381. return res;
  16382. }
  16383. if (calleridname[0]) {
  16384. ast_string_field_set(p, cid_name, calleridname);
  16385. }
  16386. if (ast_strlen_zero(p->exten)) {
  16387. char *t = uri2;
  16388. if (!strncasecmp(t, "sip:", 4)) {
  16389. t += 4;
  16390. } else if (!strncasecmp(t, "sips:", 5)) {
  16391. t += 5;
  16392. } else if (!strncasecmp(t, "tel:", 4)) { /* TEL URI INVITE */
  16393. t += 4;
  16394. }
  16395. ast_string_field_set(p, exten, t);
  16396. t = strchr(p->exten, '@');
  16397. if (t)
  16398. *t = '\0';
  16399. if (ast_strlen_zero(p->our_contact))
  16400. build_contact(p);
  16401. }
  16402. of = get_in_brackets(of);
  16403. /* save the URI part of the From header */
  16404. ast_string_field_set(p, from, of);
  16405. if (parse_uri_legacy_check(of, "sip:,sips:,tel:", &name, &unused_password, &domain, NULL)) {
  16406. ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
  16407. }
  16408. SIP_PEDANTIC_DECODE(name);
  16409. SIP_PEDANTIC_DECODE(domain);
  16410. extract_host_from_hostport(&domain);
  16411. if (ast_strlen_zero(domain)) {
  16412. /* <sip:name@[EMPTY]>, never good */
  16413. ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
  16414. return res;
  16415. }
  16416. if (ast_strlen_zero(name)) {
  16417. /* <sip:[EMPTY][@]hostport>. Asterisk 1.4 and 1.6 have always
  16418. * treated that as a username, so we continue the tradition:
  16419. * uri is now <sip:host@hostport>. */
  16420. name = domain;
  16421. } else {
  16422. /* Non-empty name, try to get caller id from it */
  16423. char *tmp = ast_strdupa(name);
  16424. /* We need to be able to handle from-headers looking like
  16425. <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
  16426. */
  16427. tmp = strsep(&tmp, ";");
  16428. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
  16429. ast_shrink_phone_number(tmp);
  16430. }
  16431. ast_string_field_set(p, cid_num, tmp);
  16432. }
  16433. if (global_match_auth_username) {
  16434. /*
  16435. * XXX This is experimental code to grab the search key from the
  16436. * Auth header's username instead of the 'From' name, if available.
  16437. * Do not enable this block unless you understand the side effects (if any!)
  16438. * Note, the search for "username" should be done in a more robust way.
  16439. * Note2, at the moment we check both fields, though maybe we should
  16440. * pick one or another depending on the request ? XXX
  16441. */
  16442. const char *hdr = sip_get_header(req, "Authorization");
  16443. if (ast_strlen_zero(hdr)) {
  16444. hdr = sip_get_header(req, "Proxy-Authorization");
  16445. }
  16446. if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
  16447. namebuf = name = ast_strdup(hdr + strlen("username=\""));
  16448. name = strsep(&name, "\"");
  16449. }
  16450. }
  16451. res = check_peer_ok(p, name, req, sipmethod, addr,
  16452. authpeer, reliable, calleridname, uri2);
  16453. if (res != AUTH_DONT_KNOW) {
  16454. return res;
  16455. }
  16456. /* Finally, apply the guest policy */
  16457. if (sip_cfg.allowguest) {
  16458. /* Ignore check_return warning from Coverity for get_rpid below. */
  16459. get_rpid(p, req);
  16460. p->rtptimeout = global_rtptimeout;
  16461. p->rtpholdtimeout = global_rtpholdtimeout;
  16462. p->rtpkeepalive = global_rtpkeepalive;
  16463. if (!dialog_initialize_rtp(p)) {
  16464. res = AUTH_SUCCESSFUL;
  16465. } else {
  16466. res = AUTH_RTP_FAILED;
  16467. }
  16468. } else {
  16469. res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
  16470. }
  16471. if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
  16472. ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
  16473. }
  16474. return res;
  16475. }
  16476. /*! \brief Find user
  16477. If we get a match, this will add a reference pointer to the user object, that needs to be unreferenced
  16478. */
  16479. static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
  16480. {
  16481. return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
  16482. }
  16483. static int set_message_vars_from_req(struct ast_msg *msg, struct sip_request *req)
  16484. {
  16485. size_t x;
  16486. char name_buf[1024];
  16487. char val_buf[1024];
  16488. const char *name;
  16489. char *c;
  16490. int res = 0;
  16491. for (x = 0; x < req->headers; x++) {
  16492. const char *header = REQ_OFFSET_TO_STR(req, header[x]);
  16493. if ((c = strchr(header, ':'))) {
  16494. ast_copy_string(name_buf, header, MIN((c - header + 1), sizeof(name_buf)));
  16495. ast_copy_string(val_buf, ast_skip_blanks(c + 1), sizeof(val_buf));
  16496. ast_trim_blanks(name_buf);
  16497. /* Convert header name to full name alias. */
  16498. name = find_full_alias(name_buf, name_buf);
  16499. res = ast_msg_set_var(msg, name, val_buf);
  16500. if (res) {
  16501. break;
  16502. }
  16503. }
  16504. }
  16505. return res;
  16506. }
  16507. /*! \brief Receive SIP MESSAGE method messages
  16508. \note We only handle messages within current calls currently
  16509. Reference: RFC 3428 */
  16510. static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
  16511. {
  16512. char *buf;
  16513. size_t len;
  16514. struct ast_frame f;
  16515. const char *content_type = sip_get_header(req, "Content-Type");
  16516. struct ast_msg *msg;
  16517. int res;
  16518. char *from;
  16519. char *to;
  16520. char from_name[50];
  16521. char stripped[SIPBUFSIZE];
  16522. enum sip_get_dest_result dest_result;
  16523. if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
  16524. transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
  16525. if (!p->owner) {
  16526. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16527. }
  16528. return;
  16529. }
  16530. if (!(buf = get_content(req))) {
  16531. ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
  16532. transmit_response(p, "500 Internal Server Error", req);
  16533. if (!p->owner) {
  16534. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16535. }
  16536. return;
  16537. }
  16538. /* Strip trailing line feeds from message body. (get_content may add
  16539. * a trailing linefeed and we don't need any at the end) */
  16540. len = strlen(buf);
  16541. while (len > 0) {
  16542. if (buf[--len] != '\n') {
  16543. ++len;
  16544. break;
  16545. }
  16546. }
  16547. buf[len] = '\0';
  16548. if (p->owner) {
  16549. if (sip_debug_test_pvt(p)) {
  16550. ast_verbose("SIP Text message received: '%s'\n", buf);
  16551. }
  16552. memset(&f, 0, sizeof(f));
  16553. f.frametype = AST_FRAME_TEXT;
  16554. f.subclass.integer = 0;
  16555. f.offset = 0;
  16556. f.data.ptr = buf;
  16557. f.datalen = strlen(buf) + 1;
  16558. ast_queue_frame(p->owner, &f);
  16559. transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
  16560. return;
  16561. }
  16562. /*
  16563. * At this point MESSAGE is outside of a call.
  16564. *
  16565. * NOTE: p->owner is NULL so no additional check is needed after
  16566. * this point.
  16567. */
  16568. if (!sip_cfg.accept_outofcall_message) {
  16569. /* Message outside of a call, we do not support that */
  16570. ast_debug(1, "MESSAGE outside of a call administratively disabled.\n");
  16571. transmit_response(p, "405 Method Not Allowed", req);
  16572. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16573. return;
  16574. }
  16575. copy_request(&p->initreq, req);
  16576. if (sip_cfg.auth_message_requests) {
  16577. int res;
  16578. set_pvt_allowed_methods(p, req);
  16579. res = check_user(p, req, SIP_MESSAGE, e, XMIT_UNRELIABLE, addr);
  16580. if (res == AUTH_CHALLENGE_SENT) {
  16581. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16582. return;
  16583. }
  16584. if (res < 0) { /* Something failed in authentication */
  16585. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
  16586. transmit_response(p, "403 Forbidden", req);
  16587. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16588. return;
  16589. }
  16590. /* Auth was successful. Proceed. */
  16591. } else {
  16592. struct sip_peer *peer;
  16593. /*
  16594. * MESSAGE outside of a call, not authenticating it.
  16595. * Check to see if we match a peer anyway so that we can direct
  16596. * it to the right context.
  16597. */
  16598. peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, 0, p->socket.type);
  16599. if (peer) {
  16600. /* Only if no auth is required. */
  16601. if (ast_strlen_zero(peer->secret) && ast_strlen_zero(peer->md5secret)) {
  16602. ast_string_field_set(p, context, peer->context);
  16603. }
  16604. if (!ast_strlen_zero(peer->messagecontext)) {
  16605. ast_string_field_set(p, messagecontext, peer->messagecontext);
  16606. }
  16607. ast_string_field_set(p, peername, peer->name);
  16608. peer = sip_unref_peer(peer, "from sip_find_peer() in receive_message");
  16609. }
  16610. }
  16611. /* Override the context with the message context _BEFORE_
  16612. * getting the destination. This way we can guarantee the correct
  16613. * extension is used in the message context when it is present. */
  16614. if (!ast_strlen_zero(p->messagecontext)) {
  16615. ast_string_field_set(p, context, p->messagecontext);
  16616. } else if (!ast_strlen_zero(sip_cfg.messagecontext)) {
  16617. ast_string_field_set(p, context, sip_cfg.messagecontext);
  16618. }
  16619. dest_result = get_destination(p, NULL, NULL);
  16620. switch (dest_result) {
  16621. case SIP_GET_DEST_REFUSED:
  16622. /* Okay to send 403 since this is after auth processing */
  16623. transmit_response(p, "403 Forbidden", req);
  16624. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16625. return;
  16626. case SIP_GET_DEST_INVALID_URI:
  16627. transmit_response(p, "416 Unsupported URI Scheme", req);
  16628. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16629. return;
  16630. default:
  16631. /* We may have something other than dialplan who wants
  16632. * the message, so defer further error handling for now */
  16633. break;
  16634. }
  16635. if (!(msg = ast_msg_alloc())) {
  16636. transmit_response(p, "500 Internal Server Error", req);
  16637. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16638. return;
  16639. }
  16640. to = ast_strdupa(REQ_OFFSET_TO_STR(req, rlpart2));
  16641. from = ast_strdupa(sip_get_header(req, "From"));
  16642. res = ast_msg_set_to(msg, "%s", to);
  16643. /* Build "display" <uri> for from string. */
  16644. from = (char *) get_calleridname(from, from_name, sizeof(from_name));
  16645. from = get_in_brackets(from);
  16646. if (from_name[0]) {
  16647. char from_buf[128];
  16648. ast_escape_quoted(from_name, from_buf, sizeof(from_buf));
  16649. res |= ast_msg_set_from(msg, "\"%s\" <%s>", from_buf, from);
  16650. } else {
  16651. res |= ast_msg_set_from(msg, "<%s>", from);
  16652. }
  16653. res |= ast_msg_set_body(msg, "%s", buf);
  16654. res |= ast_msg_set_context(msg, "%s", p->context);
  16655. res |= ast_msg_set_var(msg, "SIP_RECVADDR", ast_sockaddr_stringify(&p->recv));
  16656. res |= ast_msg_set_tech(msg, "%s", "SIP");
  16657. if (!ast_strlen_zero(p->peername)) {
  16658. res |= ast_msg_set_endpoint(msg, "%s", p->peername);
  16659. res |= ast_msg_set_var(msg, "SIP_PEERNAME", p->peername);
  16660. }
  16661. ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
  16662. res |= ast_msg_set_var(msg, "SIP_FULLCONTACT", get_in_brackets(stripped));
  16663. res |= ast_msg_set_exten(msg, "%s", p->exten);
  16664. res |= set_message_vars_from_req(msg, req);
  16665. if (res) {
  16666. ast_msg_destroy(msg);
  16667. transmit_response(p, "500 Internal Server Error", req);
  16668. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16669. return;
  16670. }
  16671. if (ast_msg_has_destination(msg)) {
  16672. ast_msg_queue(msg);
  16673. transmit_response(p, "202 Accepted", req);
  16674. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16675. return;
  16676. }
  16677. /* Find a specific error cause to send */
  16678. switch (dest_result) {
  16679. case SIP_GET_DEST_EXTEN_NOT_FOUND:
  16680. case SIP_GET_DEST_EXTEN_MATCHMORE:
  16681. transmit_response(p, "404 Not Found", req);
  16682. break;
  16683. case SIP_GET_DEST_EXTEN_FOUND:
  16684. default:
  16685. /* We should have sent the message already! */
  16686. ast_assert(0);
  16687. transmit_response(p, "500 Internal Server Error", req);
  16688. break;
  16689. }
  16690. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  16691. ast_msg_destroy(msg);
  16692. }
  16693. /*! \brief CLI Command to show calls within limits set by call_limit */
  16694. static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16695. {
  16696. #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
  16697. #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
  16698. char ilimits[40];
  16699. char iused[40];
  16700. int showall = FALSE;
  16701. struct ao2_iterator i;
  16702. struct sip_peer *peer;
  16703. switch (cmd) {
  16704. case CLI_INIT:
  16705. e->command = "sip show inuse";
  16706. e->usage =
  16707. "Usage: sip show inuse [all]\n"
  16708. " List all SIP devices usage counters and limits.\n"
  16709. " Add option \"all\" to show all devices, not only those with a limit.\n";
  16710. return NULL;
  16711. case CLI_GENERATE:
  16712. return NULL;
  16713. }
  16714. if (a->argc < 3)
  16715. return CLI_SHOWUSAGE;
  16716. if (a->argc == 4 && !strcmp(a->argv[3], "all"))
  16717. showall = TRUE;
  16718. ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
  16719. i = ao2_iterator_init(peers, 0);
  16720. while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
  16721. ao2_lock(peer);
  16722. if (peer->call_limit)
  16723. snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
  16724. else
  16725. ast_copy_string(ilimits, "N/A", sizeof(ilimits));
  16726. snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inuse, peer->ringing, peer->onhold);
  16727. if (showall || peer->call_limit)
  16728. ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
  16729. ao2_unlock(peer);
  16730. sip_unref_peer(peer, "toss iterator pointer");
  16731. }
  16732. ao2_iterator_destroy(&i);
  16733. return CLI_SUCCESS;
  16734. #undef FORMAT
  16735. #undef FORMAT2
  16736. }
  16737. /*! \brief Convert transfer mode to text string */
  16738. static char *transfermode2str(enum transfermodes mode)
  16739. {
  16740. if (mode == TRANSFER_OPENFORALL)
  16741. return "open";
  16742. else if (mode == TRANSFER_CLOSED)
  16743. return "closed";
  16744. return "strict";
  16745. }
  16746. /*! \brief Report Peer status in character string
  16747. * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
  16748. */
  16749. /* Session-Timer Modes */
  16750. static const struct _map_x_s stmodes[] = {
  16751. { SESSION_TIMER_MODE_ACCEPT, "Accept"},
  16752. { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
  16753. { SESSION_TIMER_MODE_REFUSE, "Refuse"},
  16754. { -1, NULL},
  16755. };
  16756. static const char *stmode2str(enum st_mode m)
  16757. {
  16758. return map_x_s(stmodes, m, "Unknown");
  16759. }
  16760. static enum st_mode str2stmode(const char *s)
  16761. {
  16762. return map_s_x(stmodes, s, -1);
  16763. }
  16764. /* Session-Timer Refreshers */
  16765. static const struct _map_x_s strefresher_params[] = {
  16766. { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
  16767. { SESSION_TIMER_REFRESHER_PARAM_UAC, "uac" },
  16768. { SESSION_TIMER_REFRESHER_PARAM_UAS, "uas" },
  16769. { -1, NULL },
  16770. };
  16771. static const struct _map_x_s strefreshers[] = {
  16772. { SESSION_TIMER_REFRESHER_AUTO, "auto" },
  16773. { SESSION_TIMER_REFRESHER_US, "us" },
  16774. { SESSION_TIMER_REFRESHER_THEM, "them" },
  16775. { -1, NULL },
  16776. };
  16777. static const char *strefresherparam2str(enum st_refresher r)
  16778. {
  16779. return map_x_s(strefresher_params, r, "Unknown");
  16780. }
  16781. static enum st_refresher str2strefresherparam(const char *s)
  16782. {
  16783. return map_s_x(strefresher_params, s, -1);
  16784. }
  16785. /* Autocreatepeer modes */
  16786. static struct _map_x_s autopeermodes[] = {
  16787. { AUTOPEERS_DISABLED, "Off"},
  16788. { AUTOPEERS_VOLATILE, "Volatile"},
  16789. { AUTOPEERS_PERSIST, "Persisted"},
  16790. { -1, NULL},
  16791. };
  16792. static const char *strefresher2str(enum st_refresher r)
  16793. {
  16794. return map_x_s(strefreshers, r, "Unknown");
  16795. }
  16796. static const char *autocreatepeer2str(enum autocreatepeer_mode r)
  16797. {
  16798. return map_x_s(autopeermodes, r, "Unknown");
  16799. }
  16800. static int peer_status(struct sip_peer *peer, char *status, int statuslen)
  16801. {
  16802. int res = 0;
  16803. if (peer->maxms) {
  16804. if (peer->lastms < 0) {
  16805. ast_copy_string(status, "UNREACHABLE", statuslen);
  16806. } else if (peer->lastms > peer->maxms) {
  16807. snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
  16808. res = 1;
  16809. } else if (peer->lastms) {
  16810. snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
  16811. res = 1;
  16812. } else {
  16813. ast_copy_string(status, "UNKNOWN", statuslen);
  16814. }
  16815. } else {
  16816. ast_copy_string(status, "Unmonitored", statuslen);
  16817. /* Checking if port is 0 */
  16818. res = -1;
  16819. }
  16820. return res;
  16821. }
  16822. /*! \brief Show active TCP connections */
  16823. static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16824. {
  16825. struct sip_threadinfo *th;
  16826. struct ao2_iterator i;
  16827. #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
  16828. #define FORMAT "%-47.47s %-9.9s %-6.6s\n"
  16829. switch (cmd) {
  16830. case CLI_INIT:
  16831. e->command = "sip show tcp";
  16832. e->usage =
  16833. "Usage: sip show tcp\n"
  16834. " Lists all active TCP/TLS sessions.\n";
  16835. return NULL;
  16836. case CLI_GENERATE:
  16837. return NULL;
  16838. }
  16839. if (a->argc != 3)
  16840. return CLI_SHOWUSAGE;
  16841. ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
  16842. i = ao2_iterator_init(threadt, 0);
  16843. while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
  16844. ast_cli(a->fd, FORMAT,
  16845. ast_sockaddr_stringify(&th->tcptls_session->remote_address),
  16846. sip_get_transport(th->type),
  16847. (th->tcptls_session->client ? "Client" : "Server"));
  16848. ao2_t_ref(th, -1, "decrement ref from iterator");
  16849. }
  16850. ao2_iterator_destroy(&i);
  16851. return CLI_SUCCESS;
  16852. #undef FORMAT
  16853. #undef FORMAT2
  16854. }
  16855. /*! \brief CLI Command 'SIP Show Users' */
  16856. static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16857. {
  16858. regex_t regexbuf;
  16859. int havepattern = FALSE;
  16860. struct ao2_iterator user_iter;
  16861. struct sip_peer *user;
  16862. #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
  16863. switch (cmd) {
  16864. case CLI_INIT:
  16865. e->command = "sip show users";
  16866. e->usage =
  16867. "Usage: sip show users [like <pattern>]\n"
  16868. " Lists all known SIP users.\n"
  16869. " Optional regular expression pattern is used to filter the user list.\n";
  16870. return NULL;
  16871. case CLI_GENERATE:
  16872. return NULL;
  16873. }
  16874. switch (a->argc) {
  16875. case 5:
  16876. if (!strcasecmp(a->argv[3], "like")) {
  16877. if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
  16878. return CLI_SHOWUSAGE;
  16879. havepattern = TRUE;
  16880. } else
  16881. return CLI_SHOWUSAGE;
  16882. case 3:
  16883. break;
  16884. default:
  16885. return CLI_SHOWUSAGE;
  16886. }
  16887. ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "Forcerport");
  16888. user_iter = ao2_iterator_init(peers, 0);
  16889. while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
  16890. ao2_lock(user);
  16891. if (!(user->type & SIP_TYPE_USER)) {
  16892. ao2_unlock(user);
  16893. sip_unref_peer(user, "sip show users");
  16894. continue;
  16895. }
  16896. if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
  16897. ao2_unlock(user);
  16898. sip_unref_peer(user, "sip show users");
  16899. continue;
  16900. }
  16901. ast_cli(a->fd, FORMAT, user->name,
  16902. user->secret,
  16903. user->accountcode,
  16904. user->context,
  16905. AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0),
  16906. AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
  16907. ao2_unlock(user);
  16908. sip_unref_peer(user, "sip show users");
  16909. }
  16910. ao2_iterator_destroy(&user_iter);
  16911. if (havepattern)
  16912. regfree(&regexbuf);
  16913. return CLI_SUCCESS;
  16914. #undef FORMAT
  16915. }
  16916. /*! \brief Show SIP registrations in the manager API */
  16917. static int manager_show_registry(struct mansession *s, const struct message *m)
  16918. {
  16919. const char *id = astman_get_header(m, "ActionID");
  16920. char idtext[256] = "";
  16921. int total = 0;
  16922. struct ao2_iterator iter;
  16923. struct sip_registry *iterator;
  16924. if (!ast_strlen_zero(id))
  16925. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  16926. astman_send_listack(s, m, "Registrations will follow", "start");
  16927. iter = ao2_iterator_init(registry_list, 0);
  16928. while ((iterator = ao2_t_iterator_next(&iter, "manager_show_registry iter"))) {
  16929. ao2_lock(iterator);
  16930. astman_append(s,
  16931. "Event: RegistryEntry\r\n"
  16932. "%s"
  16933. "Host: %s\r\n"
  16934. "Port: %d\r\n"
  16935. "Username: %s\r\n"
  16936. "Domain: %s\r\n"
  16937. "DomainPort: %d\r\n"
  16938. "Refresh: %d\r\n"
  16939. "State: %s\r\n"
  16940. "RegistrationTime: %ld\r\n"
  16941. "\r\n",
  16942. idtext,
  16943. iterator->hostname,
  16944. iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
  16945. iterator->username,
  16946. S_OR(iterator->regdomain,iterator->hostname),
  16947. iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
  16948. iterator->refresh,
  16949. regstate2str(iterator->regstate),
  16950. (long) iterator->regtime.tv_sec);
  16951. ao2_unlock(iterator);
  16952. ao2_t_ref(iterator, -1, "manager_show_registry iter");
  16953. total++;
  16954. }
  16955. ao2_iterator_destroy(&iter);
  16956. astman_append(s,
  16957. "Event: RegistrationsComplete\r\n"
  16958. "EventList: Complete\r\n"
  16959. "ListItems: %d\r\n"
  16960. "%s"
  16961. "\r\n", total, idtext);
  16962. return 0;
  16963. }
  16964. /*! \brief Show SIP peers in the manager API */
  16965. /* Inspired from chan_iax2 */
  16966. static int manager_sip_show_peers(struct mansession *s, const struct message *m)
  16967. {
  16968. const char *id = astman_get_header(m, "ActionID");
  16969. const char *a[] = {"sip", "show", "peers"};
  16970. char idtext[256] = "";
  16971. int total = 0;
  16972. if (!ast_strlen_zero(id))
  16973. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  16974. astman_send_listack(s, m, "Peer status list will follow", "start");
  16975. /* List the peers in separate manager events */
  16976. _sip_show_peers(-1, &total, s, m, 3, a);
  16977. /* Send final confirmation */
  16978. astman_append(s,
  16979. "Event: PeerlistComplete\r\n"
  16980. "EventList: Complete\r\n"
  16981. "ListItems: %d\r\n"
  16982. "%s"
  16983. "\r\n", total, idtext);
  16984. return 0;
  16985. }
  16986. /*! \brief CLI Show Peers command */
  16987. static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16988. {
  16989. switch (cmd) {
  16990. case CLI_INIT:
  16991. e->command = "sip show peers";
  16992. e->usage =
  16993. "Usage: sip show peers [like <pattern>]\n"
  16994. " Lists all known SIP peers.\n"
  16995. " Optional regular expression pattern is used to filter the peer list.\n";
  16996. return NULL;
  16997. case CLI_GENERATE:
  16998. return NULL;
  16999. }
  17000. return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
  17001. }
  17002. int peercomparefunc(const void *a, const void *b);
  17003. int peercomparefunc(const void *a, const void *b)
  17004. {
  17005. struct sip_peer **ap = (struct sip_peer **)a;
  17006. struct sip_peer **bp = (struct sip_peer **)b;
  17007. return strcmp((*ap)->name, (*bp)->name);
  17008. }
  17009. /* the last argument is left-aligned, so we don't need a size anyways */
  17010. #define PEERS_FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-10.10s %-3.3s %-8s %-11s %-32.32s %s\n"
  17011. /*! \brief Used in the sip_show_peers functions to pass parameters */
  17012. struct show_peers_context {
  17013. regex_t regexbuf;
  17014. int havepattern;
  17015. char idtext[256];
  17016. int realtimepeers;
  17017. int peers_mon_online;
  17018. int peers_mon_offline;
  17019. int peers_unmon_offline;
  17020. int peers_unmon_online;
  17021. };
  17022. /*! \brief Execute sip show peers command */
  17023. static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
  17024. {
  17025. struct show_peers_context cont = {
  17026. .havepattern = FALSE,
  17027. .idtext = "",
  17028. .peers_mon_online = 0,
  17029. .peers_mon_offline = 0,
  17030. .peers_unmon_online = 0,
  17031. .peers_unmon_offline = 0,
  17032. };
  17033. struct sip_peer *peer;
  17034. struct ao2_iterator* it_peers;
  17035. int total_peers = 0;
  17036. const char *id;
  17037. struct sip_peer **peerarray;
  17038. int k;
  17039. cont.realtimepeers = ast_check_realtime("sippeers");
  17040. if (s) { /* Manager - get ActionID */
  17041. id = astman_get_header(m, "ActionID");
  17042. if (!ast_strlen_zero(id)) {
  17043. snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
  17044. }
  17045. }
  17046. switch (argc) {
  17047. case 5:
  17048. if (!strcasecmp(argv[3], "like")) {
  17049. if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB)) {
  17050. return CLI_SHOWUSAGE;
  17051. }
  17052. cont.havepattern = TRUE;
  17053. } else {
  17054. return CLI_SHOWUSAGE;
  17055. }
  17056. case 3:
  17057. break;
  17058. default:
  17059. return CLI_SHOWUSAGE;
  17060. }
  17061. if (!s) {
  17062. /* Normal list */
  17063. ast_cli(fd, PEERS_FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "Comedia", "ACL", "Port", "Status", "Description", (cont.realtimepeers ? "Realtime" : ""));
  17064. }
  17065. ao2_lock(peers);
  17066. if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
  17067. ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
  17068. ao2_unlock(peers);
  17069. return CLI_FAILURE;
  17070. }
  17071. if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
  17072. ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
  17073. ao2_iterator_destroy(it_peers);
  17074. ao2_unlock(peers);
  17075. return CLI_FAILURE;
  17076. }
  17077. ao2_unlock(peers);
  17078. while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
  17079. ao2_lock(peer);
  17080. if (!(peer->type & SIP_TYPE_PEER)) {
  17081. ao2_unlock(peer);
  17082. sip_unref_peer(peer, "unref peer because it's actually a user");
  17083. continue;
  17084. }
  17085. if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
  17086. ao2_unlock(peer);
  17087. sip_unref_peer(peer, "toss iterator peer ptr before continue");
  17088. continue;
  17089. }
  17090. peerarray[total_peers++] = peer;
  17091. ao2_unlock(peer);
  17092. }
  17093. ao2_iterator_destroy(it_peers);
  17094. qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
  17095. for(k = 0; k < total_peers; k++) {
  17096. peerarray[k] = _sip_show_peers_one(fd, s, &cont, peerarray[k]);
  17097. }
  17098. if (!s) {
  17099. ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
  17100. total_peers, cont.peers_mon_online, cont.peers_mon_offline, cont.peers_unmon_online, cont.peers_unmon_offline);
  17101. }
  17102. if (cont.havepattern) {
  17103. regfree(&cont.regexbuf);
  17104. }
  17105. if (total) {
  17106. *total = total_peers;
  17107. }
  17108. ast_free(peerarray);
  17109. return CLI_SUCCESS;
  17110. }
  17111. /*! \brief Emit informations for one peer during sip show peers command */
  17112. static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer)
  17113. {
  17114. /* _sip_show_peers_one() is separated from _sip_show_peers() to properly free the ast_strdupa
  17115. * (this is executed in a loop in _sip_show_peers() )
  17116. */
  17117. char name[256];
  17118. char status[20] = "";
  17119. char pstatus;
  17120. /*
  17121. * tmp_port and tmp_host store copies of ast_sockaddr_stringify strings since the
  17122. * string pointers for that function aren't valid between subsequent calls to
  17123. * ast_sockaddr_stringify functions
  17124. */
  17125. char *tmp_port;
  17126. char *tmp_host;
  17127. tmp_port = ast_sockaddr_isnull(&peer->addr) ?
  17128. "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
  17129. tmp_host = ast_sockaddr_isnull(&peer->addr) ?
  17130. "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
  17131. ao2_lock(peer);
  17132. if (cont->havepattern && regexec(&cont->regexbuf, peer->name, 0, NULL, 0)) {
  17133. ao2_unlock(peer);
  17134. return sip_unref_peer(peer, "toss iterator peer ptr no match");
  17135. }
  17136. if (!ast_strlen_zero(peer->username) && !s) {
  17137. snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
  17138. } else {
  17139. ast_copy_string(name, peer->name, sizeof(name));
  17140. }
  17141. pstatus = peer_status(peer, status, sizeof(status));
  17142. if (pstatus == 1) {
  17143. cont->peers_mon_online++;
  17144. } else if (pstatus == 0) {
  17145. cont->peers_mon_offline++;
  17146. } else {
  17147. if (ast_sockaddr_isnull(&peer->addr) ||
  17148. !ast_sockaddr_port(&peer->addr)) {
  17149. cont->peers_unmon_offline++;
  17150. } else {
  17151. cont->peers_unmon_online++;
  17152. }
  17153. }
  17154. if (!s) { /* Normal CLI list */
  17155. ast_cli(fd, PEERS_FORMAT2, name,
  17156. tmp_host,
  17157. peer->host_dynamic ? " D " : " ", /* Dynamic or not? */
  17158. force_rport_string(peer->flags),
  17159. comedia_string(peer->flags),
  17160. (!ast_acl_list_is_empty(peer->acl)) ? " A " : " ", /* permit/deny */
  17161. tmp_port, status,
  17162. peer->description ? peer->description : "",
  17163. cont->realtimepeers ? (peer->is_realtime ? "Cached RT" : "") : "");
  17164. } else { /* Manager format */
  17165. /* The names here need to be the same as other channels */
  17166. astman_append(s,
  17167. "Event: PeerEntry\r\n%s"
  17168. "Channeltype: SIP\r\n"
  17169. "ObjectName: %s\r\n"
  17170. "ChanObjectType: peer\r\n" /* "peer" or "user" */
  17171. "IPaddress: %s\r\n"
  17172. "IPport: %s\r\n"
  17173. "Dynamic: %s\r\n"
  17174. "AutoForcerport: %s\r\n"
  17175. "Forcerport: %s\r\n"
  17176. "AutoComedia: %s\r\n"
  17177. "Comedia: %s\r\n"
  17178. "VideoSupport: %s\r\n"
  17179. "TextSupport: %s\r\n"
  17180. "ACL: %s\r\n"
  17181. "Status: %s\r\n"
  17182. "RealtimeDevice: %s\r\n"
  17183. "Description: %s\r\n\r\n",
  17184. cont->idtext,
  17185. peer->name,
  17186. ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
  17187. ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
  17188. peer->host_dynamic ? "yes" : "no", /* Dynamic or not? */
  17189. ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ? "yes" : "no",
  17190. ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
  17191. ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ? "yes" : "no",
  17192. ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "yes" : "no",
  17193. ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
  17194. ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no", /* TEXTSUPPORT=yes? */
  17195. ast_acl_list_is_empty(peer->acl) ? "no" : "yes", /* permit/deny/acl */
  17196. status,
  17197. cont->realtimepeers ? (peer->is_realtime ? "yes" : "no") : "no",
  17198. peer->description);
  17199. }
  17200. ao2_unlock(peer);
  17201. return sip_unref_peer(peer, "toss iterator peer ptr");
  17202. }
  17203. #undef PEERS_FORMAT2
  17204. static int peer_dump_func(void *userobj, void *arg, int flags)
  17205. {
  17206. struct sip_peer *peer = userobj;
  17207. int refc = ao2_t_ref(userobj, 0, "");
  17208. struct ast_cli_args *a = (struct ast_cli_args *) arg;
  17209. ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
  17210. peer->name, 0, refc);
  17211. return 0;
  17212. }
  17213. static int dialog_dump_func(void *userobj, void *arg, int flags)
  17214. {
  17215. struct sip_pvt *pvt = userobj;
  17216. int refc = ao2_t_ref(userobj, 0, "");
  17217. struct ast_cli_args *a = (struct ast_cli_args *) arg;
  17218. ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
  17219. pvt->callid, 0, refc);
  17220. return 0;
  17221. }
  17222. /*! \brief List all allocated SIP Objects (realtime or static) */
  17223. static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17224. {
  17225. struct sip_registry *reg;
  17226. struct ao2_iterator iter;
  17227. switch (cmd) {
  17228. case CLI_INIT:
  17229. e->command = "sip show objects";
  17230. e->usage =
  17231. "Usage: sip show objects\n"
  17232. " Lists status of known SIP objects\n";
  17233. return NULL;
  17234. case CLI_GENERATE:
  17235. return NULL;
  17236. }
  17237. if (a->argc != 3)
  17238. return CLI_SHOWUSAGE;
  17239. ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
  17240. ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
  17241. ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
  17242. ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
  17243. iter = ao2_iterator_init(registry_list, 0);
  17244. ast_cli(a->fd, "-= Registry objects: %d =-\n\n", ao2_container_count(registry_list));
  17245. while ((reg = ao2_t_iterator_next(&iter, "sip_show_objects iter"))) {
  17246. ao2_lock(reg);
  17247. ast_cli(a->fd, "name: %s\n", reg->configvalue);
  17248. ao2_unlock(reg);
  17249. ao2_t_ref(reg, -1, "sip_show_objects iter");
  17250. }
  17251. ao2_iterator_destroy(&iter);
  17252. ast_cli(a->fd, "-= Dialog objects:\n\n");
  17253. ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
  17254. return CLI_SUCCESS;
  17255. }
  17256. /*! \brief Print call group and pickup group */
  17257. static void print_group(int fd, ast_group_t group, int crlf)
  17258. {
  17259. char buf[256];
  17260. ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
  17261. }
  17262. /*! \brief Print named call groups and pickup groups */
  17263. static void print_named_groups(int fd, struct ast_namedgroups *group, int crlf)
  17264. {
  17265. struct ast_str *buf = ast_str_create(1024);
  17266. if (buf) {
  17267. ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_namedgroups(&buf, group) );
  17268. ast_free(buf);
  17269. }
  17270. }
  17271. /*! \brief mapping between dtmf flags and strings */
  17272. static const struct _map_x_s dtmfstr[] = {
  17273. { SIP_DTMF_RFC2833, "rfc2833" },
  17274. { SIP_DTMF_INFO, "info" },
  17275. { SIP_DTMF_SHORTINFO, "shortinfo" },
  17276. { SIP_DTMF_INBAND, "inband" },
  17277. { SIP_DTMF_AUTO, "auto" },
  17278. { -1, NULL }, /* terminator */
  17279. };
  17280. /*! \brief Convert DTMF mode to printable string */
  17281. static const char *dtmfmode2str(int mode)
  17282. {
  17283. return map_x_s(dtmfstr, mode, "<error>");
  17284. }
  17285. /*! \brief maps a string to dtmfmode, returns -1 on error */
  17286. static int str2dtmfmode(const char *str)
  17287. {
  17288. return map_s_x(dtmfstr, str, -1);
  17289. }
  17290. static const struct _map_x_s insecurestr[] = {
  17291. { SIP_INSECURE_PORT, "port" },
  17292. { SIP_INSECURE_INVITE, "invite" },
  17293. { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
  17294. { 0, "no" },
  17295. { -1, NULL }, /* terminator */
  17296. };
  17297. /*! \brief Convert Insecure setting to printable string */
  17298. static const char *insecure2str(int mode)
  17299. {
  17300. return map_x_s(insecurestr, mode, "<error>");
  17301. }
  17302. static const struct _map_x_s allowoverlapstr[] = {
  17303. { SIP_PAGE2_ALLOWOVERLAP_YES, "Yes" },
  17304. { SIP_PAGE2_ALLOWOVERLAP_DTMF, "DTMF" },
  17305. { SIP_PAGE2_ALLOWOVERLAP_NO, "No" },
  17306. { -1, NULL }, /* terminator */
  17307. };
  17308. /*! \brief Convert AllowOverlap setting to printable string */
  17309. static const char *allowoverlap2str(int mode)
  17310. {
  17311. return map_x_s(allowoverlapstr, mode, "<error>");
  17312. }
  17313. static const struct _map_x_s trust_id_outboundstr[] = {
  17314. { SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY, "Legacy" },
  17315. { SIP_PAGE2_TRUST_ID_OUTBOUND_NO, "No" },
  17316. { SIP_PAGE2_TRUST_ID_OUTBOUND_YES, "Yes" },
  17317. { -1, NULL }, /* terminator */
  17318. };
  17319. static const char *trust_id_outbound2str(int mode)
  17320. {
  17321. return map_x_s(trust_id_outboundstr, mode, "<error>");
  17322. }
  17323. /*! \brief Destroy disused contexts between reloads
  17324. Only used in reload_config so the code for regcontext doesn't get ugly
  17325. */
  17326. static void cleanup_stale_contexts(char *new, char *old)
  17327. {
  17328. char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
  17329. while ((oldcontext = strsep(&old, "&"))) {
  17330. stalecontext = '\0';
  17331. ast_copy_string(newlist, new, sizeof(newlist));
  17332. stringp = newlist;
  17333. while ((newcontext = strsep(&stringp, "&"))) {
  17334. if (!strcmp(newcontext, oldcontext)) {
  17335. /* This is not the context you're looking for */
  17336. stalecontext = '\0';
  17337. break;
  17338. } else if (strcmp(newcontext, oldcontext)) {
  17339. stalecontext = oldcontext;
  17340. }
  17341. }
  17342. if (stalecontext)
  17343. ast_context_destroy(ast_context_find(stalecontext), "SIP");
  17344. }
  17345. }
  17346. /*!
  17347. * \brief Check RTP Timeout on dialogs
  17348. *
  17349. * \details This is used with ao2_callback to check rtptimeout
  17350. * rtponholdtimeout and send rtpkeepalive packets.
  17351. *
  17352. * \return CMP_MATCH for items to be unlinked from dialogs_rtpcheck.
  17353. */
  17354. static int dialog_checkrtp_cb(void *dialogobj, void *arg, int flags)
  17355. {
  17356. struct sip_pvt *dialog = dialogobj;
  17357. time_t *t = arg;
  17358. int match_status;
  17359. if (sip_pvt_trylock(dialog)) {
  17360. return 0;
  17361. }
  17362. if (dialog->rtp || dialog->vrtp) {
  17363. match_status = check_rtp_timeout(dialog, *t);
  17364. } else {
  17365. /* Dialog has no active RTP or VRTP. unlink it from dialogs_rtpcheck. */
  17366. match_status = CMP_MATCH;
  17367. }
  17368. sip_pvt_unlock(dialog);
  17369. return match_status;
  17370. }
  17371. /*!
  17372. * \brief Match dialogs that need to be destroyed
  17373. *
  17374. * \details This is used with ao2_callback to unlink/delete all dialogs that
  17375. * are marked needdestroy.
  17376. *
  17377. * \todo Re-work this to improve efficiency. Currently, this function is called
  17378. * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
  17379. * potentially even more often when the scheduler has entries to run.
  17380. */
  17381. static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
  17382. {
  17383. struct sip_pvt *dialog = dialogobj;
  17384. if (sip_pvt_trylock(dialog)) {
  17385. /* Don't block the monitor thread. This function is called often enough
  17386. * that we can wait for the next time around. */
  17387. return 0;
  17388. }
  17389. /* If we have sessions that needs to be destroyed, do it now */
  17390. /* Check if we have outstanding requests not responsed to or an active call
  17391. - if that's the case, wait with destruction */
  17392. if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
  17393. /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
  17394. if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
  17395. ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
  17396. sip_pvt_unlock(dialog);
  17397. return 0;
  17398. }
  17399. if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
  17400. ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
  17401. sip_pvt_unlock(dialog);
  17402. return 0;
  17403. }
  17404. sip_pvt_unlock(dialog);
  17405. /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
  17406. /* the CMP_MATCH will unlink this dialog from the dialog hash table */
  17407. dialog_unlink_all(dialog);
  17408. return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
  17409. }
  17410. sip_pvt_unlock(dialog);
  17411. return 0;
  17412. }
  17413. /*! \brief Remove temporary realtime objects from memory (CLI) */
  17414. /*! \todo XXXX Propably needs an overhaul after removal of the devices */
  17415. static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17416. {
  17417. struct sip_peer *peer, *pi;
  17418. int prunepeer = FALSE;
  17419. int multi = FALSE;
  17420. const char *name = NULL;
  17421. regex_t regexbuf;
  17422. int havepattern = 0;
  17423. struct ao2_iterator i;
  17424. static const char * const choices[] = { "all", "like", NULL };
  17425. char *cmplt;
  17426. if (cmd == CLI_INIT) {
  17427. e->command = "sip prune realtime [peer|all]";
  17428. e->usage =
  17429. "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
  17430. " Prunes object(s) from the cache.\n"
  17431. " Optional regular expression pattern is used to filter the objects.\n";
  17432. return NULL;
  17433. } else if (cmd == CLI_GENERATE) {
  17434. if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
  17435. cmplt = ast_cli_complete(a->word, choices, a->n);
  17436. if (!cmplt)
  17437. cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
  17438. return cmplt;
  17439. }
  17440. if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
  17441. return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
  17442. return NULL;
  17443. }
  17444. switch (a->argc) {
  17445. case 4:
  17446. name = a->argv[3];
  17447. /* we accept a name in position 3, but keywords are not good. */
  17448. if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
  17449. return CLI_SHOWUSAGE;
  17450. prunepeer = TRUE;
  17451. if (!strcasecmp(name, "all")) {
  17452. multi = TRUE;
  17453. name = NULL;
  17454. }
  17455. /* else a single name, already set */
  17456. break;
  17457. case 5:
  17458. /* sip prune realtime {peer|like} name */
  17459. name = a->argv[4];
  17460. if (!strcasecmp(a->argv[3], "peer"))
  17461. prunepeer = TRUE;
  17462. else if (!strcasecmp(a->argv[3], "like")) {
  17463. prunepeer = TRUE;
  17464. multi = TRUE;
  17465. } else
  17466. return CLI_SHOWUSAGE;
  17467. if (!strcasecmp(name, "like"))
  17468. return CLI_SHOWUSAGE;
  17469. if (!multi && !strcasecmp(name, "all")) {
  17470. multi = TRUE;
  17471. name = NULL;
  17472. }
  17473. break;
  17474. case 6:
  17475. name = a->argv[5];
  17476. multi = TRUE;
  17477. /* sip prune realtime {peer} like name */
  17478. if (strcasecmp(a->argv[4], "like"))
  17479. return CLI_SHOWUSAGE;
  17480. if (!strcasecmp(a->argv[3], "peer")) {
  17481. prunepeer = TRUE;
  17482. } else
  17483. return CLI_SHOWUSAGE;
  17484. break;
  17485. default:
  17486. return CLI_SHOWUSAGE;
  17487. }
  17488. if (multi && name) {
  17489. if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
  17490. return CLI_SHOWUSAGE;
  17491. }
  17492. havepattern = 1;
  17493. }
  17494. if (multi) {
  17495. if (prunepeer) {
  17496. int pruned = 0;
  17497. i = ao2_iterator_init(peers, 0);
  17498. while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  17499. ao2_lock(pi);
  17500. if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
  17501. ao2_unlock(pi);
  17502. sip_unref_peer(pi, "toss iterator peer ptr before continue");
  17503. continue;
  17504. };
  17505. if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  17506. pi->the_mark = 1;
  17507. pruned++;
  17508. }
  17509. ao2_unlock(pi);
  17510. sip_unref_peer(pi, "toss iterator peer ptr");
  17511. }
  17512. ao2_iterator_destroy(&i);
  17513. if (pruned) {
  17514. unlink_marked_peers_from_tables();
  17515. ast_cli(a->fd, "%d peers pruned.\n", pruned);
  17516. } else
  17517. ast_cli(a->fd, "No peers found to prune.\n");
  17518. }
  17519. } else {
  17520. if (prunepeer) {
  17521. struct sip_peer tmp;
  17522. ast_copy_string(tmp.name, name, sizeof(tmp.name));
  17523. if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
  17524. if (!ast_sockaddr_isnull(&peer->addr)) {
  17525. ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
  17526. }
  17527. if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  17528. ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
  17529. /* put it back! */
  17530. ao2_t_link(peers, peer, "link peer into peer table");
  17531. if (!ast_sockaddr_isnull(&peer->addr)) {
  17532. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  17533. }
  17534. } else
  17535. ast_cli(a->fd, "Peer '%s' pruned.\n", name);
  17536. sip_unref_peer(peer, "sip_prune_realtime: sip_unref_peer: tossing temp peer ptr");
  17537. } else
  17538. ast_cli(a->fd, "Peer '%s' not found.\n", name);
  17539. }
  17540. }
  17541. if (havepattern) {
  17542. regfree(&regexbuf);
  17543. }
  17544. return CLI_SUCCESS;
  17545. }
  17546. /*! \brief Print domain mode to cli */
  17547. static const char *domain_mode_to_text(const enum domain_mode mode)
  17548. {
  17549. switch (mode) {
  17550. case SIP_DOMAIN_AUTO:
  17551. return "[Automatic]";
  17552. case SIP_DOMAIN_CONFIG:
  17553. return "[Configured]";
  17554. }
  17555. return "";
  17556. }
  17557. /*! \brief CLI command to list local domains */
  17558. static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17559. {
  17560. struct domain *d;
  17561. #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
  17562. switch (cmd) {
  17563. case CLI_INIT:
  17564. e->command = "sip show domains";
  17565. e->usage =
  17566. "Usage: sip show domains\n"
  17567. " Lists all configured SIP local domains.\n"
  17568. " Asterisk only responds to SIP messages to local domains.\n";
  17569. return NULL;
  17570. case CLI_GENERATE:
  17571. return NULL;
  17572. }
  17573. if (AST_LIST_EMPTY(&domain_list)) {
  17574. ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
  17575. return CLI_SUCCESS;
  17576. } else {
  17577. ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
  17578. AST_LIST_LOCK(&domain_list);
  17579. AST_LIST_TRAVERSE(&domain_list, d, list)
  17580. ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
  17581. domain_mode_to_text(d->mode));
  17582. AST_LIST_UNLOCK(&domain_list);
  17583. ast_cli(a->fd, "\n");
  17584. return CLI_SUCCESS;
  17585. }
  17586. }
  17587. #undef FORMAT
  17588. /*! \brief Show SIP peers in the manager API */
  17589. static int manager_sip_show_peer(struct mansession *s, const struct message *m)
  17590. {
  17591. const char *a[4];
  17592. const char *peer;
  17593. peer = astman_get_header(m, "Peer");
  17594. if (ast_strlen_zero(peer)) {
  17595. astman_send_error(s, m, "Peer: <name> missing.");
  17596. return 0;
  17597. }
  17598. a[0] = "sip";
  17599. a[1] = "show";
  17600. a[2] = "peer";
  17601. a[3] = peer;
  17602. _sip_show_peer(1, -1, s, m, 4, a);
  17603. astman_append(s, "\r\n" );
  17604. return 0;
  17605. }
  17606. /*! \brief Show one peer in detail */
  17607. static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17608. {
  17609. switch (cmd) {
  17610. case CLI_INIT:
  17611. e->command = "sip show peer";
  17612. e->usage =
  17613. "Usage: sip show peer <name> [load]\n"
  17614. " Shows all details on one SIP peer and the current status.\n"
  17615. " Option \"load\" forces lookup of peer in realtime storage.\n";
  17616. return NULL;
  17617. case CLI_GENERATE:
  17618. return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
  17619. }
  17620. return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
  17621. }
  17622. static void send_manager_peer_status(struct mansession *s, struct sip_peer *peer, const char *idText)
  17623. {
  17624. char time[128] = "";
  17625. char status[128] = "";
  17626. if (peer->maxms) {
  17627. if (peer->lastms < 0) {
  17628. snprintf(status, sizeof(status), "PeerStatus: Unreachable\r\n");
  17629. } else if (peer->lastms > peer->maxms) {
  17630. snprintf(status, sizeof(status), "PeerStatus: Lagged\r\n");
  17631. snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
  17632. } else if (peer->lastms) {
  17633. snprintf(status, sizeof(status), "PeerStatus: Reachable\r\n");
  17634. snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
  17635. } else {
  17636. snprintf(status, sizeof(status), "PeerStatus: Unknown\r\n");
  17637. }
  17638. } else {
  17639. snprintf(status, sizeof(status), "PeerStatus: Unmonitored\r\n");
  17640. }
  17641. astman_append(s,
  17642. "Event: PeerStatus\r\n"
  17643. "Privilege: System\r\n"
  17644. "ChannelType: SIP\r\n"
  17645. "Peer: SIP/%s\r\n"
  17646. "%s"
  17647. "%s"
  17648. "%s"
  17649. "\r\n",
  17650. peer->name, status, time, idText);
  17651. }
  17652. /*! \brief Show SIP peers in the manager API */
  17653. static int manager_sip_peer_status(struct mansession *s, const struct message *m)
  17654. {
  17655. const char *id = astman_get_header(m,"ActionID");
  17656. const char *peer_name = astman_get_header(m,"Peer");
  17657. char idText[256] = "";
  17658. struct sip_peer *peer = NULL;
  17659. if (!ast_strlen_zero(id)) {
  17660. snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
  17661. }
  17662. if (!ast_strlen_zero(peer_name)) {
  17663. /* strip SIP/ from the begining of the peer name */
  17664. if (strlen(peer_name) >= 4 && !strncasecmp("SIP/", peer_name, 4)) {
  17665. peer_name += 4;
  17666. }
  17667. peer = sip_find_peer(peer_name, NULL, TRUE, FINDPEERS, FALSE, 0);
  17668. if (!peer) {
  17669. astman_send_error(s, m, "No such peer");
  17670. return 0;
  17671. }
  17672. }
  17673. astman_send_ack(s, m, "Peer status will follow");
  17674. if (!peer) {
  17675. struct ao2_iterator i = ao2_iterator_init(peers, 0);
  17676. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table for SIPpeerstatus"))) {
  17677. ao2_lock(peer);
  17678. send_manager_peer_status(s, peer, idText);
  17679. ao2_unlock(peer);
  17680. sip_unref_peer(peer, "unref peer for SIPpeerstatus");
  17681. }
  17682. ao2_iterator_destroy(&i);
  17683. } else {
  17684. ao2_lock(peer);
  17685. send_manager_peer_status(s, peer, idText);
  17686. ao2_unlock(peer);
  17687. sip_unref_peer(peer, "unref peer for SIPpeerstatus");
  17688. }
  17689. astman_append(s,
  17690. "Event: SIPpeerstatusComplete\r\n"
  17691. "%s"
  17692. "\r\n",
  17693. idText);
  17694. return 0;
  17695. }
  17696. static void publish_qualify_peer_done(const char *id, const char *peer)
  17697. {
  17698. RAII_VAR(struct ast_json *, body, NULL, ast_json_unref);
  17699. if (ast_strlen_zero(id)) {
  17700. body = ast_json_pack("{s: s}", "Peer", peer);
  17701. } else {
  17702. body = ast_json_pack("{s: s, s: s}", "Peer", peer, "ActionID", id);
  17703. }
  17704. if (!body) {
  17705. return;
  17706. }
  17707. ast_manager_publish_event("SIPQualifyPeerDone", EVENT_FLAG_CALL, body);
  17708. }
  17709. /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
  17710. static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
  17711. {
  17712. struct sip_peer *peer;
  17713. int load_realtime;
  17714. if (argc < 4)
  17715. return CLI_SHOWUSAGE;
  17716. load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
  17717. if ((peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
  17718. const char *id = astman_get_header(m,"ActionID");
  17719. if (type != 0) {
  17720. astman_send_ack(s, m, "SIP peer found - will qualify");
  17721. }
  17722. sip_poke_peer(peer, 1);
  17723. publish_qualify_peer_done(id, argv[3]);
  17724. sip_unref_peer(peer, "qualify: done with peer");
  17725. } else if (type == 0) {
  17726. ast_cli(fd, "Peer '%s' not found\n", argv[3]);
  17727. } else {
  17728. astman_send_error(s, m, "Peer not found");
  17729. }
  17730. return CLI_SUCCESS;
  17731. }
  17732. /*! \brief Qualify SIP peers in the manager API */
  17733. static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
  17734. {
  17735. const char *a[4];
  17736. const char *peer;
  17737. peer = astman_get_header(m, "Peer");
  17738. if (ast_strlen_zero(peer)) {
  17739. astman_send_error(s, m, "Peer: <name> missing.");
  17740. return 0;
  17741. }
  17742. a[0] = "sip";
  17743. a[1] = "qualify";
  17744. a[2] = "peer";
  17745. a[3] = peer;
  17746. _sip_qualify_peer(1, -1, s, m, 4, a);
  17747. return 0;
  17748. }
  17749. /*! \brief Send an OPTIONS packet to a SIP peer */
  17750. static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17751. {
  17752. switch (cmd) {
  17753. case CLI_INIT:
  17754. e->command = "sip qualify peer";
  17755. e->usage =
  17756. "Usage: sip qualify peer <name> [load]\n"
  17757. " Requests a response from one SIP peer and the current status.\n"
  17758. " Option \"load\" forces lookup of peer in realtime storage.\n";
  17759. return NULL;
  17760. case CLI_GENERATE:
  17761. return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
  17762. }
  17763. return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
  17764. }
  17765. /*! \brief list peer mailboxes to CLI */
  17766. static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
  17767. {
  17768. struct sip_mailbox *mailbox;
  17769. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  17770. ast_str_append(mailbox_str, 0, "%s%s",
  17771. mailbox->id,
  17772. AST_LIST_NEXT(mailbox, entry) ? "," : "");
  17773. }
  17774. }
  17775. static struct _map_x_s faxecmodes[] = {
  17776. { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
  17777. { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
  17778. { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
  17779. { -1, NULL},
  17780. };
  17781. static const char *faxec2str(int faxec)
  17782. {
  17783. return map_x_s(faxecmodes, faxec, "Unknown");
  17784. }
  17785. /*! \brief Show one peer in detail (main function) */
  17786. static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
  17787. {
  17788. char status[30] = "";
  17789. char cbuf[256];
  17790. struct sip_peer *peer;
  17791. struct ast_str *codec_buf = ast_str_alloca(64);
  17792. struct ast_variable *v;
  17793. int x = 0, load_realtime;
  17794. int realtimepeers;
  17795. realtimepeers = ast_check_realtime("sippeers");
  17796. if (argc < 4)
  17797. return CLI_SHOWUSAGE;
  17798. load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
  17799. peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
  17800. if (s) { /* Manager */
  17801. if (peer) {
  17802. const char *id = astman_get_header(m, "ActionID");
  17803. astman_append(s, "Response: Success\r\n");
  17804. if (!ast_strlen_zero(id))
  17805. astman_append(s, "ActionID: %s\r\n", id);
  17806. } else {
  17807. snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
  17808. astman_send_error(s, m, cbuf);
  17809. return CLI_SUCCESS;
  17810. }
  17811. }
  17812. if (peer && type==0 ) { /* Normal listing */
  17813. struct ast_str *mailbox_str = ast_str_alloca(512);
  17814. struct ast_str *path;
  17815. struct sip_auth_container *credentials;
  17816. ao2_lock(peer);
  17817. credentials = peer->auth;
  17818. if (credentials) {
  17819. ao2_t_ref(credentials, +1, "Ref peer auth for show");
  17820. }
  17821. ao2_unlock(peer);
  17822. ast_cli(fd, "\n\n");
  17823. ast_cli(fd, " * Name : %s\n", peer->name);
  17824. ast_cli(fd, " Description : %s\n", peer->description);
  17825. if (realtimepeers) { /* Realtime is enabled */
  17826. ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
  17827. }
  17828. ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
  17829. ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
  17830. ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
  17831. if (credentials) {
  17832. struct sip_auth *auth;
  17833. AST_LIST_TRAVERSE(&credentials->list, auth, node) {
  17834. ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s %s\n",
  17835. auth->realm,
  17836. auth->username,
  17837. !ast_strlen_zero(auth->secret)
  17838. ? "<Secret set>"
  17839. : (!ast_strlen_zero(auth->md5secret)
  17840. ? "<MD5secret set>" : "<Not set>"));
  17841. }
  17842. ao2_t_ref(credentials, -1, "Unref peer auth for show");
  17843. }
  17844. ast_cli(fd, " Context : %s\n", peer->context);
  17845. ast_cli(fd, " Record On feature : %s\n", peer->record_on_feature);
  17846. ast_cli(fd, " Record Off feature : %s\n", peer->record_off_feature);
  17847. ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
  17848. ast_cli(fd, " Language : %s\n", peer->language);
  17849. ast_cli(fd, " Tonezone : %s\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
  17850. if (!ast_strlen_zero(peer->accountcode))
  17851. ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
  17852. ast_cli(fd, " AMA flags : %s\n", ast_channel_amaflags2string(peer->amaflags));
  17853. ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
  17854. ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
  17855. if (!ast_strlen_zero(peer->fromuser))
  17856. ast_cli(fd, " FromUser : %s\n", peer->fromuser);
  17857. if (!ast_strlen_zero(peer->fromdomain))
  17858. ast_cli(fd, " FromDomain : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
  17859. ast_cli(fd, " Callgroup : ");
  17860. print_group(fd, peer->callgroup, 0);
  17861. ast_cli(fd, " Pickupgroup : ");
  17862. print_group(fd, peer->pickupgroup, 0);
  17863. ast_cli(fd, " Named Callgr : ");
  17864. print_named_groups(fd, peer->named_callgroups, 0);
  17865. ast_cli(fd, " Nam. Pickupgr: ");
  17866. print_named_groups(fd, peer->named_pickupgroups, 0);
  17867. peer_mailboxes_to_str(&mailbox_str, peer);
  17868. ast_cli(fd, " MOH Suggest : %s\n", peer->mohsuggest);
  17869. ast_cli(fd, " Mailbox : %s\n", ast_str_buffer(mailbox_str));
  17870. ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
  17871. ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
  17872. ast_cli(fd, " Call limit : %d\n", peer->call_limit);
  17873. ast_cli(fd, " Max forwards : %d\n", peer->maxforwards);
  17874. if (peer->busy_level)
  17875. ast_cli(fd, " Busy level : %d\n", peer->busy_level);
  17876. ast_cli(fd, " Dynamic : %s\n", AST_CLI_YESNO(peer->host_dynamic));
  17877. ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
  17878. ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
  17879. ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
  17880. ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
  17881. ast_cli(fd, " Force rport : %s\n", force_rport_string(peer->flags));
  17882. ast_cli(fd, " Symmetric RTP: %s\n", comedia_string(peer->flags));
  17883. ast_cli(fd, " ACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->acl) == 0));
  17884. ast_cli(fd, " DirectMedACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->directmediaacl) == 0));
  17885. ast_cli(fd, " T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
  17886. ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
  17887. ast_cli(fd, " T.38 MaxDtgrm: %u\n", peer->t38_maxdatagram);
  17888. ast_cli(fd, " DirectMedia : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
  17889. ast_cli(fd, " PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
  17890. ast_cli(fd, " User=Phone : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
  17891. 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)));
  17892. ast_cli(fd, " Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
  17893. ast_cli(fd, " Ign SDP ver : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
  17894. ast_cli(fd, " Trust RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
  17895. ast_cli(fd, " Send RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
  17896. ast_cli(fd, " Path support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEPATH)));
  17897. if ((path = sip_route_list(&peer->path, 1, 0))) {
  17898. ast_cli(fd, " Path : %s\n", ast_str_buffer(path));
  17899. ast_free(path);
  17900. }
  17901. ast_cli(fd, " TrustIDOutbnd: %s\n", trust_id_outbound2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND)));
  17902. ast_cli(fd, " Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
  17903. ast_cli(fd, " Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
  17904. if (peer->outboundproxy)
  17905. ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
  17906. peer->outboundproxy->force ? "(forced)" : "");
  17907. /* - is enumerated */
  17908. ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
  17909. ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
  17910. ast_cli(fd, " Timer B : %d\n", peer->timer_b);
  17911. ast_cli(fd, " ToHost : %s\n", peer->tohost);
  17912. ast_cli(fd, " Addr->IP : %s\n", ast_sockaddr_stringify(&peer->addr));
  17913. ast_cli(fd, " Defaddr->IP : %s\n", ast_sockaddr_stringify(&peer->defaddr));
  17914. ast_cli(fd, " Prim.Transp. : %s\n", sip_get_transport(peer->socket.type));
  17915. ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
  17916. if (!ast_strlen_zero(sip_cfg.regcontext))
  17917. ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
  17918. ast_cli(fd, " Def. Username: %s\n", peer->username);
  17919. ast_cli(fd, " SIP Options : ");
  17920. if (peer->sipoptions) {
  17921. int lastoption = -1;
  17922. for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
  17923. if (sip_options[x].id != lastoption) {
  17924. if (peer->sipoptions & sip_options[x].id)
  17925. ast_cli(fd, "%s ", sip_options[x].text);
  17926. lastoption = x;
  17927. }
  17928. }
  17929. } else
  17930. ast_cli(fd, "(none)");
  17931. ast_cli(fd, "\n");
  17932. ast_cli(fd, " Codecs : %s\n", ast_format_cap_get_names(peer->caps, &codec_buf));
  17933. ast_cli(fd, " Auto-Framing : %s\n", AST_CLI_YESNO(peer->autoframing));
  17934. ast_cli(fd, " Status : ");
  17935. peer_status(peer, status, sizeof(status));
  17936. ast_cli(fd, "%s\n", status);
  17937. ast_cli(fd, " Useragent : %s\n", peer->useragent);
  17938. ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
  17939. ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
  17940. ast_cli(fd, " Keepalive : %d ms\n", peer->keepalive * 1000);
  17941. if (peer->chanvars) {
  17942. ast_cli(fd, " Variables :\n");
  17943. for (v = peer->chanvars ; v ; v = v->next)
  17944. ast_cli(fd, " %s = %s\n", v->name, v->value);
  17945. }
  17946. ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
  17947. ast_cli(fd, " Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
  17948. ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
  17949. ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
  17950. ast_cli(fd, " RTP Engine : %s\n", peer->engine);
  17951. ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
  17952. ast_cli(fd, " Use Reason : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
  17953. ast_cli(fd, " Encryption : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
  17954. ast_cli(fd, "\n");
  17955. peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer ptr");
  17956. } else if (peer && type == 1) { /* manager listing */
  17957. char buffer[256];
  17958. struct ast_str *tmp_str = ast_str_alloca(512);
  17959. astman_append(s, "Channeltype: SIP\r\n");
  17960. astman_append(s, "ObjectName: %s\r\n", peer->name);
  17961. astman_append(s, "ChanObjectType: peer\r\n");
  17962. astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
  17963. astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
  17964. astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
  17965. astman_append(s, "Context: %s\r\n", peer->context);
  17966. if (!ast_strlen_zero(peer->subscribecontext)) {
  17967. astman_append(s, "SubscribeContext: %s\r\n", peer->subscribecontext);
  17968. }
  17969. astman_append(s, "Language: %s\r\n", peer->language);
  17970. astman_append(s, "ToneZone: %s\r\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
  17971. if (!ast_strlen_zero(peer->accountcode))
  17972. astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
  17973. astman_append(s, "AMAflags: %s\r\n", ast_channel_amaflags2string(peer->amaflags));
  17974. astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
  17975. if (!ast_strlen_zero(peer->fromuser))
  17976. astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
  17977. if (!ast_strlen_zero(peer->fromdomain))
  17978. astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
  17979. astman_append(s, "Callgroup: ");
  17980. astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
  17981. astman_append(s, "Pickupgroup: ");
  17982. astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
  17983. astman_append(s, "Named Callgroup: ");
  17984. astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_callgroups));
  17985. ast_str_reset(tmp_str);
  17986. astman_append(s, "Named Pickupgroup: ");
  17987. astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_pickupgroups));
  17988. ast_str_reset(tmp_str);
  17989. astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
  17990. peer_mailboxes_to_str(&tmp_str, peer);
  17991. astman_append(s, "VoiceMailbox: %s\r\n", ast_str_buffer(tmp_str));
  17992. astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
  17993. astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
  17994. astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
  17995. astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
  17996. astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
  17997. astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
  17998. astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
  17999. astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
  18000. astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
  18001. astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
  18002. astman_append(s, "SIP-Forcerport: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
  18003. (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "A" : "a") :
  18004. (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "Y" : "N"));
  18005. astman_append(s, "SIP-Comedia: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ?
  18006. (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "A" : "a") :
  18007. (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "Y" : "N"));
  18008. astman_append(s, "ACL: %s\r\n", (ast_acl_list_is_empty(peer->acl) ? "N" : "Y"));
  18009. astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
  18010. astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
  18011. astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
  18012. astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
  18013. astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
  18014. astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
  18015. astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
  18016. astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
  18017. astman_append(s, "SIP-T.38MaxDtgrm: %u\r\n", peer->t38_maxdatagram);
  18018. astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
  18019. astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
  18020. astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
  18021. astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
  18022. astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
  18023. astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
  18024. /* - is enumerated */
  18025. astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
  18026. astman_append(s, "ToHost: %s\r\n", peer->tohost);
  18027. astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
  18028. 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));
  18029. astman_append(s, "Default-Username: %s\r\n", peer->username);
  18030. if (!ast_strlen_zero(sip_cfg.regcontext))
  18031. astman_append(s, "RegExtension: %s\r\n", peer->regexten);
  18032. astman_append(s, "Codecs: %s\r\n", ast_format_cap_get_names(peer->caps, &codec_buf));
  18033. astman_append(s, "Status: ");
  18034. peer_status(peer, status, sizeof(status));
  18035. astman_append(s, "%s\r\n", status);
  18036. astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
  18037. astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
  18038. astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
  18039. astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
  18040. if (peer->chanvars) {
  18041. for (v = peer->chanvars ; v ; v = v->next) {
  18042. astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
  18043. }
  18044. }
  18045. astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
  18046. astman_append(s, "Description: %s\r\n", peer->description);
  18047. peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer");
  18048. } else {
  18049. ast_cli(fd, "Peer %s not found.\n", argv[3]);
  18050. ast_cli(fd, "\n");
  18051. }
  18052. return CLI_SUCCESS;
  18053. }
  18054. /*! \brief Do completion on user name */
  18055. static char *complete_sip_user(const char *word, int state)
  18056. {
  18057. char *result = NULL;
  18058. int wordlen = strlen(word);
  18059. int which = 0;
  18060. struct ao2_iterator user_iter;
  18061. struct sip_peer *user;
  18062. user_iter = ao2_iterator_init(peers, 0);
  18063. while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
  18064. ao2_lock(user);
  18065. if (!(user->type & SIP_TYPE_USER)) {
  18066. ao2_unlock(user);
  18067. sip_unref_peer(user, "complete sip user");
  18068. continue;
  18069. }
  18070. /* locking of the object is not required because only the name and flags are being compared */
  18071. if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
  18072. result = ast_strdup(user->name);
  18073. }
  18074. ao2_unlock(user);
  18075. sip_unref_peer(user, "complete sip user");
  18076. if (result) {
  18077. break;
  18078. }
  18079. }
  18080. ao2_iterator_destroy(&user_iter);
  18081. return result;
  18082. }
  18083. /*! \brief Support routine for 'sip show user' CLI */
  18084. static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
  18085. {
  18086. if (pos == 3)
  18087. return complete_sip_user(word, state);
  18088. return NULL;
  18089. }
  18090. /*! \brief Show one user in detail */
  18091. static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18092. {
  18093. char cbuf[256];
  18094. struct sip_peer *user;
  18095. struct ast_variable *v;
  18096. int load_realtime;
  18097. switch (cmd) {
  18098. case CLI_INIT:
  18099. e->command = "sip show user";
  18100. e->usage =
  18101. "Usage: sip show user <name> [load]\n"
  18102. " Shows all details on one SIP user and the current status.\n"
  18103. " Option \"load\" forces lookup of peer in realtime storage.\n";
  18104. return NULL;
  18105. case CLI_GENERATE:
  18106. return complete_sip_show_user(a->line, a->word, a->pos, a->n);
  18107. }
  18108. if (a->argc < 4)
  18109. return CLI_SHOWUSAGE;
  18110. /* Load from realtime storage? */
  18111. load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
  18112. if ((user = sip_find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
  18113. ao2_lock(user);
  18114. ast_cli(a->fd, "\n\n");
  18115. ast_cli(a->fd, " * Name : %s\n", user->name);
  18116. ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
  18117. ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
  18118. ast_cli(a->fd, " Context : %s\n", user->context);
  18119. ast_cli(a->fd, " Language : %s\n", user->language);
  18120. if (!ast_strlen_zero(user->accountcode))
  18121. ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
  18122. ast_cli(a->fd, " AMA flags : %s\n", ast_channel_amaflags2string(user->amaflags));
  18123. ast_cli(a->fd, " Tonezone : %s\n", user->zone[0] != '\0' ? user->zone : "<Not set>");
  18124. ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
  18125. ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
  18126. ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
  18127. ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
  18128. ast_cli(a->fd, " Callgroup : ");
  18129. print_group(a->fd, user->callgroup, 0);
  18130. ast_cli(a->fd, " Pickupgroup : ");
  18131. print_group(a->fd, user->pickupgroup, 0);
  18132. ast_cli(a->fd, " Named Callgr : ");
  18133. print_named_groups(a->fd, user->named_callgroups, 0);
  18134. ast_cli(a->fd, " Nam. Pickupgr: ");
  18135. print_named_groups(a->fd, user->named_pickupgroups, 0);
  18136. ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
  18137. ast_cli(a->fd, " ACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0));
  18138. ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
  18139. ast_cli(a->fd, " Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
  18140. ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
  18141. ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
  18142. ast_cli(a->fd, " RTP Engine : %s\n", user->engine);
  18143. ast_cli(a->fd, " Auto-Framing: %s \n", AST_CLI_YESNO(user->autoframing));
  18144. if (user->chanvars) {
  18145. ast_cli(a->fd, " Variables :\n");
  18146. for (v = user->chanvars ; v ; v = v->next)
  18147. ast_cli(a->fd, " %s = %s\n", v->name, v->value);
  18148. }
  18149. ast_cli(a->fd, "\n");
  18150. ao2_unlock(user);
  18151. sip_unref_peer(user, "sip show user");
  18152. } else {
  18153. ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
  18154. ast_cli(a->fd, "\n");
  18155. }
  18156. return CLI_SUCCESS;
  18157. }
  18158. static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18159. {
  18160. struct ast_str *cbuf;
  18161. struct ast_cb_names cbnames = {9, { "retrans_pkt",
  18162. "__sip_autodestruct",
  18163. "expire_register",
  18164. "auto_congest",
  18165. "sip_reg_timeout",
  18166. "sip_poke_peer_s",
  18167. "sip_poke_noanswer",
  18168. "sip_reregister",
  18169. "sip_reinvite_retry"},
  18170. { retrans_pkt,
  18171. __sip_autodestruct,
  18172. expire_register,
  18173. auto_congest,
  18174. sip_reg_timeout,
  18175. sip_poke_peer_s,
  18176. sip_poke_noanswer,
  18177. sip_reregister,
  18178. sip_reinvite_retry}};
  18179. switch (cmd) {
  18180. case CLI_INIT:
  18181. e->command = "sip show sched";
  18182. e->usage =
  18183. "Usage: sip show sched\n"
  18184. " Shows stats on what's in the sched queue at the moment\n";
  18185. return NULL;
  18186. case CLI_GENERATE:
  18187. return NULL;
  18188. }
  18189. cbuf = ast_str_alloca(2048);
  18190. ast_cli(a->fd, "\n");
  18191. ast_sched_report(sched, &cbuf, &cbnames);
  18192. ast_cli(a->fd, "%s", ast_str_buffer(cbuf));
  18193. return CLI_SUCCESS;
  18194. }
  18195. /*! \brief Show SIP Registry (registrations with other SIP proxies */
  18196. static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18197. {
  18198. #define FORMAT2 "%-39.39s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
  18199. #define FORMAT "%-39.39s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
  18200. char host[80];
  18201. char user[80];
  18202. char tmpdat[256];
  18203. struct ast_tm tm;
  18204. int counter = 0;
  18205. struct ao2_iterator iter;
  18206. struct sip_registry *iterator;
  18207. switch (cmd) {
  18208. case CLI_INIT:
  18209. e->command = "sip show registry";
  18210. e->usage =
  18211. "Usage: sip show registry\n"
  18212. " Lists all registration requests and status.\n";
  18213. return NULL;
  18214. case CLI_GENERATE:
  18215. return NULL;
  18216. }
  18217. if (a->argc != 3)
  18218. return CLI_SHOWUSAGE;
  18219. ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
  18220. iter = ao2_iterator_init(registry_list, 0);
  18221. while ((iterator = ao2_t_iterator_next(&iter, "sip_show_registry iter"))) {
  18222. ao2_lock(iterator);
  18223. snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
  18224. snprintf(user, sizeof(user), "%s", iterator->username);
  18225. if (!ast_strlen_zero(iterator->regdomain)) {
  18226. snprintf(tmpdat, sizeof(tmpdat), "%s", user);
  18227. snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
  18228. if (iterator->regdomainport) {
  18229. snprintf(tmpdat, sizeof(tmpdat), "%s", user);
  18230. snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
  18231. if (iterator->regtime.tv_sec) {
  18232. ast_localtime(&iterator->regtime, &tm, NULL);
  18233. ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
  18234. } else
  18235. tmpdat[0] = '\0';
  18236. ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
  18237. ao2_unlock(iterator);
  18238. ao2_t_ref(iterator, -1, "sip_show_registry iter");
  18239. counter++;
  18240. }
  18241. ao2_iterator_destroy(&iter);
  18242. ast_cli(a->fd, "%d SIP registrations.\n", counter);
  18243. return CLI_SUCCESS;
  18244. #undef FORMAT
  18245. #undef FORMAT2
  18246. }
  18247. /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
  18248. \note This function does not tell the SIP device what's going on,
  18249. so use it with great care.
  18250. */
  18251. static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18252. {
  18253. struct sip_peer *peer;
  18254. int load_realtime = 0;
  18255. switch (cmd) {
  18256. case CLI_INIT:
  18257. e->command = "sip unregister";
  18258. e->usage =
  18259. "Usage: sip unregister <peer>\n"
  18260. " Unregister (force expiration) a SIP peer from the registry\n";
  18261. return NULL;
  18262. case CLI_GENERATE:
  18263. return complete_sip_unregister(a->line, a->word, a->pos, a->n);
  18264. }
  18265. if (a->argc != 3)
  18266. return CLI_SHOWUSAGE;
  18267. if ((peer = sip_find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
  18268. if (peer->expire > 0) {
  18269. AST_SCHED_DEL_UNREF(sched, peer->expire,
  18270. sip_unref_peer(peer, "remove register expire ref"));
  18271. expire_register(sip_ref_peer(peer, "ref for expire_register"));
  18272. ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
  18273. } else {
  18274. ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
  18275. }
  18276. sip_unref_peer(peer, "sip_unregister: sip_unref_peer via sip_unregister: done with peer from sip_find_peer call");
  18277. } else {
  18278. ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
  18279. }
  18280. return CLI_SUCCESS;
  18281. }
  18282. /*! \brief Callback for show_chanstats */
  18283. static int show_chanstats_cb(void *__cur, void *__arg, int flags)
  18284. {
  18285. #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
  18286. #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"
  18287. struct sip_pvt *cur = __cur;
  18288. struct ast_rtp_instance_stats stats;
  18289. char durbuf[10];
  18290. struct ast_channel *c;
  18291. struct __show_chan_arg *arg = __arg;
  18292. int fd = arg->fd;
  18293. sip_pvt_lock(cur);
  18294. c = cur->owner;
  18295. if (cur->subscribed != NONE) {
  18296. /* Subscriptions */
  18297. sip_pvt_unlock(cur);
  18298. return 0; /* don't care, we scan all channels */
  18299. }
  18300. if (!cur->rtp) {
  18301. if (sipdebug) {
  18302. ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n",
  18303. ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
  18304. invitestate2string[cur->invitestate].desc,
  18305. "-- No RTP active");
  18306. }
  18307. sip_pvt_unlock(cur);
  18308. return 0; /* don't care, we scan all channels */
  18309. }
  18310. if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
  18311. sip_pvt_unlock(cur);
  18312. ast_log(LOG_WARNING, "Could not get RTP stats.\n");
  18313. return 0;
  18314. }
  18315. if (c) {
  18316. ast_format_duration_hh_mm_ss(ast_channel_get_duration(c), durbuf, sizeof(durbuf));
  18317. } else {
  18318. durbuf[0] = '\0';
  18319. }
  18320. ast_cli(fd, FORMAT,
  18321. ast_sockaddr_stringify_addr(&cur->sa),
  18322. cur->callid,
  18323. durbuf,
  18324. stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
  18325. stats.rxcount > (unsigned int) 100000 ? "K":" ",
  18326. stats.rxploss,
  18327. (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
  18328. stats.rxjitter,
  18329. stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
  18330. stats.txcount > (unsigned int) 100000 ? "K":" ",
  18331. stats.txploss,
  18332. stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
  18333. stats.txjitter
  18334. );
  18335. arg->numchans++;
  18336. sip_pvt_unlock(cur);
  18337. return 0; /* don't care, we scan all channels */
  18338. }
  18339. /*! \brief SIP show channelstats CLI (main function) */
  18340. static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18341. {
  18342. struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
  18343. switch (cmd) {
  18344. case CLI_INIT:
  18345. e->command = "sip show channelstats";
  18346. e->usage =
  18347. "Usage: sip show channelstats\n"
  18348. " Lists all currently active SIP channel's RTCP statistics.\n"
  18349. " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
  18350. return NULL;
  18351. case CLI_GENERATE:
  18352. return NULL;
  18353. }
  18354. if (a->argc != 3)
  18355. return CLI_SHOWUSAGE;
  18356. ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
  18357. /* iterate on the container and invoke the callback on each item */
  18358. ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
  18359. ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
  18360. return CLI_SUCCESS;
  18361. }
  18362. #undef FORMAT
  18363. #undef FORMAT2
  18364. /*! \brief List global settings for the SIP channel */
  18365. static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18366. {
  18367. int realtimepeers;
  18368. int realtimeregs;
  18369. struct ast_str *codec_buf = ast_str_alloca(64);
  18370. const char *msg; /* temporary msg pointer */
  18371. struct sip_auth_container *credentials;
  18372. switch (cmd) {
  18373. case CLI_INIT:
  18374. e->command = "sip show settings";
  18375. e->usage =
  18376. "Usage: sip show settings\n"
  18377. " Provides detailed list of the configuration of the SIP channel.\n";
  18378. return NULL;
  18379. case CLI_GENERATE:
  18380. return NULL;
  18381. }
  18382. if (a->argc != 3)
  18383. return CLI_SHOWUSAGE;
  18384. realtimepeers = ast_check_realtime("sippeers");
  18385. realtimeregs = ast_check_realtime("sipregs");
  18386. ast_mutex_lock(&authl_lock);
  18387. credentials = authl;
  18388. if (credentials) {
  18389. ao2_t_ref(credentials, +1, "Ref global auth for show");
  18390. }
  18391. ast_mutex_unlock(&authl_lock);
  18392. ast_cli(a->fd, "\n\nGlobal Settings:\n");
  18393. ast_cli(a->fd, "----------------\n");
  18394. ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_sockaddr_stringify(&bindaddr));
  18395. if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
  18396. ast_cli(a->fd, " ** Additional Info:\n");
  18397. ast_cli(a->fd, " [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
  18398. }
  18399. ast_cli(a->fd, " TCP SIP Bindaddress: %s\n",
  18400. sip_cfg.tcp_enabled != FALSE ?
  18401. ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
  18402. "Disabled");
  18403. ast_cli(a->fd, " TLS SIP Bindaddress: %s\n",
  18404. default_tls_cfg.enabled != FALSE ?
  18405. ast_sockaddr_stringify(&sip_tls_desc.local_address) :
  18406. "Disabled");
  18407. ast_cli(a->fd, " Videosupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
  18408. ast_cli(a->fd, " Textsupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
  18409. ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
  18410. ast_cli(a->fd, " AutoCreate Peer: %s\n", autocreatepeer2str(sip_cfg.autocreatepeer));
  18411. ast_cli(a->fd, " Match Auth Username: %s\n", AST_CLI_YESNO(global_match_auth_username));
  18412. ast_cli(a->fd, " Allow unknown access: %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
  18413. ast_cli(a->fd, " Allow subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
  18414. ast_cli(a->fd, " Allow overlap dialing: %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
  18415. ast_cli(a->fd, " Allow promisc. redir: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
  18416. ast_cli(a->fd, " Enable call counters: %s\n", AST_CLI_YESNO(global_callcounter));
  18417. ast_cli(a->fd, " SIP domain support: %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
  18418. ast_cli(a->fd, " Path support : %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEPATH)));
  18419. ast_cli(a->fd, " Realm. auth: %s\n", AST_CLI_YESNO(credentials != NULL));
  18420. if (credentials) {
  18421. struct sip_auth *auth;
  18422. AST_LIST_TRAVERSE(&credentials->list, auth, node) {
  18423. ast_cli(a->fd, " Realm. auth entry: Realm %-15.15s User %-10.20s %s\n",
  18424. auth->realm,
  18425. auth->username,
  18426. !ast_strlen_zero(auth->secret)
  18427. ? "<Secret set>"
  18428. : (!ast_strlen_zero(auth->md5secret)
  18429. ? "<MD5secret set>" : "<Not set>"));
  18430. }
  18431. ao2_t_ref(credentials, -1, "Unref global auth for show");
  18432. }
  18433. ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
  18434. ast_cli(a->fd, " Use domains as realms: %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
  18435. ast_cli(a->fd, " Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
  18436. ast_cli(a->fd, " URI user is phone no: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
  18437. ast_cli(a->fd, " Always auth rejects: %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
  18438. ast_cli(a->fd, " Direct RTP setup: %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
  18439. ast_cli(a->fd, " User Agent: %s\n", global_useragent);
  18440. ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
  18441. ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
  18442. ast_cli(a->fd, " Reg. context: %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
  18443. ast_cli(a->fd, " Regexten on Qualify: %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
  18444. ast_cli(a->fd, " Trust RPID: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_TRUSTRPID)));
  18445. ast_cli(a->fd, " Send RPID: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_SENDRPID)));
  18446. ast_cli(a->fd, " Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
  18447. ast_cli(a->fd, " Send Diversion: %s\n", AST_CLI_YESNO(sip_cfg.send_diversion));
  18448. ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
  18449. if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
  18450. ast_cli(a->fd, " From: Domain: %s:%d\n", default_fromdomain, default_fromdomainport);
  18451. } else {
  18452. ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
  18453. }
  18454. ast_cli(a->fd, " Record SIP history: %s\n", AST_CLI_ONOFF(recordhistory));
  18455. ast_cli(a->fd, " Auth. Failure Events: %s\n", AST_CLI_ONOFF(global_authfailureevents));
  18456. ast_cli(a->fd, " T.38 support: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
  18457. ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
  18458. ast_cli(a->fd, " T.38 MaxDtgrm: %u\n", global_t38_maxdatagram);
  18459. if (!realtimepeers && !realtimeregs)
  18460. ast_cli(a->fd, " SIP realtime: Disabled\n" );
  18461. else
  18462. ast_cli(a->fd, " SIP realtime: Enabled\n" );
  18463. ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
  18464. ast_cli(a->fd, " Q.850 Reason header: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
  18465. ast_cli(a->fd, " Store SIP_CAUSE: %s\n", AST_CLI_YESNO(global_store_sip_cause));
  18466. ast_cli(a->fd, "\nNetwork QoS Settings:\n");
  18467. ast_cli(a->fd, "---------------------------\n");
  18468. ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
  18469. ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
  18470. ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
  18471. ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
  18472. ast_cli(a->fd, " 802.1p CoS SIP: %u\n", global_cos_sip);
  18473. ast_cli(a->fd, " 802.1p CoS RTP audio: %u\n", global_cos_audio);
  18474. ast_cli(a->fd, " 802.1p CoS RTP video: %u\n", global_cos_video);
  18475. ast_cli(a->fd, " 802.1p CoS RTP text: %u\n", global_cos_text);
  18476. ast_cli(a->fd, " Jitterbuffer enabled: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
  18477. if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
  18478. ast_cli(a->fd, " Jitterbuffer forced: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
  18479. ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
  18480. ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
  18481. ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
  18482. if (!strcasecmp(global_jbconf.impl, "adaptive")) {
  18483. ast_cli(a->fd, " Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
  18484. }
  18485. ast_cli(a->fd, " Jitterbuffer log: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
  18486. }
  18487. ast_cli(a->fd, "\nNetwork Settings:\n");
  18488. ast_cli(a->fd, "---------------------------\n");
  18489. /* determine if/how SIP address can be remapped */
  18490. if (localaddr == NULL)
  18491. msg = "Disabled, no localnet list";
  18492. else if (ast_sockaddr_isnull(&externaddr))
  18493. msg = "Disabled";
  18494. else if (!ast_strlen_zero(externhost))
  18495. msg = "Enabled using externhost";
  18496. else
  18497. msg = "Enabled using externaddr";
  18498. ast_cli(a->fd, " SIP address remapping: %s\n", msg);
  18499. ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
  18500. ast_cli(a->fd, " Externaddr: %s\n", ast_sockaddr_stringify(&externaddr));
  18501. ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
  18502. {
  18503. struct ast_ha *d;
  18504. const char *prefix = "Localnet:";
  18505. for (d = localaddr; d ; prefix = "", d = d->next) {
  18506. const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
  18507. const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
  18508. ast_cli(a->fd, " %-24s%s/%s\n", prefix, addr, mask);
  18509. }
  18510. }
  18511. ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
  18512. ast_cli(a->fd, "---------------------------\n");
  18513. ast_cli(a->fd, " Codecs: %s\n", ast_format_cap_get_names(sip_cfg.caps, &codec_buf));
  18514. ast_cli(a->fd, " Relax DTMF: %s\n", AST_CLI_YESNO(global_relaxdtmf));
  18515. ast_cli(a->fd, " RFC2833 Compensation: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
  18516. ast_cli(a->fd, " Symmetric RTP: %s\n", comedia_string(global_flags));
  18517. ast_cli(a->fd, " Compact SIP headers: %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
  18518. ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
  18519. ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
  18520. ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
  18521. ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
  18522. ast_cli(a->fd, " DNS SRV lookup: %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
  18523. ast_cli(a->fd, " Pedantic SIP support: %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
  18524. ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
  18525. ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
  18526. ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
  18527. ast_cli(a->fd, " Sub. min duration %d secs\n", min_subexpiry);
  18528. ast_cli(a->fd, " Sub. max duration: %d secs\n", max_subexpiry);
  18529. ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
  18530. ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
  18531. ast_cli(a->fd, " Outbound reg. retry 403:%d\n", global_reg_retry_403);
  18532. ast_cli(a->fd, " Notify ringing state: %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
  18533. if (sip_cfg.notifyringing) {
  18534. ast_cli(a->fd, " Include CID: %s%s\n",
  18535. AST_CLI_YESNO(sip_cfg.notifycid),
  18536. sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
  18537. }
  18538. ast_cli(a->fd, " Notify hold state: %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
  18539. ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
  18540. ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
  18541. ast_cli(a->fd, " Auto-Framing: %s\n", AST_CLI_YESNO(global_autoframing));
  18542. ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
  18543. sip_cfg.outboundproxy.force ? "(forced)" : "");
  18544. ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
  18545. ast_cli(a->fd, " Session Refresher: %s\n", strefresherparam2str(global_st_refresher));
  18546. ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
  18547. ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
  18548. ast_cli(a->fd, " Timer T1: %d\n", global_t1);
  18549. ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
  18550. ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
  18551. ast_cli(a->fd, " No premature media: %s\n", AST_CLI_YESNO(global_prematuremediafilter));
  18552. ast_cli(a->fd, " Max forwards: %d\n", sip_cfg.default_max_forwards);
  18553. ast_cli(a->fd, "\nDefault Settings:\n");
  18554. ast_cli(a->fd, "-----------------\n");
  18555. ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
  18556. ast_cli(a->fd, " Outbound transport: %s\n", sip_get_transport(default_primary_transport));
  18557. ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
  18558. ast_cli(a->fd, " Record on feature: %s\n", sip_cfg.default_record_on_feature);
  18559. ast_cli(a->fd, " Record off feature: %s\n", sip_cfg.default_record_off_feature);
  18560. ast_cli(a->fd, " Force rport: %s\n", force_rport_string(global_flags));
  18561. ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
  18562. ast_cli(a->fd, " Qualify: %d\n", default_qualify);
  18563. ast_cli(a->fd, " Keepalive: %d\n", default_keepalive);
  18564. ast_cli(a->fd, " Use ClientCode: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
  18565. 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)));
  18566. ast_cli(a->fd, " Language: %s\n", default_language);
  18567. ast_cli(a->fd, " Tone zone: %s\n", default_zone[0] != '\0' ? default_zone : "<Not set>");
  18568. ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
  18569. ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
  18570. ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
  18571. if (realtimepeers || realtimeregs) {
  18572. ast_cli(a->fd, "\nRealtime SIP Settings:\n");
  18573. ast_cli(a->fd, "----------------------\n");
  18574. ast_cli(a->fd, " Realtime Peers: %s\n", AST_CLI_YESNO(realtimepeers));
  18575. ast_cli(a->fd, " Realtime Regs: %s\n", AST_CLI_YESNO(realtimeregs));
  18576. ast_cli(a->fd, " Cache Friends: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
  18577. ast_cli(a->fd, " Update: %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
  18578. ast_cli(a->fd, " Ignore Reg. Expire: %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
  18579. ast_cli(a->fd, " Save sys. name: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
  18580. ast_cli(a->fd, " Save path header: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_path));
  18581. ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
  18582. }
  18583. ast_cli(a->fd, "\n----\n");
  18584. return CLI_SUCCESS;
  18585. }
  18586. static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18587. {
  18588. #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
  18589. char host[80];
  18590. struct ao2_iterator iter;
  18591. struct sip_subscription_mwi *iterator;
  18592. switch (cmd) {
  18593. case CLI_INIT:
  18594. e->command = "sip show mwi";
  18595. e->usage =
  18596. "Usage: sip show mwi\n"
  18597. " Provides a list of MWI subscriptions and status.\n";
  18598. return NULL;
  18599. case CLI_GENERATE:
  18600. return NULL;
  18601. }
  18602. ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
  18603. iter = ao2_iterator_init(subscription_mwi_list, 0);
  18604. while ((iterator = ao2_t_iterator_next(&iter, "sip_show_mwi iter"))) {
  18605. ao2_lock(iterator);
  18606. snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
  18607. ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
  18608. ao2_unlock(iterator);
  18609. ao2_t_ref(iterator, -1, "sip_show_mwi iter");
  18610. }
  18611. ao2_iterator_destroy(&iter);
  18612. return CLI_SUCCESS;
  18613. #undef FORMAT
  18614. }
  18615. /*! \brief Show subscription type in string format */
  18616. static const char *subscription_type2str(enum subscriptiontype subtype)
  18617. {
  18618. int i;
  18619. for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
  18620. if (subscription_types[i].type == subtype) {
  18621. return subscription_types[i].text;
  18622. }
  18623. }
  18624. return subscription_types[0].text;
  18625. }
  18626. /*! \brief Find subscription type in array */
  18627. static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
  18628. {
  18629. int i;
  18630. for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
  18631. if (subscription_types[i].type == subtype) {
  18632. return &subscription_types[i];
  18633. }
  18634. }
  18635. return &subscription_types[0];
  18636. }
  18637. /*
  18638. * We try to structure all functions that loop on data structures as
  18639. * a handler for individual entries, and a mainloop that iterates
  18640. * on the main data structure. This way, moving the code to containers
  18641. * that support iteration through callbacks will be a lot easier.
  18642. */
  18643. #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
  18644. #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
  18645. #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-10.10s %-10.10s\n"
  18646. #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s %-10.10s\n"
  18647. /*! \brief callback for show channel|subscription */
  18648. static int show_channels_cb(void *__cur, void *__arg, int flags)
  18649. {
  18650. struct sip_pvt *cur = __cur;
  18651. struct __show_chan_arg *arg = __arg;
  18652. const struct ast_sockaddr *dst;
  18653. sip_pvt_lock(cur);
  18654. dst = sip_real_dst(cur);
  18655. /* XXX indentation preserved to reduce diff. Will be fixed later */
  18656. if (cur->subscribed == NONE && !arg->subscriptions) {
  18657. /* set if SIP transfer in progress */
  18658. const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
  18659. struct ast_str *codec_buf = ast_str_alloca(64);
  18660. ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
  18661. S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
  18662. cur->callid,
  18663. cur->owner ? ast_format_cap_get_names(ast_channel_nativeformats(cur->owner), &codec_buf) : "(nothing)",
  18664. AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
  18665. cur->needdestroy ? "(d)" : "",
  18666. cur->lastmsg ,
  18667. referstatus,
  18668. cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
  18669. );
  18670. arg->numchans++;
  18671. }
  18672. if (cur->subscribed != NONE && arg->subscriptions) {
  18673. struct ast_str *mailbox_str = ast_str_alloca(512);
  18674. if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
  18675. peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
  18676. ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
  18677. S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
  18678. cur->callid,
  18679. /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
  18680. cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
  18681. cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
  18682. subscription_type2str(cur->subscribed),
  18683. cur->subscribed == MWI_NOTIFICATION ? S_OR(ast_str_buffer(mailbox_str), "<none>") : "<none>",
  18684. cur->expiry
  18685. );
  18686. arg->numchans++;
  18687. }
  18688. sip_pvt_unlock(cur);
  18689. return 0; /* don't care, we scan all channels */
  18690. }
  18691. /*! \brief CLI for show channels or subscriptions.
  18692. * This is a new-style CLI handler so a single function contains
  18693. * the prototype for the function, the 'generator' to produce multiple
  18694. * entries in case it is required, and the actual handler for the command.
  18695. */
  18696. static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18697. {
  18698. struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
  18699. if (cmd == CLI_INIT) {
  18700. e->command = "sip show {channels|subscriptions}";
  18701. e->usage =
  18702. "Usage: sip show channels\n"
  18703. " Lists all currently active SIP calls (dialogs).\n"
  18704. "Usage: sip show subscriptions\n"
  18705. " Lists active SIP subscriptions.\n";
  18706. return NULL;
  18707. } else if (cmd == CLI_GENERATE)
  18708. return NULL;
  18709. if (a->argc != e->args)
  18710. return CLI_SHOWUSAGE;
  18711. arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
  18712. if (!arg.subscriptions)
  18713. ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
  18714. else
  18715. ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
  18716. /* iterate on the container and invoke the callback on each item */
  18717. ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
  18718. /* print summary information */
  18719. ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
  18720. (arg.subscriptions ? "subscription" : "dialog"),
  18721. ESS(arg.numchans)); /* ESS(n) returns an "s" if n>1 */
  18722. return CLI_SUCCESS;
  18723. #undef FORMAT
  18724. #undef FORMAT2
  18725. #undef FORMAT3
  18726. }
  18727. /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
  18728. * This is in charge of generating all strings that match a prefix in the
  18729. * given position. As many functions of this kind, each invokation has
  18730. * O(state) time complexity so be careful in using it.
  18731. */
  18732. static char *complete_sipch(const char *line, const char *word, int pos, int state)
  18733. {
  18734. int which=0;
  18735. struct sip_pvt *cur;
  18736. char *c = NULL;
  18737. int wordlen = strlen(word);
  18738. struct ao2_iterator i;
  18739. if (pos != 3) {
  18740. return NULL;
  18741. }
  18742. i = ao2_iterator_init(dialogs, 0);
  18743. while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  18744. sip_pvt_lock(cur);
  18745. if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
  18746. c = ast_strdup(cur->callid);
  18747. sip_pvt_unlock(cur);
  18748. dialog_unref(cur, "drop ref in iterator loop break");
  18749. break;
  18750. }
  18751. sip_pvt_unlock(cur);
  18752. dialog_unref(cur, "drop ref in iterator loop");
  18753. }
  18754. ao2_iterator_destroy(&i);
  18755. return c;
  18756. }
  18757. /*! \brief Do completion on peer name */
  18758. static char *complete_sip_peer(const char *word, int state, int flags2)
  18759. {
  18760. char *result = NULL;
  18761. int wordlen = strlen(word);
  18762. int which = 0;
  18763. struct ao2_iterator i = ao2_iterator_init(peers, 0);
  18764. struct sip_peer *peer;
  18765. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  18766. /* locking of the object is not required because only the name and flags are being compared */
  18767. if (!strncasecmp(word, peer->name, wordlen) &&
  18768. (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
  18769. ++which > state)
  18770. result = ast_strdup(peer->name);
  18771. sip_unref_peer(peer, "toss iterator peer ptr before break");
  18772. if (result) {
  18773. break;
  18774. }
  18775. }
  18776. ao2_iterator_destroy(&i);
  18777. return result;
  18778. }
  18779. /*! \brief Do completion on registered peer name */
  18780. static char *complete_sip_registered_peer(const char *word, int state, int flags2)
  18781. {
  18782. char *result = NULL;
  18783. int wordlen = strlen(word);
  18784. int which = 0;
  18785. struct ao2_iterator i;
  18786. struct sip_peer *peer;
  18787. i = ao2_iterator_init(peers, 0);
  18788. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  18789. if (!strncasecmp(word, peer->name, wordlen) &&
  18790. (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
  18791. ++which > state && peer->expire > 0)
  18792. result = ast_strdup(peer->name);
  18793. if (result) {
  18794. sip_unref_peer(peer, "toss iterator peer ptr before break");
  18795. break;
  18796. }
  18797. sip_unref_peer(peer, "toss iterator peer ptr");
  18798. }
  18799. ao2_iterator_destroy(&i);
  18800. return result;
  18801. }
  18802. /*! \brief Support routine for 'sip show history' CLI */
  18803. static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
  18804. {
  18805. if (pos == 3)
  18806. return complete_sipch(line, word, pos, state);
  18807. return NULL;
  18808. }
  18809. /*! \brief Support routine for 'sip show peer' CLI */
  18810. static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
  18811. {
  18812. if (pos == 3) {
  18813. return complete_sip_peer(word, state, 0);
  18814. }
  18815. return NULL;
  18816. }
  18817. /*! \brief Support routine for 'sip unregister' CLI */
  18818. static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
  18819. {
  18820. if (pos == 2)
  18821. return complete_sip_registered_peer(word, state, 0);
  18822. return NULL;
  18823. }
  18824. /*! \brief Support routine for 'sip notify' CLI */
  18825. static char *complete_sip_notify(const char *line, const char *word, int pos, int state)
  18826. {
  18827. char *c = NULL;
  18828. if (pos == 2) {
  18829. int which = 0;
  18830. char *cat = NULL;
  18831. int wordlen = strlen(word);
  18832. /* do completion for notify type */
  18833. if (!notify_types)
  18834. return NULL;
  18835. while ( (cat = ast_category_browse(notify_types, cat)) ) {
  18836. if (!strncasecmp(word, cat, wordlen) && ++which > state) {
  18837. c = ast_strdup(cat);
  18838. break;
  18839. }
  18840. }
  18841. return c;
  18842. }
  18843. if (pos > 2)
  18844. return complete_sip_peer(word, state, 0);
  18845. return NULL;
  18846. }
  18847. /*! \brief Show details of one active dialog */
  18848. static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18849. {
  18850. struct sip_pvt *cur;
  18851. size_t len;
  18852. int found = 0;
  18853. struct ao2_iterator i;
  18854. switch (cmd) {
  18855. case CLI_INIT:
  18856. e->command = "sip show channel";
  18857. e->usage =
  18858. "Usage: sip show channel <call-id>\n"
  18859. " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
  18860. return NULL;
  18861. case CLI_GENERATE:
  18862. return complete_sipch(a->line, a->word, a->pos, a->n);
  18863. }
  18864. if (a->argc != 4)
  18865. return CLI_SHOWUSAGE;
  18866. len = strlen(a->argv[3]);
  18867. i = ao2_iterator_init(dialogs, 0);
  18868. while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  18869. sip_pvt_lock(cur);
  18870. if (!strncasecmp(cur->callid, a->argv[3], len)) {
  18871. struct ast_str *strbuf;
  18872. struct ast_str *codec_buf = ast_str_alloca(64);
  18873. ast_cli(a->fd, "\n");
  18874. if (cur->subscribed != NONE) {
  18875. ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
  18876. } else {
  18877. ast_cli(a->fd, " * SIP Call\n");
  18878. }
  18879. ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
  18880. ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
  18881. ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? ast_channel_name(cur->owner) : "<none>");
  18882. ast_cli(a->fd, " Our Codec Capability: %s\n", ast_format_cap_get_names(cur->caps, &codec_buf));
  18883. ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
  18884. ast_cli(a->fd, " Their Codec Capability: %s\n", ast_format_cap_get_names(cur->peercaps, &codec_buf));
  18885. ast_cli(a->fd, " Joint Codec Capability: %s\n", ast_format_cap_get_names(cur->jointcaps, &codec_buf));
  18886. ast_cli(a->fd, " Format: %s\n", cur->owner ? ast_format_cap_get_names(ast_channel_nativeformats(cur->owner), &codec_buf) : "(nothing)" );
  18887. ast_cli(a->fd, " T.38 support %s\n", AST_CLI_YESNO(cur->udptl != NULL));
  18888. ast_cli(a->fd, " Video support %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
  18889. ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
  18890. ast_cli(a->fd, " Theoretical Address: %s\n", ast_sockaddr_stringify(&cur->sa));
  18891. ast_cli(a->fd, " Received Address: %s\n", ast_sockaddr_stringify(&cur->recv));
  18892. ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
  18893. ast_cli(a->fd, " Force rport: %s\n", force_rport_string(cur->flags));
  18894. if (ast_sockaddr_isnull(&cur->redirip)) {
  18895. ast_cli(a->fd,
  18896. " Audio IP: %s (local)\n",
  18897. ast_sockaddr_stringify_addr(&cur->ourip));
  18898. } else {
  18899. ast_cli(a->fd,
  18900. " Audio IP: %s (Outside bridge)\n",
  18901. ast_sockaddr_stringify_addr(&cur->redirip));
  18902. }
  18903. ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
  18904. ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
  18905. ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
  18906. if (!ast_strlen_zero(cur->username)) {
  18907. ast_cli(a->fd, " Username: %s\n", cur->username);
  18908. }
  18909. if (!ast_strlen_zero(cur->peername)) {
  18910. ast_cli(a->fd, " Peername: %s\n", cur->peername);
  18911. }
  18912. if (!ast_strlen_zero(cur->uri)) {
  18913. ast_cli(a->fd, " Original uri: %s\n", cur->uri);
  18914. }
  18915. if (!ast_strlen_zero(cur->cid_num)) {
  18916. ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
  18917. }
  18918. ast_cli(a->fd, " Need Destroy: %s\n", AST_CLI_YESNO(cur->needdestroy));
  18919. ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
  18920. ast_cli(a->fd, " Promiscuous Redir: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
  18921. if ((strbuf = sip_route_list(&cur->route, 1, 0))) {
  18922. ast_cli(a->fd, " Route: %s\n", ast_str_buffer(strbuf));
  18923. ast_free(strbuf);
  18924. }
  18925. ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
  18926. ast_cli(a->fd, " SIP Options: ");
  18927. if (cur->sipoptions) {
  18928. int x;
  18929. for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
  18930. if (cur->sipoptions & sip_options[x].id)
  18931. ast_cli(a->fd, "%s ", sip_options[x].text);
  18932. }
  18933. ast_cli(a->fd, "\n");
  18934. } else {
  18935. ast_cli(a->fd, "(none)\n");
  18936. }
  18937. if (!cur->stimer) {
  18938. ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
  18939. } else {
  18940. ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
  18941. if (cur->stimer->st_active == TRUE) {
  18942. ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
  18943. ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
  18944. ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
  18945. ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
  18946. ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
  18947. ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
  18948. ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresherparam2str(cur->stimer->st_cached_ref));
  18949. ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
  18950. }
  18951. }
  18952. /* add transport and media types */
  18953. ast_cli(a->fd, " Transport: %s\n", ast_transport2str(cur->socket.type));
  18954. ast_cli(a->fd, " Media: %s\n", cur->srtp ? "SRTP" : cur->rtp ? "RTP" : "None");
  18955. ast_cli(a->fd, "\n\n");
  18956. found++;
  18957. }
  18958. sip_pvt_unlock(cur);
  18959. ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
  18960. }
  18961. ao2_iterator_destroy(&i);
  18962. if (!found) {
  18963. ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
  18964. }
  18965. return CLI_SUCCESS;
  18966. }
  18967. /*! \brief Show history details of one dialog */
  18968. static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  18969. {
  18970. struct sip_pvt *cur;
  18971. size_t len;
  18972. int found = 0;
  18973. struct ao2_iterator i;
  18974. switch (cmd) {
  18975. case CLI_INIT:
  18976. e->command = "sip show history";
  18977. e->usage =
  18978. "Usage: sip show history <call-id>\n"
  18979. " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
  18980. return NULL;
  18981. case CLI_GENERATE:
  18982. return complete_sip_show_history(a->line, a->word, a->pos, a->n);
  18983. }
  18984. if (a->argc != 4) {
  18985. return CLI_SHOWUSAGE;
  18986. }
  18987. if (!recordhistory) {
  18988. ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
  18989. }
  18990. len = strlen(a->argv[3]);
  18991. i = ao2_iterator_init(dialogs, 0);
  18992. while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  18993. sip_pvt_lock(cur);
  18994. if (!strncasecmp(cur->callid, a->argv[3], len)) {
  18995. struct sip_history *hist;
  18996. int x = 0;
  18997. ast_cli(a->fd, "\n");
  18998. if (cur->subscribed != NONE) {
  18999. ast_cli(a->fd, " * Subscription\n");
  19000. } else {
  19001. ast_cli(a->fd, " * SIP Call\n");
  19002. }
  19003. if (cur->history) {
  19004. AST_LIST_TRAVERSE(cur->history, hist, list)
  19005. ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
  19006. }
  19007. if (x == 0) {
  19008. ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
  19009. }
  19010. found++;
  19011. }
  19012. sip_pvt_unlock(cur);
  19013. ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
  19014. }
  19015. ao2_iterator_destroy(&i);
  19016. if (!found) {
  19017. ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
  19018. }
  19019. return CLI_SUCCESS;
  19020. }
  19021. /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
  19022. static void sip_dump_history(struct sip_pvt *dialog)
  19023. {
  19024. int x = 0;
  19025. struct sip_history *hist;
  19026. static int errmsg = 0;
  19027. if (!dialog) {
  19028. return;
  19029. }
  19030. if (!option_debug && !sipdebug) {
  19031. if (!errmsg) {
  19032. ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
  19033. errmsg = 1;
  19034. }
  19035. return;
  19036. }
  19037. ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
  19038. if (dialog->subscribed) {
  19039. ast_debug(1, " * Subscription\n");
  19040. } else {
  19041. ast_debug(1, " * SIP Call\n");
  19042. }
  19043. if (dialog->history) {
  19044. AST_LIST_TRAVERSE(dialog->history, hist, list)
  19045. ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
  19046. }
  19047. if (!x) {
  19048. ast_debug(1, "Call '%s' has no history\n", dialog->callid);
  19049. }
  19050. ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
  19051. }
  19052. /*! \brief Receive SIP INFO Message */
  19053. static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
  19054. {
  19055. const char *buf = "";
  19056. unsigned int event;
  19057. const char *c = sip_get_header(req, "Content-Type");
  19058. /* Need to check the media/type */
  19059. if (!strcasecmp(c, "application/dtmf-relay") ||
  19060. !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
  19061. !strcasecmp(c, "application/dtmf")) {
  19062. unsigned int duration = 0;
  19063. if (!p->owner) { /* not a PBX call */
  19064. transmit_response(p, "481 Call leg/transaction does not exist", req);
  19065. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  19066. return;
  19067. }
  19068. /* If dtmf-relay or vnd.nortelnetworks.digits, parse the signal and duration;
  19069. * otherwise use the body as the signal */
  19070. if (strcasecmp(c, "application/dtmf")) {
  19071. const char *tmp;
  19072. if (ast_strlen_zero(buf = get_content_line(req, "Signal", '='))
  19073. && ast_strlen_zero(buf = get_content_line(req, "d", '='))) {
  19074. ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
  19075. "call %s\n", p->callid);
  19076. transmit_response(p, "200 OK", req);
  19077. return;
  19078. }
  19079. if (!ast_strlen_zero((tmp = get_content_line(req, "Duration", '=')))) {
  19080. sscanf(tmp, "%30u", &duration);
  19081. }
  19082. } else {
  19083. /* Type is application/dtmf, simply use what's in the message body */
  19084. buf = get_content(req);
  19085. }
  19086. /* An empty message body requires us to send a 200 OK */
  19087. if (ast_strlen_zero(buf)) {
  19088. transmit_response(p, "200 OK", req);
  19089. return;
  19090. }
  19091. if (!duration) {
  19092. duration = 100; /* 100 ms */
  19093. }
  19094. if (buf[0] == '*') {
  19095. event = 10;
  19096. } else if (buf[0] == '#') {
  19097. event = 11;
  19098. } else if (buf[0] == '!') {
  19099. event = 16;
  19100. } else if ('A' <= buf[0] && buf[0] <= 'D') {
  19101. event = 12 + buf[0] - 'A';
  19102. } else if ('a' <= buf[0] && buf[0] <= 'd') {
  19103. event = 12 + buf[0] - 'a';
  19104. } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
  19105. ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
  19106. "value for INFO message on call %s\n", p->callid);
  19107. transmit_response(p, "200 OK", req);
  19108. return;
  19109. }
  19110. if (event == 16) {
  19111. /* send a FLASH event */
  19112. struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
  19113. ast_queue_frame(p->owner, &f);
  19114. if (sipdebug) {
  19115. ast_verbose("* DTMF-relay event received: FLASH\n");
  19116. }
  19117. } else {
  19118. /* send a DTMF event */
  19119. struct ast_frame f = { AST_FRAME_DTMF, };
  19120. if (event < 10) {
  19121. f.subclass.integer = '0' + event;
  19122. } else if (event == 10) {
  19123. f.subclass.integer = '*';
  19124. } else if (event == 11) {
  19125. f.subclass.integer = '#';
  19126. } else {
  19127. f.subclass.integer = 'A' + (event - 12);
  19128. }
  19129. f.len = duration;
  19130. ast_queue_frame(p->owner, &f);
  19131. if (sipdebug) {
  19132. ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
  19133. }
  19134. }
  19135. transmit_response(p, "200 OK", req);
  19136. return;
  19137. } else if (!strcasecmp(c, "application/media_control+xml")) {
  19138. /* Eh, we'll just assume it's a fast picture update for now */
  19139. if (p->owner) {
  19140. ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
  19141. }
  19142. transmit_response(p, "200 OK", req);
  19143. return;
  19144. } else if (!ast_strlen_zero(c = sip_get_header(req, "X-ClientCode"))) {
  19145. /* Client code (from SNOM phone) */
  19146. if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
  19147. if (p->owner) {
  19148. ast_cdr_setuserfield(ast_channel_name(p->owner), c);
  19149. }
  19150. transmit_response(p, "200 OK", req);
  19151. } else {
  19152. transmit_response(p, "403 Forbidden", req);
  19153. }
  19154. return;
  19155. } else if (!ast_strlen_zero(c = sip_get_header(req, "Record"))) {
  19156. /* INFO messages generated by some phones to start/stop recording
  19157. * on phone calls.
  19158. */
  19159. char feat[AST_FEATURE_MAX_LEN];
  19160. int feat_res = -1;
  19161. int j;
  19162. struct ast_frame f = { AST_FRAME_DTMF, };
  19163. int suppress_warning = 0; /* Supress warning if the feature is blank */
  19164. if (!p->owner) { /* not a PBX call */
  19165. transmit_response(p, "481 Call leg/transaction does not exist", req);
  19166. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  19167. return;
  19168. }
  19169. /* first, get the feature string, if it exists */
  19170. if (p->relatedpeer) {
  19171. if (!strcasecmp(c, "on")) {
  19172. if (ast_strlen_zero(p->relatedpeer->record_on_feature)) {
  19173. suppress_warning = 1;
  19174. } else {
  19175. feat_res = ast_get_feature(p->owner, p->relatedpeer->record_on_feature, feat, sizeof(feat));
  19176. }
  19177. } else if (!strcasecmp(c, "off")) {
  19178. if (ast_strlen_zero(p->relatedpeer->record_off_feature)) {
  19179. suppress_warning = 1;
  19180. } else {
  19181. feat_res = ast_get_feature(p->owner, p->relatedpeer->record_off_feature, feat, sizeof(feat));
  19182. }
  19183. } else {
  19184. ast_log(LOG_ERROR, "Received INFO requesting to record with invalid value: %s\n", c);
  19185. }
  19186. }
  19187. if (feat_res || ast_strlen_zero(feat)) {
  19188. if (!suppress_warning) {
  19189. ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
  19190. }
  19191. /* 403 means that we don't support this feature, so don't request it again */
  19192. transmit_response(p, "403 Forbidden", req);
  19193. return;
  19194. }
  19195. /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
  19196. f.len = 100;
  19197. for (j = 0; j < strlen(feat); j++) {
  19198. f.subclass.integer = feat[j];
  19199. ast_queue_frame(p->owner, &f);
  19200. if (sipdebug) {
  19201. ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
  19202. }
  19203. }
  19204. ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
  19205. transmit_response(p, "200 OK", req);
  19206. return;
  19207. } else if (ast_strlen_zero(c = sip_get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
  19208. /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
  19209. transmit_response(p, "200 OK", req);
  19210. return;
  19211. }
  19212. /* Other type of INFO message, not really understood by Asterisk */
  19213. ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
  19214. transmit_response(p, "415 Unsupported media type", req);
  19215. return;
  19216. }
  19217. /*! \brief Enable SIP Debugging for a single IP */
  19218. static char *sip_do_debug_ip(int fd, const char *arg)
  19219. {
  19220. if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
  19221. return CLI_SHOWUSAGE;
  19222. }
  19223. ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
  19224. sipdebug |= sip_debug_console;
  19225. return CLI_SUCCESS;
  19226. }
  19227. /*! \brief Turn on SIP debugging for a given peer */
  19228. static char *sip_do_debug_peer(int fd, const char *arg)
  19229. {
  19230. struct sip_peer *peer = sip_find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
  19231. if (!peer) {
  19232. ast_cli(fd, "No such peer '%s'\n", arg);
  19233. } else if (ast_sockaddr_isnull(&peer->addr)) {
  19234. ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
  19235. } else {
  19236. ast_sockaddr_copy(&debugaddr, &peer->addr);
  19237. ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
  19238. sipdebug |= sip_debug_console;
  19239. }
  19240. if (peer) {
  19241. sip_unref_peer(peer, "sip_do_debug_peer: sip_unref_peer, from sip_find_peer call");
  19242. }
  19243. return CLI_SUCCESS;
  19244. }
  19245. /*! \brief Turn on SIP debugging (CLI command) */
  19246. static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  19247. {
  19248. int oldsipdebug = sipdebug & sip_debug_console;
  19249. const char *what;
  19250. if (cmd == CLI_INIT) {
  19251. e->command = "sip set debug {on|off|ip|peer}";
  19252. e->usage =
  19253. "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
  19254. " Globally disables dumping of SIP packets,\n"
  19255. " or enables it either globally or for a (single)\n"
  19256. " IP address or registered peer.\n";
  19257. return NULL;
  19258. } else if (cmd == CLI_GENERATE) {
  19259. if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
  19260. return complete_sip_peer(a->word, a->n, 0);
  19261. return NULL;
  19262. }
  19263. what = a->argv[e->args-1]; /* guaranteed to exist */
  19264. if (a->argc == e->args) { /* on/off */
  19265. if (!strcasecmp(what, "on")) {
  19266. sipdebug |= sip_debug_console;
  19267. sipdebug_text = 1; /*! \note this can be a special debug command - "sip debug text" or something */
  19268. memset(&debugaddr, 0, sizeof(debugaddr));
  19269. ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
  19270. return CLI_SUCCESS;
  19271. } else if (!strcasecmp(what, "off")) {
  19272. sipdebug &= ~sip_debug_console;
  19273. sipdebug_text = 0;
  19274. ast_cli(a->fd, "SIP Debugging Disabled\n");
  19275. return CLI_SUCCESS;
  19276. }
  19277. } else if (a->argc == e->args + 1) { /* ip/peer */
  19278. if (!strcasecmp(what, "ip"))
  19279. return sip_do_debug_ip(a->fd, a->argv[e->args]);
  19280. else if (!strcasecmp(what, "peer"))
  19281. return sip_do_debug_peer(a->fd, a->argv[e->args]);
  19282. }
  19283. return CLI_SHOWUSAGE; /* default, failure */
  19284. }
  19285. /*! \brief Cli command to send SIP notify to peer */
  19286. static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  19287. {
  19288. struct ast_variable *varlist;
  19289. int i;
  19290. switch (cmd) {
  19291. case CLI_INIT:
  19292. e->command = "sip notify";
  19293. e->usage =
  19294. "Usage: sip notify <type> <peer> [<peer>...]\n"
  19295. " Send a NOTIFY message to a SIP peer or peers\n"
  19296. " Message types are defined in sip_notify.conf\n";
  19297. return NULL;
  19298. case CLI_GENERATE:
  19299. return complete_sip_notify(a->line, a->word, a->pos, a->n);
  19300. }
  19301. if (a->argc < 4)
  19302. return CLI_SHOWUSAGE;
  19303. if (!notify_types) {
  19304. ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
  19305. return CLI_FAILURE;
  19306. }
  19307. varlist = ast_variable_browse(notify_types, a->argv[2]);
  19308. if (!varlist) {
  19309. ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
  19310. return CLI_FAILURE;
  19311. }
  19312. for (i = 3; i < a->argc; i++) {
  19313. struct sip_pvt *p;
  19314. char buf[512];
  19315. struct ast_variable *header, *var;
  19316. if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
  19317. ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
  19318. return CLI_FAILURE;
  19319. }
  19320. if (create_addr(p, a->argv[i], NULL, 1)) {
  19321. /* Maybe they're not registered, etc. */
  19322. dialog_unlink_all(p);
  19323. dialog_unref(p, "unref dialog inside for loop" );
  19324. /* sip_destroy(p); */
  19325. ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
  19326. continue;
  19327. }
  19328. /* Notify is outgoing call */
  19329. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  19330. sip_notify_alloc(p);
  19331. p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
  19332. for (var = varlist; var; var = var->next) {
  19333. ast_copy_string(buf, var->value, sizeof(buf));
  19334. ast_unescape_semicolon(buf);
  19335. if (!strcasecmp(var->name, "Content")) {
  19336. if (ast_str_strlen(p->notify->content))
  19337. ast_str_append(&p->notify->content, 0, "\r\n");
  19338. ast_str_append(&p->notify->content, 0, "%s", buf);
  19339. } else if (!strcasecmp(var->name, "Content-Length")) {
  19340. ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
  19341. } else {
  19342. header->next = ast_variable_new(var->name, buf, "");
  19343. header = header->next;
  19344. }
  19345. }
  19346. /* Now that we have the peer's address, set our ip and change callid */
  19347. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  19348. build_via(p);
  19349. change_callid_pvt(p, NULL);
  19350. ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
  19351. sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
  19352. transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
  19353. dialog_unref(p, "bump down the count of p since we're done with it.");
  19354. }
  19355. return CLI_SUCCESS;
  19356. }
  19357. /*! \brief Enable/Disable SIP History logging (CLI) */
  19358. static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  19359. {
  19360. switch (cmd) {
  19361. case CLI_INIT:
  19362. e->command = "sip set history {on|off}";
  19363. e->usage =
  19364. "Usage: sip set history {on|off}\n"
  19365. " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
  19366. " Use 'sip show history' to view the history of a call number.\n";
  19367. return NULL;
  19368. case CLI_GENERATE:
  19369. return NULL;
  19370. }
  19371. if (a->argc != e->args)
  19372. return CLI_SHOWUSAGE;
  19373. if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
  19374. recordhistory = TRUE;
  19375. ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
  19376. } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
  19377. recordhistory = FALSE;
  19378. ast_cli(a->fd, "SIP History Recording Disabled\n");
  19379. } else {
  19380. return CLI_SHOWUSAGE;
  19381. }
  19382. return CLI_SUCCESS;
  19383. }
  19384. /*! \brief Authenticate for outbound registration */
  19385. static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
  19386. {
  19387. char *header, *respheader;
  19388. char digest[1024];
  19389. p->authtries++;
  19390. sip_auth_headers(code, &header, &respheader);
  19391. memset(digest, 0, sizeof(digest));
  19392. if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
  19393. /* There's nothing to use for authentication */
  19394. /* No digest challenge in request */
  19395. if (sip_debug_test_pvt(p) && p->registry)
  19396. ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
  19397. /* No old challenge */
  19398. return -1;
  19399. }
  19400. if (p->do_history)
  19401. append_history(p, "RegistryAuth", "Try: %d", p->authtries);
  19402. if (sip_debug_test_pvt(p) && p->registry)
  19403. ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
  19404. return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
  19405. }
  19406. /*! \brief Add authentication on outbound SIP packet */
  19407. static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
  19408. {
  19409. char *header, *respheader;
  19410. char digest[1024];
  19411. if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
  19412. return -2;
  19413. p->authtries++;
  19414. sip_auth_headers(code, &header, &respheader);
  19415. ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
  19416. memset(digest, 0, sizeof(digest));
  19417. if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
  19418. /* No way to authenticate */
  19419. return -1;
  19420. }
  19421. /* Now we have a reply digest */
  19422. p->options->auth = digest;
  19423. p->options->authheader = respheader;
  19424. return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
  19425. }
  19426. /*! \brief reply to authentication for outbound registrations
  19427. \return Returns -1 if we have no auth
  19428. \note This is used for register= servers in sip.conf, SIP proxies we register
  19429. with for receiving calls from. */
  19430. static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
  19431. {
  19432. char tmp[512];
  19433. char *c;
  19434. char oldnonce[256];
  19435. /* table of recognised keywords, and places where they should be copied */
  19436. const struct x {
  19437. const char *key;
  19438. const ast_string_field *field;
  19439. } *i, keys[] = {
  19440. { "realm=", &p->realm },
  19441. { "nonce=", &p->nonce },
  19442. { "opaque=", &p->opaque },
  19443. { "qop=", &p->qop },
  19444. { "domain=", &p->domain },
  19445. { NULL, 0 },
  19446. };
  19447. ast_copy_string(tmp, sip_get_header(req, header), sizeof(tmp));
  19448. if (ast_strlen_zero(tmp))
  19449. return -1;
  19450. if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
  19451. ast_log(LOG_WARNING, "missing Digest.\n");
  19452. return -1;
  19453. }
  19454. c = tmp + strlen("Digest ");
  19455. ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
  19456. while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
  19457. for (i = keys; i->key != NULL; i++) {
  19458. char *src, *separator;
  19459. if (strncasecmp(c, i->key, strlen(i->key)) != 0)
  19460. continue;
  19461. /* Found. Skip keyword, take text in quotes or up to the separator. */
  19462. c += strlen(i->key);
  19463. if (*c == '"') {
  19464. src = ++c;
  19465. separator = "\"";
  19466. } else {
  19467. src = c;
  19468. separator = ",";
  19469. }
  19470. strsep(&c, separator); /* clear separator and move ptr */
  19471. ast_string_field_ptr_set(p, i->field, src);
  19472. break;
  19473. }
  19474. if (i->key == NULL) /* not found, try ',' */
  19475. strsep(&c, ",");
  19476. }
  19477. /* Reset nonce count */
  19478. if (strcmp(p->nonce, oldnonce))
  19479. p->noncecount = 0;
  19480. /* Save auth data for following registrations */
  19481. if (p->registry) {
  19482. struct sip_registry *r = p->registry;
  19483. if (strcmp(r->nonce, p->nonce)) {
  19484. ast_string_field_set(r, realm, p->realm);
  19485. ast_string_field_set(r, nonce, p->nonce);
  19486. ast_string_field_set(r, authdomain, p->domain);
  19487. ast_string_field_set(r, opaque, p->opaque);
  19488. ast_string_field_set(r, qop, p->qop);
  19489. r->noncecount = 0;
  19490. }
  19491. }
  19492. return build_reply_digest(p, sipmethod, digest, digest_len);
  19493. }
  19494. /*! \brief Build reply digest
  19495. \return Returns -1 if we have no auth
  19496. \note Build digest challenge for authentication of registrations and calls
  19497. Also used for authentication of BYE
  19498. */
  19499. static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
  19500. {
  19501. char a1[256];
  19502. char a2[256];
  19503. char a1_hash[256];
  19504. char a2_hash[256];
  19505. char resp[256];
  19506. char resp_hash[256];
  19507. char uri[256];
  19508. char opaque[256] = "";
  19509. char cnonce[80];
  19510. const char *username;
  19511. const char *secret;
  19512. const char *md5secret;
  19513. struct sip_auth *auth; /* Realm authentication credential */
  19514. struct sip_auth_container *credentials;
  19515. if (!ast_strlen_zero(p->domain))
  19516. snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == AST_TRANSPORT_TLS ? "sips" : "sip", p->domain);
  19517. else if (!ast_strlen_zero(p->uri))
  19518. ast_copy_string(uri, p->uri, sizeof(uri));
  19519. else
  19520. snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == AST_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
  19521. snprintf(cnonce, sizeof(cnonce), "%08lx", (unsigned long)ast_random());
  19522. /* Check if we have peer credentials */
  19523. ao2_lock(p);
  19524. credentials = p->peerauth;
  19525. if (credentials) {
  19526. ao2_t_ref(credentials, +1, "Ref peer auth for digest");
  19527. }
  19528. ao2_unlock(p);
  19529. auth = find_realm_authentication(credentials, p->realm);
  19530. if (!auth) {
  19531. /* If not, check global credentials */
  19532. if (credentials) {
  19533. ao2_t_ref(credentials, -1, "Unref peer auth for digest");
  19534. }
  19535. ast_mutex_lock(&authl_lock);
  19536. credentials = authl;
  19537. if (credentials) {
  19538. ao2_t_ref(credentials, +1, "Ref global auth for digest");
  19539. }
  19540. ast_mutex_unlock(&authl_lock);
  19541. auth = find_realm_authentication(credentials, p->realm);
  19542. }
  19543. if (auth) {
  19544. ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
  19545. username = auth->username;
  19546. secret = auth->secret;
  19547. md5secret = auth->md5secret;
  19548. if (sipdebug)
  19549. ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
  19550. } else {
  19551. /* No authentication, use peer or register= config */
  19552. username = p->authname;
  19553. secret = p->relatedpeer
  19554. && !ast_strlen_zero(p->relatedpeer->remotesecret)
  19555. ? p->relatedpeer->remotesecret : p->peersecret;
  19556. md5secret = p->peermd5secret;
  19557. }
  19558. if (ast_strlen_zero(username)) {
  19559. /* We have no authentication */
  19560. if (credentials) {
  19561. ao2_t_ref(credentials, -1, "Unref auth for digest");
  19562. }
  19563. return -1;
  19564. }
  19565. /* Calculate SIP digest response */
  19566. snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
  19567. snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
  19568. if (!ast_strlen_zero(md5secret))
  19569. ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
  19570. else
  19571. ast_md5_hash(a1_hash, a1);
  19572. ast_md5_hash(a2_hash, a2);
  19573. p->noncecount++;
  19574. if (!ast_strlen_zero(p->qop))
  19575. snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, (unsigned)p->noncecount, cnonce, "auth", a2_hash);
  19576. else
  19577. snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
  19578. ast_md5_hash(resp_hash, resp);
  19579. /* only include the opaque string if it's set */
  19580. if (!ast_strlen_zero(p->opaque)) {
  19581. snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
  19582. }
  19583. /* XXX We hard code our qop to "auth" for now. XXX */
  19584. if (!ast_strlen_zero(p->qop))
  19585. 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);
  19586. else
  19587. 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);
  19588. append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
  19589. if (credentials) {
  19590. ao2_t_ref(credentials, -1, "Unref auth for digest");
  19591. }
  19592. return 0;
  19593. }
  19594. /*! \brief Read SIP header (dialplan function) */
  19595. static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
  19596. {
  19597. struct sip_pvt *p;
  19598. const char *content = NULL;
  19599. AST_DECLARE_APP_ARGS(args,
  19600. AST_APP_ARG(header);
  19601. AST_APP_ARG(number);
  19602. );
  19603. int i, number, start = 0;
  19604. if (!chan) {
  19605. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", function);
  19606. return -1;
  19607. }
  19608. if (ast_strlen_zero(data)) {
  19609. ast_log(LOG_WARNING, "This function requires a header name.\n");
  19610. return -1;
  19611. }
  19612. ast_channel_lock(chan);
  19613. if (!IS_SIP_TECH(ast_channel_tech(chan))) {
  19614. ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
  19615. ast_channel_unlock(chan);
  19616. return -1;
  19617. }
  19618. AST_STANDARD_APP_ARGS(args, data);
  19619. if (!args.number) {
  19620. number = 1;
  19621. } else {
  19622. sscanf(args.number, "%30d", &number);
  19623. if (number < 1)
  19624. number = 1;
  19625. }
  19626. p = ast_channel_tech_pvt(chan);
  19627. /* If there is no private structure, this channel is no longer alive */
  19628. if (!p) {
  19629. ast_channel_unlock(chan);
  19630. return -1;
  19631. }
  19632. for (i = 0; i < number; i++)
  19633. content = __get_header(&p->initreq, args.header, &start);
  19634. if (ast_strlen_zero(content)) {
  19635. ast_channel_unlock(chan);
  19636. return -1;
  19637. }
  19638. ast_copy_string(buf, content, len);
  19639. ast_channel_unlock(chan);
  19640. return 0;
  19641. }
  19642. static struct ast_custom_function sip_header_function = {
  19643. .name = "SIP_HEADER",
  19644. .read = func_header_read,
  19645. };
  19646. /*! \brief Dial plan function to check if domain is local */
  19647. static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  19648. {
  19649. if (ast_strlen_zero(data)) {
  19650. ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
  19651. return -1;
  19652. }
  19653. if (check_sip_domain(data, NULL, 0))
  19654. ast_copy_string(buf, data, len);
  19655. else
  19656. buf[0] = '\0';
  19657. return 0;
  19658. }
  19659. static struct ast_custom_function checksipdomain_function = {
  19660. .name = "CHECKSIPDOMAIN",
  19661. .read = func_check_sipdomain,
  19662. };
  19663. /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
  19664. static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  19665. {
  19666. struct sip_peer *peer;
  19667. char *colname;
  19668. if ((colname = strchr(data, ','))) {
  19669. *colname++ = '\0';
  19670. } else {
  19671. colname = "ip";
  19672. }
  19673. if (!(peer = sip_find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
  19674. return -1;
  19675. if (!strcasecmp(colname, "ip")) {
  19676. ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
  19677. } else if (!strcasecmp(colname, "port")) {
  19678. snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
  19679. } else if (!strcasecmp(colname, "status")) {
  19680. peer_status(peer, buf, len);
  19681. } else if (!strcasecmp(colname, "language")) {
  19682. ast_copy_string(buf, peer->language, len);
  19683. } else if (!strcasecmp(colname, "regexten")) {
  19684. ast_copy_string(buf, peer->regexten, len);
  19685. } else if (!strcasecmp(colname, "limit")) {
  19686. snprintf(buf, len, "%d", peer->call_limit);
  19687. } else if (!strcasecmp(colname, "busylevel")) {
  19688. snprintf(buf, len, "%d", peer->busy_level);
  19689. } else if (!strcasecmp(colname, "curcalls")) {
  19690. snprintf(buf, len, "%d", peer->inuse);
  19691. } else if (!strcasecmp(colname, "maxforwards")) {
  19692. snprintf(buf, len, "%d", peer->maxforwards);
  19693. } else if (!strcasecmp(colname, "accountcode")) {
  19694. ast_copy_string(buf, peer->accountcode, len);
  19695. } else if (!strcasecmp(colname, "callgroup")) {
  19696. ast_print_group(buf, len, peer->callgroup);
  19697. } else if (!strcasecmp(colname, "pickupgroup")) {
  19698. ast_print_group(buf, len, peer->pickupgroup);
  19699. } else if (!strcasecmp(colname, "namedcallgroup")) {
  19700. struct ast_str *tmp_str = ast_str_create(1024);
  19701. if (tmp_str) {
  19702. ast_copy_string(buf, ast_print_namedgroups(&tmp_str, peer->named_callgroups), len);
  19703. ast_free(tmp_str);
  19704. }
  19705. } else if (!strcasecmp(colname, "namedpickupgroup")) {
  19706. struct ast_str *tmp_str = ast_str_create(1024);
  19707. if (tmp_str) {
  19708. ast_copy_string(buf, ast_print_namedgroups(&tmp_str, peer->named_pickupgroups), len);
  19709. ast_free(tmp_str);
  19710. }
  19711. } else if (!strcasecmp(colname, "useragent")) {
  19712. ast_copy_string(buf, peer->useragent, len);
  19713. } else if (!strcasecmp(colname, "mailbox")) {
  19714. struct ast_str *mailbox_str = ast_str_alloca(512);
  19715. peer_mailboxes_to_str(&mailbox_str, peer);
  19716. ast_copy_string(buf, ast_str_buffer(mailbox_str), len);
  19717. } else if (!strcasecmp(colname, "context")) {
  19718. ast_copy_string(buf, peer->context, len);
  19719. } else if (!strcasecmp(colname, "expire")) {
  19720. snprintf(buf, len, "%d", peer->expire);
  19721. } else if (!strcasecmp(colname, "dynamic")) {
  19722. ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
  19723. } else if (!strcasecmp(colname, "callerid_name")) {
  19724. ast_copy_string(buf, peer->cid_name, len);
  19725. } else if (!strcasecmp(colname, "callerid_num")) {
  19726. ast_copy_string(buf, peer->cid_num, len);
  19727. } else if (!strcasecmp(colname, "codecs")) {
  19728. struct ast_str *codec_buf = ast_str_alloca(64);
  19729. ast_format_cap_get_names(peer->caps, &codec_buf);
  19730. ast_copy_string(buf, ast_str_buffer(codec_buf), len);
  19731. } else if (!strcasecmp(colname, "encryption")) {
  19732. snprintf(buf, len, "%u", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
  19733. } else if (!strncasecmp(colname, "chanvar[", 8)) {
  19734. char *chanvar=colname + 8;
  19735. struct ast_variable *v;
  19736. chanvar = strsep(&chanvar, "]");
  19737. for (v = peer->chanvars ; v ; v = v->next) {
  19738. if (!strcasecmp(v->name, chanvar)) {
  19739. ast_copy_string(buf, v->value, len);
  19740. }
  19741. }
  19742. } else if (!strncasecmp(colname, "codec[", 6)) {
  19743. char *codecnum;
  19744. struct ast_format *codec;
  19745. codecnum = colname + 6; /* move past the '[' */
  19746. codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
  19747. codec = ast_format_cap_get_format(peer->caps, atoi(codecnum));
  19748. if (codec) {
  19749. ast_copy_string(buf, ast_format_get_name(codec), len);
  19750. ao2_ref(codec, -1);
  19751. } else {
  19752. buf[0] = '\0';
  19753. }
  19754. } else {
  19755. buf[0] = '\0';
  19756. }
  19757. sip_unref_peer(peer, "sip_unref_peer from function_sippeer, just before return");
  19758. return 0;
  19759. }
  19760. /*! \brief Structure to declare a dialplan function: SIPPEER */
  19761. static struct ast_custom_function sippeer_function = {
  19762. .name = "SIPPEER",
  19763. .read = function_sippeer,
  19764. };
  19765. /*! \brief update redirecting information for a channel based on headers
  19766. *
  19767. */
  19768. static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
  19769. struct ast_party_redirecting *redirecting,
  19770. struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
  19771. {
  19772. char *redirecting_from_name = NULL;
  19773. char *redirecting_from_number = NULL;
  19774. char *redirecting_to_name = NULL;
  19775. char *redirecting_to_number = NULL;
  19776. char *reason_str = NULL;
  19777. int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
  19778. int is_response = req->method == SIP_RESPONSE;
  19779. int res = 0;
  19780. res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason, &reason_str);
  19781. if (res == -1) {
  19782. if (is_response) {
  19783. get_name_and_number(sip_get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
  19784. } else {
  19785. return;
  19786. }
  19787. }
  19788. /* At this point, all redirecting "from" info should be filled in appropriately
  19789. * on to the "to" info
  19790. */
  19791. if (is_response) {
  19792. parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
  19793. } else {
  19794. get_name_and_number(sip_get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
  19795. }
  19796. if (!ast_strlen_zero(redirecting_from_number)) {
  19797. ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
  19798. update_redirecting->from.number = 1;
  19799. redirecting->from.number.valid = 1;
  19800. ast_free(redirecting->from.number.str);
  19801. redirecting->from.number.str = redirecting_from_number;
  19802. }
  19803. if (!ast_strlen_zero(redirecting_from_name)) {
  19804. ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
  19805. update_redirecting->from.name = 1;
  19806. redirecting->from.name.valid = 1;
  19807. ast_free(redirecting->from.name.str);
  19808. redirecting->from.name.str = redirecting_from_name;
  19809. }
  19810. if (!ast_strlen_zero(p->cid_tag)) {
  19811. ast_free(redirecting->from.tag);
  19812. redirecting->from.tag = ast_strdup(p->cid_tag);
  19813. ast_free(redirecting->to.tag);
  19814. redirecting->to.tag = ast_strdup(p->cid_tag);
  19815. }
  19816. if (!ast_strlen_zero(redirecting_to_number)) {
  19817. ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
  19818. update_redirecting->to.number = 1;
  19819. redirecting->to.number.valid = 1;
  19820. ast_free(redirecting->to.number.str);
  19821. redirecting->to.number.str = redirecting_to_number;
  19822. }
  19823. if (!ast_strlen_zero(redirecting_to_name)) {
  19824. ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
  19825. update_redirecting->to.name = 1;
  19826. redirecting->to.name.valid = 1;
  19827. ast_free(redirecting->to.name.str);
  19828. redirecting->to.name.str = redirecting_to_name;
  19829. }
  19830. redirecting->reason.code = reason;
  19831. if (reason_str) {
  19832. ast_debug(3, "Got redirecting reason %s\n", reason_str);
  19833. ast_free(redirecting->reason.str);
  19834. redirecting->reason.str = reason_str;
  19835. }
  19836. }
  19837. /*! \brief Parse 302 Moved temporalily response
  19838. \todo XXX Doesn't redirect over TLS on sips: uri's.
  19839. If we get a redirect to a SIPS: uri, this needs to be going back to the
  19840. dialplan (this is a request for a secure signalling path).
  19841. Note that transport=tls is deprecated, but we need to support it on incoming requests.
  19842. */
  19843. static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
  19844. {
  19845. char contact[SIPBUFSIZE];
  19846. char *contact_name = NULL;
  19847. char *contact_number = NULL;
  19848. char *separator, *trans;
  19849. char *domain;
  19850. enum ast_transport transport = AST_TRANSPORT_UDP;
  19851. ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
  19852. if ((separator = strchr(contact, ',')))
  19853. *separator = '\0';
  19854. contact_number = get_in_brackets(contact);
  19855. if ((trans = strcasestr(contact_number, ";transport="))) {
  19856. trans += 11;
  19857. if ((separator = strchr(trans, ';')))
  19858. *separator = '\0';
  19859. if (!strncasecmp(trans, "tcp", 3))
  19860. transport = AST_TRANSPORT_TCP;
  19861. else if (!strncasecmp(trans, "tls", 3))
  19862. transport = AST_TRANSPORT_TLS;
  19863. else {
  19864. if (strncasecmp(trans, "udp", 3))
  19865. ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
  19866. /* This will assume UDP for all unknown transports */
  19867. transport = AST_TRANSPORT_UDP;
  19868. }
  19869. }
  19870. contact_number = remove_uri_parameters(contact_number);
  19871. if (p->socket.tcptls_session) {
  19872. ao2_ref(p->socket.tcptls_session, -1);
  19873. p->socket.tcptls_session = NULL;
  19874. } else if (p->socket.ws_session) {
  19875. ast_websocket_unref(p->socket.ws_session);
  19876. p->socket.ws_session = NULL;
  19877. }
  19878. set_socket_transport(&p->socket, transport);
  19879. if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
  19880. char *host = NULL;
  19881. if (!strncasecmp(contact_number, "sip:", 4))
  19882. contact_number += 4;
  19883. else if (!strncasecmp(contact_number, "sips:", 5))
  19884. contact_number += 5;
  19885. separator = strchr(contact_number, '/');
  19886. if (separator)
  19887. *separator = '\0';
  19888. if ((host = strchr(contact_number, '@'))) {
  19889. *host++ = '\0';
  19890. ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, sip_get_transport(transport), host);
  19891. if (p->owner)
  19892. ast_channel_call_forward_build(p->owner, "SIP/%s::::%s@%s", contact_number, sip_get_transport(transport), host);
  19893. } else {
  19894. ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", sip_get_transport(transport), contact_number);
  19895. if (p->owner)
  19896. ast_channel_call_forward_build(p->owner, "SIP/::::%s@%s", sip_get_transport(transport), contact_number);
  19897. }
  19898. } else {
  19899. separator = strchr(contact, '@');
  19900. if (separator) {
  19901. *separator++ = '\0';
  19902. domain = separator;
  19903. } else {
  19904. /* No username part */
  19905. domain = contact;
  19906. }
  19907. separator = strchr(contact, '/'); /* WHEN do we hae a forward slash in the URI? */
  19908. if (separator)
  19909. *separator = '\0';
  19910. if (!strncasecmp(contact_number, "sip:", 4))
  19911. contact_number += 4;
  19912. else if (!strncasecmp(contact_number, "sips:", 5))
  19913. contact_number += 5;
  19914. separator = strchr(contact_number, ';'); /* And username ; parameters? */
  19915. if (separator)
  19916. *separator = '\0';
  19917. ast_uri_decode(contact_number, ast_uri_sip_user);
  19918. if (set_call_forward) {
  19919. ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
  19920. if (p->owner) {
  19921. pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
  19922. ast_channel_call_forward_set(p->owner, contact_number);
  19923. }
  19924. }
  19925. }
  19926. /* We've gotten the number for the contact, now get the name */
  19927. if (*contact == '\"') {
  19928. contact_name = contact + 1;
  19929. if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
  19930. ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
  19931. }
  19932. *separator = '\0';
  19933. }
  19934. if (name && !ast_strlen_zero(contact_name)) {
  19935. *name = ast_strdup(contact_name);
  19936. }
  19937. if (number) {
  19938. *number = ast_strdup(contact_number);
  19939. }
  19940. }
  19941. /*! \brief Check pending actions on SIP call
  19942. *
  19943. * \note both sip_pvt and sip_pvt's owner channel (if present)
  19944. * must be locked for this function.
  19945. */
  19946. static void check_pendings(struct sip_pvt *p)
  19947. {
  19948. if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  19949. if (p->reinviteid > -1) {
  19950. /* Outstanding p->reinviteid timeout, so wait... */
  19951. return;
  19952. } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
  19953. /* if we can't BYE, then this is really a pending CANCEL */
  19954. p->invitestate = INV_CANCELLED;
  19955. transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
  19956. /* If the cancel occurred on an initial invite, cancel the pending BYE */
  19957. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  19958. ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
  19959. }
  19960. /* Actually don't destroy us yet, wait for the 487 on our original
  19961. INVITE, but do set an autodestruct just in case we never get it. */
  19962. } else {
  19963. /* We have a pending outbound invite, don't send something
  19964. * new in-transaction, unless it is a pending reinvite, then
  19965. * by the time we are called here, we should probably just hang up. */
  19966. if (p->pendinginvite && !p->ongoing_reinvite)
  19967. return;
  19968. if (p->owner) {
  19969. ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
  19970. }
  19971. /* Perhaps there is an SD change INVITE outstanding */
  19972. transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
  19973. ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
  19974. }
  19975. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  19976. } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
  19977. /* if we can't REINVITE, hold it for later */
  19978. if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
  19979. ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
  19980. } else {
  19981. ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
  19982. /* Didn't get to reinvite yet, so do it now */
  19983. transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
  19984. ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
  19985. }
  19986. }
  19987. }
  19988. /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
  19989. to avoid race conditions between asterisk servers.
  19990. Called from the scheduler.
  19991. */
  19992. static int sip_reinvite_retry(const void *data)
  19993. {
  19994. struct sip_pvt *p = (struct sip_pvt *) data;
  19995. struct ast_channel *owner;
  19996. sip_pvt_lock(p); /* called from schedule thread which requires a lock */
  19997. while ((owner = p->owner) && ast_channel_trylock(owner)) {
  19998. sip_pvt_unlock(p);
  19999. usleep(1);
  20000. sip_pvt_lock(p);
  20001. }
  20002. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  20003. p->waitid = -1;
  20004. check_pendings(p);
  20005. sip_pvt_unlock(p);
  20006. if (owner) {
  20007. ast_channel_unlock(owner);
  20008. }
  20009. dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
  20010. return 0;
  20011. }
  20012. /*!
  20013. * \brief Handle authentication challenge for SIP UPDATE
  20014. *
  20015. * This function is only called upon the receipt of a 401/407 response to an UPDATE.
  20016. */
  20017. static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20018. {
  20019. if (p->options) {
  20020. p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
  20021. }
  20022. if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
  20023. ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", sip_get_header(&p->initreq, "From"));
  20024. }
  20025. }
  20026. static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
  20027. {
  20028. struct cc_epa_entry *cc_entry = epa_entry->instance_data;
  20029. struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
  20030. find_sip_monitor_instance_by_suspension_entry, epa_entry);
  20031. const char *min_expires;
  20032. if (!monitor_instance) {
  20033. ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
  20034. return;
  20035. }
  20036. if (resp != 423) {
  20037. ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
  20038. "Received error response to our PUBLISH");
  20039. ao2_ref(monitor_instance, -1);
  20040. return;
  20041. }
  20042. /* Allrighty, the other end doesn't like our Expires value. They think it's
  20043. * too small, so let's see if they've provided a more sensible value. If they
  20044. * haven't, then we'll just double our Expires value and see if they like that
  20045. * instead.
  20046. *
  20047. * XXX Ideally this logic could be placed into its own function so that SUBSCRIBE,
  20048. * PUBLISH, and REGISTER could all benefit from the same shared code.
  20049. */
  20050. min_expires = sip_get_header(req, "Min-Expires");
  20051. if (ast_strlen_zero(min_expires)) {
  20052. pvt->expiry *= 2;
  20053. if (pvt->expiry < 0) {
  20054. /* You dork! You overflowed! */
  20055. ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
  20056. "PUBLISH expiry overflowed");
  20057. ao2_ref(monitor_instance, -1);
  20058. return;
  20059. }
  20060. } else if (sscanf(min_expires, "%30d", &pvt->expiry) != 1) {
  20061. ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
  20062. "Min-Expires has non-numeric value");
  20063. ao2_ref(monitor_instance, -1);
  20064. return;
  20065. }
  20066. /* At this point, we have most certainly changed pvt->expiry, so try transmitting
  20067. * again
  20068. */
  20069. transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
  20070. ao2_ref(monitor_instance, -1);
  20071. }
  20072. static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20073. {
  20074. struct sip_epa_entry *epa_entry = p->epa_entry;
  20075. const char *etag = sip_get_header(req, "Sip-ETag");
  20076. ast_assert(epa_entry != NULL);
  20077. if (resp == 401 || resp == 407) {
  20078. ast_string_field_set(p, theirtag, NULL);
  20079. if (p->options) {
  20080. p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
  20081. }
  20082. if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
  20083. ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", sip_get_header(&p->initreq, "From"));
  20084. pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
  20085. sip_alreadygone(p);
  20086. }
  20087. return;
  20088. }
  20089. if (resp == 501 || resp == 405) {
  20090. mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
  20091. }
  20092. if (resp == 200) {
  20093. p->authtries = 0;
  20094. /* If I've read section 6, item 6 of RFC 3903 correctly,
  20095. * an ESC will only generate a new etag when it sends a 200 OK
  20096. */
  20097. if (!ast_strlen_zero(etag)) {
  20098. ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
  20099. }
  20100. /* The nominal case. Everything went well. Everybody is happy.
  20101. * Each EPA will have a specific action to take as a result of this
  20102. * development, so ... callbacks!
  20103. */
  20104. if (epa_entry->static_data->handle_ok) {
  20105. epa_entry->static_data->handle_ok(p, req, epa_entry);
  20106. }
  20107. } else {
  20108. /* Rather than try to make individual callbacks for each error
  20109. * type, there is just a single error callback. The callback
  20110. * can distinguish between error messages and do what it needs to
  20111. */
  20112. if (epa_entry->static_data->handle_error) {
  20113. epa_entry->static_data->handle_error(p, resp, req, epa_entry);
  20114. }
  20115. }
  20116. }
  20117. /*!
  20118. * \internal
  20119. * \brief Set hangup source and cause.
  20120. *
  20121. * \param p SIP private.
  20122. * \param cause Hangup cause to queue. Zero if no cause.
  20123. *
  20124. * \pre p and p->owner are locked.
  20125. *
  20126. * \return Nothing
  20127. */
  20128. static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
  20129. {
  20130. struct ast_channel *owner = p->owner;
  20131. const char *name = ast_strdupa(ast_channel_name(owner));
  20132. /* Cannot hold any channel/private locks when calling. */
  20133. ast_channel_ref(owner);
  20134. ast_channel_unlock(owner);
  20135. sip_pvt_unlock(p);
  20136. ast_set_hangupsource(owner, name, 0);
  20137. if (cause) {
  20138. ast_queue_hangup_with_cause(owner, cause);
  20139. } else {
  20140. ast_queue_hangup(owner);
  20141. }
  20142. ast_channel_unref(owner);
  20143. /* Relock things. */
  20144. owner = sip_pvt_lock_full(p);
  20145. if (owner) {
  20146. ast_channel_unref(owner);
  20147. }
  20148. }
  20149. /*! \brief Handle SIP response to INVITE dialogue */
  20150. static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20151. {
  20152. int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
  20153. int res = 0;
  20154. int xmitres = 0;
  20155. int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  20156. char *p_hdrval;
  20157. int rtn;
  20158. struct ast_party_connected_line connected;
  20159. struct ast_set_party_connected_line update_connected;
  20160. if (reinvite) {
  20161. ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
  20162. } else {
  20163. ast_debug(4, "SIP response %d to standard invite\n", resp);
  20164. }
  20165. if (p->alreadygone) { /* This call is already gone */
  20166. ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
  20167. return;
  20168. }
  20169. /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
  20170. /* Don't auto congest anymore since we've gotten something useful back */
  20171. 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"));
  20172. /* RFC3261 says we must treat every 1xx response (but not 100)
  20173. that we don't recognize as if it was 183.
  20174. */
  20175. if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183) {
  20176. resp = 183;
  20177. }
  20178. /* For INVITE, treat all 2XX responses as we would a 200 response */
  20179. if ((resp >= 200) && (resp < 300)) {
  20180. resp = 200;
  20181. }
  20182. /* Any response between 100 and 199 is PROCEEDING */
  20183. if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING) {
  20184. p->invitestate = INV_PROCEEDING;
  20185. }
  20186. /* Final response, not 200 ? */
  20187. if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA )) {
  20188. p->invitestate = INV_COMPLETED;
  20189. }
  20190. if ((resp >= 200 && reinvite)) {
  20191. p->ongoing_reinvite = 0;
  20192. if (p->reinviteid > -1) {
  20193. AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
  20194. }
  20195. }
  20196. /* Final response, clear out pending invite */
  20197. if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
  20198. p->pendinginvite = 0;
  20199. }
  20200. /* If this is a response to our initial INVITE, we need to set what we can use
  20201. * for this peer.
  20202. */
  20203. if (!reinvite) {
  20204. set_pvt_allowed_methods(p, req);
  20205. }
  20206. switch (resp) {
  20207. case 100: /* Trying */
  20208. case 101: /* Dialog establishment */
  20209. if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p)) {
  20210. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  20211. }
  20212. check_pendings(p);
  20213. break;
  20214. case 180: /* 180 Ringing */
  20215. case 182: /* 182 Queued */
  20216. if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p)) {
  20217. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  20218. }
  20219. /* Store Route-set from provisional SIP responses so
  20220. * early-dialog request can be routed properly
  20221. * */
  20222. parse_ok_contact(p, req);
  20223. if (!reinvite) {
  20224. build_route(p, req, 1, resp);
  20225. }
  20226. if (!req->ignore && p->owner) {
  20227. if (get_rpid(p, req)) {
  20228. /* Queue a connected line update */
  20229. ast_party_connected_line_init(&connected);
  20230. memset(&update_connected, 0, sizeof(update_connected));
  20231. update_connected.id.number = 1;
  20232. connected.id.number.valid = 1;
  20233. connected.id.number.str = (char *) p->cid_num;
  20234. connected.id.number.presentation = p->callingpres;
  20235. update_connected.id.name = 1;
  20236. connected.id.name.valid = 1;
  20237. connected.id.name.str = (char *) p->cid_name;
  20238. connected.id.name.presentation = p->callingpres;
  20239. /* Invalidate any earlier private connected id representation */
  20240. ast_set_party_id_all(&update_connected.priv);
  20241. connected.id.tag = (char *) p->cid_tag;
  20242. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  20243. ast_channel_queue_connected_line_update(p->owner, &connected,
  20244. &update_connected);
  20245. }
  20246. sip_handle_cc(p, req, AST_CC_CCNR);
  20247. ast_queue_control(p->owner, AST_CONTROL_RINGING);
  20248. if (ast_channel_state(p->owner) != AST_STATE_UP) {
  20249. ast_setstate(p->owner, AST_STATE_RINGING);
  20250. }
  20251. }
  20252. if (find_sdp(req)) {
  20253. if (p->invitestate != INV_CANCELLED) {
  20254. p->invitestate = INV_EARLY_MEDIA;
  20255. }
  20256. res = process_sdp(p, req, SDP_T38_NONE);
  20257. if (!req->ignore && p->owner) {
  20258. /* Queue a progress frame only if we have SDP in 180 or 182 */
  20259. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  20260. /* We have not sent progress, but we have been sent progress so enable early media */
  20261. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  20262. }
  20263. ast_rtp_instance_activate(p->rtp);
  20264. }
  20265. check_pendings(p);
  20266. break;
  20267. case 181: /* Call Is Being Forwarded */
  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. /* Store Route-set from provisional SIP responses so
  20271. * early-dialog request can be routed properly
  20272. * */
  20273. parse_ok_contact(p, req);
  20274. if (!reinvite) {
  20275. build_route(p, req, 1, resp);
  20276. }
  20277. if (!req->ignore && p->owner) {
  20278. struct ast_party_redirecting redirecting;
  20279. struct ast_set_party_redirecting update_redirecting;
  20280. ast_party_redirecting_init(&redirecting);
  20281. memset(&update_redirecting, 0, sizeof(update_redirecting));
  20282. change_redirecting_information(p, req, &redirecting, &update_redirecting,
  20283. FALSE);
  20284. /* Invalidate any earlier private redirecting id representations */
  20285. ast_set_party_id_all(&update_redirecting.priv_orig);
  20286. ast_set_party_id_all(&update_redirecting.priv_from);
  20287. ast_set_party_id_all(&update_redirecting.priv_to);
  20288. ast_channel_queue_redirecting_update(p->owner, &redirecting,
  20289. &update_redirecting);
  20290. ast_party_redirecting_free(&redirecting);
  20291. sip_handle_cc(p, req, AST_CC_CCNR);
  20292. }
  20293. check_pendings(p);
  20294. break;
  20295. case 183: /* Session progress */
  20296. if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p)) {
  20297. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  20298. }
  20299. /* Store Route-set from provisional SIP responses so
  20300. * early-dialog request can be routed properly
  20301. * */
  20302. parse_ok_contact(p, req);
  20303. if (!reinvite) {
  20304. build_route(p, req, 1, resp);
  20305. }
  20306. if (!req->ignore && p->owner) {
  20307. if (get_rpid(p, req)) {
  20308. /* Queue a connected line update */
  20309. ast_party_connected_line_init(&connected);
  20310. memset(&update_connected, 0, sizeof(update_connected));
  20311. update_connected.id.number = 1;
  20312. connected.id.number.valid = 1;
  20313. connected.id.number.str = (char *) p->cid_num;
  20314. connected.id.number.presentation = p->callingpres;
  20315. update_connected.id.name = 1;
  20316. connected.id.name.valid = 1;
  20317. connected.id.name.str = (char *) p->cid_name;
  20318. connected.id.name.presentation = p->callingpres;
  20319. /* Invalidate any earlier private connected id representation */
  20320. ast_set_party_id_all(&update_connected.priv);
  20321. connected.id.tag = (char *) p->cid_tag;
  20322. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  20323. ast_channel_queue_connected_line_update(p->owner, &connected,
  20324. &update_connected);
  20325. }
  20326. sip_handle_cc(p, req, AST_CC_CCNR);
  20327. }
  20328. if (find_sdp(req)) {
  20329. if (p->invitestate != INV_CANCELLED) {
  20330. p->invitestate = INV_EARLY_MEDIA;
  20331. }
  20332. res = process_sdp(p, req, SDP_T38_NONE);
  20333. if (!req->ignore && p->owner) {
  20334. /* Queue a progress frame */
  20335. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  20336. /* We have not sent progress, but we have been sent progress so enable early media */
  20337. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  20338. }
  20339. ast_rtp_instance_activate(p->rtp);
  20340. } else {
  20341. /* Alcatel PBXs are known to send 183s with no SDP after sending
  20342. * a 100 Trying response. We're just going to treat this sort of thing
  20343. * the same as we would treat a 180 Ringing
  20344. */
  20345. if (!req->ignore && p->owner) {
  20346. ast_queue_control(p->owner, AST_CONTROL_RINGING);
  20347. }
  20348. }
  20349. check_pendings(p);
  20350. break;
  20351. case 200: /* 200 OK on invite - someone's answering our call */
  20352. if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p)) {
  20353. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  20354. }
  20355. p->authtries = 0;
  20356. if (find_sdp(req)) {
  20357. if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore) {
  20358. if (!reinvite) {
  20359. /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
  20360. /* For re-invites, we try to recover */
  20361. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20362. p->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  20363. if (p->owner) {
  20364. ast_channel_hangupcause_set(p->owner, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  20365. sip_queue_hangup_cause(p, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  20366. }
  20367. }
  20368. }
  20369. ast_rtp_instance_activate(p->rtp);
  20370. } else if (!reinvite) {
  20371. struct ast_sockaddr remote_address = {{0,}};
  20372. ast_rtp_instance_get_remote_address(p->rtp, &remote_address);
  20373. if (ast_sockaddr_isnull(&remote_address) || (!ast_strlen_zero(p->theirprovtag) && strcmp(p->theirtag, p->theirprovtag))) {
  20374. ast_log(LOG_WARNING, "Received response: \"200 OK\" from '%s' without SDP\n", p->relatedpeer->name);
  20375. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20376. ast_rtp_instance_activate(p->rtp);
  20377. }
  20378. }
  20379. if (!req->ignore && p->owner) {
  20380. int rpid_changed;
  20381. rpid_changed = get_rpid(p, req);
  20382. if (rpid_changed || !reinvite) {
  20383. /* Queue a connected line update */
  20384. ast_party_connected_line_init(&connected);
  20385. memset(&update_connected, 0, sizeof(update_connected));
  20386. if (rpid_changed
  20387. || !ast_strlen_zero(p->cid_num)
  20388. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  20389. update_connected.id.number = 1;
  20390. connected.id.number.valid = 1;
  20391. connected.id.number.str = (char *) p->cid_num;
  20392. connected.id.number.presentation = p->callingpres;
  20393. }
  20394. if (rpid_changed
  20395. || !ast_strlen_zero(p->cid_name)
  20396. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  20397. update_connected.id.name = 1;
  20398. connected.id.name.valid = 1;
  20399. connected.id.name.str = (char *) p->cid_name;
  20400. connected.id.name.presentation = p->callingpres;
  20401. }
  20402. if (update_connected.id.number || update_connected.id.name) {
  20403. /* Invalidate any earlier private connected id representation */
  20404. ast_set_party_id_all(&update_connected.priv);
  20405. connected.id.tag = (char *) p->cid_tag;
  20406. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  20407. ast_channel_queue_connected_line_update(p->owner, &connected,
  20408. &update_connected);
  20409. }
  20410. }
  20411. }
  20412. /* Parse contact header for continued conversation */
  20413. /* When we get 200 OK, we know which device (and IP) to contact for this call */
  20414. /* This is important when we have a SIP proxy between us and the phone */
  20415. if (outgoing) {
  20416. update_call_counter(p, DEC_CALL_RINGING);
  20417. parse_ok_contact(p, req);
  20418. /* Save Record-Route for any later requests we make on this dialogue */
  20419. if (!reinvite) {
  20420. build_route(p, req, 1, resp);
  20421. }
  20422. if(set_address_from_contact(p)) {
  20423. /* Bad contact - we don't know how to reach this device */
  20424. /* We need to ACK, but then send a bye */
  20425. if (sip_route_empty(&p->route) && !req->ignore) {
  20426. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20427. }
  20428. }
  20429. }
  20430. if (!req->ignore && p->owner) {
  20431. if (!reinvite && !res) {
  20432. ast_queue_control(p->owner, AST_CONTROL_ANSWER);
  20433. } else { /* RE-invite */
  20434. if (p->t38.state == T38_DISABLED || p->t38.state == T38_REJECTED) {
  20435. ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
  20436. } else {
  20437. ast_queue_frame(p->owner, &ast_null_frame);
  20438. }
  20439. }
  20440. } else {
  20441. /* It's possible we're getting an 200 OK after we've tried to disconnect
  20442. by sending CANCEL */
  20443. /* First send ACK, then send bye */
  20444. if (!req->ignore) {
  20445. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20446. }
  20447. }
  20448. /* Check for Session-Timers related headers */
  20449. if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE) {
  20450. p_hdrval = (char*)sip_get_header(req, "Session-Expires");
  20451. if (!ast_strlen_zero(p_hdrval)) {
  20452. /* UAS supports Session-Timers */
  20453. enum st_refresher_param st_ref_param;
  20454. int tmp_st_interval = 0;
  20455. rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
  20456. if (rtn != 0) {
  20457. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20458. } else if (tmp_st_interval < st_get_se(p, FALSE)) {
  20459. ast_log(LOG_WARNING, "Got Session-Expires less than local Min-SE in 200 OK, tearing down call\n");
  20460. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  20461. }
  20462. if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
  20463. p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
  20464. } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
  20465. p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
  20466. } else {
  20467. ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
  20468. }
  20469. if (tmp_st_interval) {
  20470. p->stimer->st_interval = tmp_st_interval;
  20471. }
  20472. p->stimer->st_active = TRUE;
  20473. p->stimer->st_active_peer_ua = TRUE;
  20474. start_session_timer(p);
  20475. } else {
  20476. /* UAS doesn't support Session-Timers */
  20477. if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
  20478. p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
  20479. p->stimer->st_active_peer_ua = FALSE;
  20480. start_session_timer(p);
  20481. }
  20482. }
  20483. }
  20484. /* If I understand this right, the branch is different for a non-200 ACK only */
  20485. p->invitestate = INV_TERMINATED;
  20486. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  20487. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
  20488. check_pendings(p);
  20489. break;
  20490. case 407: /* Proxy authentication */
  20491. case 401: /* Www auth */
  20492. /* First we ACK */
  20493. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20494. if (p->options) {
  20495. p->options->auth_type = resp;
  20496. }
  20497. /* Then we AUTH */
  20498. ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
  20499. if (!req->ignore) {
  20500. if (p->authtries < MAX_AUTHTRIES) {
  20501. p->invitestate = INV_CALLING;
  20502. }
  20503. if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
  20504. ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", sip_get_header(&p->initreq, "From"));
  20505. pvt_set_needdestroy(p, "failed to authenticate on INVITE");
  20506. sip_alreadygone(p);
  20507. if (p->owner) {
  20508. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  20509. }
  20510. }
  20511. }
  20512. break;
  20513. case 403: /* Forbidden */
  20514. /* First we ACK */
  20515. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20516. ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", sip_get_header(&p->initreq, "From"));
  20517. if (!req->ignore && p->owner) {
  20518. sip_queue_hangup_cause(p, hangup_sip2cause(resp));
  20519. }
  20520. break;
  20521. case 404: /* Not found */
  20522. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20523. if (p->owner && !req->ignore) {
  20524. sip_queue_hangup_cause(p, hangup_sip2cause(resp));
  20525. }
  20526. break;
  20527. case 481: /* Call leg does not exist */
  20528. /* Could be REFER caused INVITE with replaces */
  20529. ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
  20530. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20531. if (p->owner) {
  20532. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  20533. }
  20534. break;
  20535. case 422: /* Session-Timers: Session interval too small */
  20536. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20537. ast_string_field_set(p, theirtag, NULL);
  20538. proc_422_rsp(p, req);
  20539. break;
  20540. case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
  20541. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20542. append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
  20543. ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
  20544. if (p->owner && !req->ignore) {
  20545. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  20546. }
  20547. break;
  20548. case 480: /* Temporarily unavailable. */
  20549. /* RFC 3261 encourages setting the reason phrase to something indicative
  20550. * of why the endpoint is not available. We will make this readable via the
  20551. * redirecting reason.
  20552. */
  20553. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20554. append_history(p, "TempUnavailable", "Endpoint is temporarily unavailable.");
  20555. if (p->owner && !req->ignore) {
  20556. struct ast_party_redirecting redirecting;
  20557. struct ast_set_party_redirecting update_redirecting;
  20558. ast_party_redirecting_set_init(&redirecting, ast_channel_redirecting(p->owner));
  20559. memset(&update_redirecting, 0, sizeof(update_redirecting));
  20560. redirecting.reason.code = sip_reason_str_to_code(rest);
  20561. redirecting.reason.str = ast_strdup(rest);
  20562. ast_channel_queue_redirecting_update(p->owner, &redirecting, &update_redirecting);
  20563. ast_party_redirecting_free(&redirecting);
  20564. ast_queue_control(p->owner, AST_CONTROL_BUSY);
  20565. }
  20566. break;
  20567. case 487: /* Cancelled transaction */
  20568. /* We have sent CANCEL on an outbound INVITE
  20569. This transaction is already scheduled to be killed by sip_hangup().
  20570. */
  20571. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20572. if (p->owner && !req->ignore) {
  20573. ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
  20574. append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
  20575. } else if (!req->ignore) {
  20576. update_call_counter(p, DEC_CALL_LIMIT);
  20577. append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
  20578. }
  20579. check_pendings(p);
  20580. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20581. break;
  20582. case 415: /* Unsupported media type */
  20583. case 488: /* Not acceptable here */
  20584. case 606: /* Not Acceptable */
  20585. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20586. if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
  20587. change_t38_state(p, T38_REJECTED);
  20588. /* Try to reset RTP timers */
  20589. /* XXX Why is this commented away??? */
  20590. //ast_rtp_set_rtptimers_onhold(p->rtp);
  20591. /* Trigger a reinvite back to audio */
  20592. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  20593. } else {
  20594. /* We can't set up this call, so give up */
  20595. if (p->owner && !req->ignore) {
  20596. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  20597. }
  20598. }
  20599. break;
  20600. case 491: /* Pending */
  20601. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20602. if (p->owner && !req->ignore) {
  20603. if (ast_channel_state(p->owner) != AST_STATE_UP) {
  20604. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  20605. } else {
  20606. /* This is a re-invite that failed. */
  20607. /* Reset the flag after a while
  20608. */
  20609. int wait;
  20610. /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
  20611. * if not owner of call, wait 0 to 2 seconds */
  20612. if (p->outgoing_call) {
  20613. wait = 2100 + ast_random() % 2000;
  20614. } else {
  20615. wait = ast_random() % 2000;
  20616. }
  20617. 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."));
  20618. ast_debug(2, "Reinvite race. Scheduled sip_reinvite_retry in %d secs in handle_response_invite (waitid %d, dialog '%s')\n",
  20619. wait, p->waitid, p->callid);
  20620. }
  20621. }
  20622. break;
  20623. case 408: /* Request timeout */
  20624. case 405: /* Not allowed */
  20625. case 501: /* Not implemented */
  20626. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  20627. if (p->owner) {
  20628. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  20629. }
  20630. break;
  20631. }
  20632. if (xmitres == XMIT_ERROR) {
  20633. ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
  20634. }
  20635. }
  20636. /* \brief Handle SIP response in NOTIFY transaction
  20637. We've sent a NOTIFY, now handle responses to it
  20638. */
  20639. static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20640. {
  20641. switch (resp) {
  20642. case 200: /* Notify accepted */
  20643. /* They got the notify, this is the end */
  20644. if (p->owner) {
  20645. if (p->refer) {
  20646. ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
  20647. } else {
  20648. ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", ast_channel_name(p->owner));
  20649. }
  20650. } else {
  20651. if (p->subscribed == NONE && !p->refer) {
  20652. ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
  20653. pvt_set_needdestroy(p, "received 200 response");
  20654. }
  20655. if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
  20656. struct state_notify_data data = {
  20657. .state = p->laststate,
  20658. .device_state_info = p->last_device_state_info,
  20659. .presence_state = p->last_presence_state,
  20660. .presence_subtype = p->last_presence_subtype,
  20661. .presence_message = p->last_presence_message,
  20662. };
  20663. /* Ready to send the next state we have on queue */
  20664. ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
  20665. extensionstate_update(p->context, p->exten, &data, p, TRUE);
  20666. }
  20667. }
  20668. break;
  20669. case 401: /* Not www-authorized on SIP method */
  20670. case 407: /* Proxy auth */
  20671. if (!p->notify) {
  20672. break; /* Only device notify can use NOTIFY auth */
  20673. }
  20674. ast_string_field_set(p, theirtag, NULL);
  20675. if (ast_strlen_zero(p->authname)) {
  20676. 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));
  20677. pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
  20678. }
  20679. if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
  20680. ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", sip_get_header(&p->initreq, "From"));
  20681. pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
  20682. }
  20683. break;
  20684. case 481: /* Call leg does not exist */
  20685. pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
  20686. break;
  20687. }
  20688. }
  20689. /* \brief Handle SIP response in SUBSCRIBE transaction */
  20690. static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20691. {
  20692. if (p->subscribed == CALL_COMPLETION) {
  20693. struct sip_monitor_instance *monitor_instance;
  20694. if (resp < 300) {
  20695. return;
  20696. }
  20697. /* Final failure response received. */
  20698. monitor_instance = ao2_callback(sip_monitor_instances, 0,
  20699. find_sip_monitor_instance_by_subscription_pvt, p);
  20700. if (monitor_instance) {
  20701. ast_cc_monitor_failed(monitor_instance->core_id,
  20702. monitor_instance->device_name,
  20703. "Received error response to our SUBSCRIBE");
  20704. }
  20705. return;
  20706. }
  20707. if (p->subscribed != MWI_NOTIFICATION) {
  20708. return;
  20709. }
  20710. if (!p->mwi) {
  20711. return;
  20712. }
  20713. switch (resp) {
  20714. case 200: /* Subscription accepted */
  20715. ast_debug(3, "Got 200 OK on subscription for MWI\n");
  20716. set_pvt_allowed_methods(p, req);
  20717. if (p->options) {
  20718. if (p->options->outboundproxy) {
  20719. ao2_ref(p->options->outboundproxy, -1);
  20720. }
  20721. ast_free(p->options);
  20722. p->options = NULL;
  20723. }
  20724. p->mwi->subscribed = 1;
  20725. 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) {
  20726. ao2_t_ref(p->mwi, -1, "mwi ast_sched_add < 0");
  20727. }
  20728. break;
  20729. case 401:
  20730. case 407:
  20731. ast_string_field_set(p, theirtag, NULL);
  20732. if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
  20733. ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", sip_get_header(&p->initreq, "From"));
  20734. p->mwi->call = NULL;
  20735. ao2_t_ref(p->mwi, -1, "failed to authenticate SUBSCRIBE");
  20736. pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
  20737. }
  20738. break;
  20739. case 403:
  20740. transmit_response_with_date(p, "200 OK", req);
  20741. ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
  20742. p->mwi->call = NULL;
  20743. ao2_t_ref(p->mwi, -1, "received 403 response");
  20744. pvt_set_needdestroy(p, "received 403 response");
  20745. sip_alreadygone(p);
  20746. break;
  20747. case 404:
  20748. ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
  20749. p->mwi->call = NULL;
  20750. ao2_t_ref(p->mwi, -1, "received 404 response");
  20751. pvt_set_needdestroy(p, "received 404 response");
  20752. break;
  20753. case 481:
  20754. ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
  20755. p->mwi->call = NULL;
  20756. ao2_t_ref(p->mwi, -1, "received 481 response");
  20757. pvt_set_needdestroy(p, "received 481 response");
  20758. break;
  20759. case 500:
  20760. case 501:
  20761. ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
  20762. p->mwi->call = NULL;
  20763. ao2_t_ref(p->mwi, -1, "received 500/501 response");
  20764. pvt_set_needdestroy(p, "received 500/501 response");
  20765. break;
  20766. }
  20767. }
  20768. /* \brief Handle SIP response in REFER transaction
  20769. We've sent a REFER, now handle responses to it
  20770. */
  20771. static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20772. {
  20773. enum ast_control_transfer message = AST_TRANSFER_FAILED;
  20774. /* If no refer structure exists, then do nothing */
  20775. if (!p->refer)
  20776. return;
  20777. switch (resp) {
  20778. case 202: /* Transfer accepted */
  20779. /* We need to do something here */
  20780. /* The transferee is now sending INVITE to target */
  20781. p->refer->status = REFER_ACCEPTED;
  20782. /* Now wait for next message */
  20783. ast_debug(3, "Got 202 accepted on transfer\n");
  20784. /* We should hang along, waiting for NOTIFY's here */
  20785. break;
  20786. case 401: /* Not www-authorized on SIP method */
  20787. case 407: /* Proxy auth */
  20788. if (ast_strlen_zero(p->authname)) {
  20789. ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
  20790. ast_sockaddr_stringify(&p->recv));
  20791. if (p->owner) {
  20792. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20793. }
  20794. pvt_set_needdestroy(p, "unable to authenticate REFER");
  20795. }
  20796. if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
  20797. ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", sip_get_header(&p->initreq, "From"));
  20798. p->refer->status = REFER_NOAUTH;
  20799. if (p->owner) {
  20800. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20801. }
  20802. pvt_set_needdestroy(p, "failed to authenticate REFER");
  20803. }
  20804. break;
  20805. case 405: /* Method not allowed */
  20806. /* Return to the current call onhold */
  20807. /* Status flag needed to be reset */
  20808. ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
  20809. pvt_set_needdestroy(p, "received 405 response");
  20810. p->refer->status = REFER_FAILED;
  20811. if (p->owner) {
  20812. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20813. }
  20814. break;
  20815. case 481: /* Call leg does not exist */
  20816. /* A transfer with Replaces did not work */
  20817. /* OEJ: We should Set flag, cancel the REFER, go back
  20818. to original call - but right now we can't */
  20819. ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
  20820. if (p->owner)
  20821. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  20822. pvt_set_needdestroy(p, "received 481 response");
  20823. break;
  20824. case 500: /* Server error */
  20825. case 501: /* Method not implemented */
  20826. /* Return to the current call onhold */
  20827. /* Status flag needed to be reset */
  20828. ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
  20829. pvt_set_needdestroy(p, "received 500/501 response");
  20830. p->refer->status = REFER_FAILED;
  20831. if (p->owner) {
  20832. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20833. }
  20834. break;
  20835. case 603: /* Transfer declined */
  20836. ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
  20837. p->refer->status = REFER_FAILED;
  20838. pvt_set_needdestroy(p, "received 603 response");
  20839. if (p->owner) {
  20840. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20841. }
  20842. break;
  20843. default:
  20844. /* We should treat unrecognized 9xx as 900. 400 is actually
  20845. specified as a possible response, but any 4-6xx is
  20846. theoretically possible. */
  20847. if (resp < 299) { /* 1xx cases don't get here */
  20848. ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
  20849. } else {
  20850. ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
  20851. }
  20852. p->refer->status = REFER_FAILED;
  20853. pvt_set_needdestroy(p, "received failure response");
  20854. if (p->owner) {
  20855. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20856. }
  20857. break;
  20858. }
  20859. }
  20860. /*! \brief Handle responses on REGISTER to services */
  20861. static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  20862. {
  20863. int expires, expires_ms;
  20864. struct sip_registry *r;
  20865. r = p->registry;
  20866. switch (resp) {
  20867. case 401: /* Unauthorized */
  20868. if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
  20869. ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
  20870. pvt_set_needdestroy(p, "failed to authenticate REGISTER");
  20871. }
  20872. break;
  20873. case 403: /* Forbidden */
  20874. if (global_reg_retry_403) {
  20875. ast_log(LOG_NOTICE, "Treating 403 response to REGISTER as non-fatal for %s@%s\n",
  20876. p->registry->username, p->registry->hostname);
  20877. ast_string_field_set(r, nonce, "");
  20878. ast_string_field_set(p, nonce, "");
  20879. break;
  20880. }
  20881. ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
  20882. AST_SCHED_DEL_UNREF(sched, r->timeout, ao2_t_ref(r, -1, "reg ptr unref from handle_response_register 403"));
  20883. r->regstate = REG_STATE_NOAUTH;
  20884. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  20885. pvt_set_needdestroy(p, "received 403 response");
  20886. break;
  20887. case 404: /* Not found */
  20888. ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
  20889. pvt_set_needdestroy(p, "received 404 response");
  20890. if (r->call)
  20891. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
  20892. r->regstate = REG_STATE_REJECTED;
  20893. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  20894. AST_SCHED_DEL_UNREF(sched, r->timeout, ao2_t_ref(r, -1, "reg ptr unref from handle_response_register 404"));
  20895. break;
  20896. case 407: /* Proxy auth */
  20897. if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
  20898. ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", sip_get_header(&p->initreq, "From"), p->authtries);
  20899. pvt_set_needdestroy(p, "failed to authenticate REGISTER");
  20900. }
  20901. break;
  20902. case 408: /* Request timeout */
  20903. /* Got a timeout response, so reset the counter of failed responses */
  20904. if (r) {
  20905. r->regattempts = 0;
  20906. } else {
  20907. ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
  20908. }
  20909. break;
  20910. case 423: /* Interval too brief */
  20911. r->expiry = atoi(sip_get_header(req, "Min-Expires"));
  20912. 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);
  20913. AST_SCHED_DEL_UNREF(sched, r->timeout, ao2_t_ref(r, -1, "reg ptr unref from handle_response_register 423"));
  20914. if (r->call) {
  20915. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
  20916. pvt_set_needdestroy(p, "received 423 response");
  20917. }
  20918. if (r->expiry > max_expiry) {
  20919. ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
  20920. r->expiry = r->configured_expiry;
  20921. r->regstate = REG_STATE_REJECTED;
  20922. } else {
  20923. r->regstate = REG_STATE_UNREGISTERED;
  20924. transmit_register(r, SIP_REGISTER, NULL, NULL);
  20925. }
  20926. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  20927. break;
  20928. case 479: /* SER: Not able to process the URI - address is wrong in register*/
  20929. ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
  20930. pvt_set_needdestroy(p, "received 479 response");
  20931. if (r->call)
  20932. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
  20933. r->regstate = REG_STATE_REJECTED;
  20934. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  20935. AST_SCHED_DEL_UNREF(sched, r->timeout, ao2_t_ref(r, -1, "reg ptr unref from handle_response_register 479"));
  20936. break;
  20937. case 200: /* 200 OK */
  20938. if (!r) {
  20939. 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));
  20940. pvt_set_needdestroy(p, "received erroneous 200 response");
  20941. return 0;
  20942. }
  20943. r->regstate = REG_STATE_REGISTERED;
  20944. r->regtime = ast_tvnow(); /* Reset time of last successful registration */
  20945. sip_publish_registry(r->username, r->hostname, regstate2str(r->regstate));
  20946. r->regattempts = 0;
  20947. ast_debug(1, "Registration successful\n");
  20948. if (r->timeout > -1) {
  20949. ast_debug(1, "Cancelling timeout %d\n", r->timeout);
  20950. }
  20951. AST_SCHED_DEL_UNREF(sched, r->timeout, ao2_t_ref(r, -1, "reg ptr unref from handle_response_register 200"));
  20952. if (r->call)
  20953. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
  20954. ao2_t_replace(p->registry, NULL, "unref registry entry p->registry");
  20955. /* destroy dialog now to avoid interference with next register */
  20956. pvt_set_needdestroy(p, "Registration successfull");
  20957. /* set us up for re-registering
  20958. * figure out how long we got registered for
  20959. * according to section 6.13 of RFC, contact headers override
  20960. * expires headers, so check those first */
  20961. expires = 0;
  20962. /* XXX todo: try to save the extra call */
  20963. if (!ast_strlen_zero(sip_get_header(req, "Contact"))) {
  20964. const char *contact = NULL;
  20965. const char *tmptmp = NULL;
  20966. int start = 0;
  20967. for(;;) {
  20968. contact = __get_header(req, "Contact", &start);
  20969. /* this loop ensures we get a contact header about our register request */
  20970. if(!ast_strlen_zero(contact)) {
  20971. if( (tmptmp=strstr(contact, p->our_contact))) {
  20972. contact=tmptmp;
  20973. break;
  20974. }
  20975. } else
  20976. break;
  20977. }
  20978. tmptmp = strcasestr(contact, "expires=");
  20979. if (tmptmp) {
  20980. if (sscanf(tmptmp + 8, "%30d", &expires) != 1) {
  20981. expires = 0;
  20982. }
  20983. }
  20984. }
  20985. if (!expires)
  20986. expires=atoi(sip_get_header(req, "expires"));
  20987. if (!expires)
  20988. expires=default_expiry;
  20989. expires_ms = expires * 1000;
  20990. if (expires <= EXPIRY_GUARD_LIMIT)
  20991. expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
  20992. else
  20993. expires_ms -= EXPIRY_GUARD_SECS * 1000;
  20994. if (sipdebug)
  20995. ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
  20996. r->refresh= (int) expires_ms / 1000;
  20997. /* Schedule re-registration before we expire */
  20998. AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
  20999. ao2_t_ref(_data, -1, "unref in REPLACE del fail"),
  21000. ao2_t_ref(r, -1, "unref in REPLACE add fail"),
  21001. ao2_t_ref(r, +1, "The Addition side of REPLACE"));
  21002. }
  21003. return 1;
  21004. }
  21005. /*! \brief Handle qualification responses (OPTIONS) */
  21006. static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
  21007. {
  21008. 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! */
  21009. int statechanged, is_reachable, was_reachable;
  21010. int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
  21011. /*
  21012. * Compute the response time to a ping (goes in peer->lastms.)
  21013. * -1 means did not respond, 0 means unknown,
  21014. * 1..maxms is a valid response, >maxms means late response.
  21015. */
  21016. if (pingtime < 1) { /* zero = unknown, so round up to 1 */
  21017. pingtime = 1;
  21018. }
  21019. if (!peer->maxms) { /* this should never happens */
  21020. pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
  21021. return;
  21022. }
  21023. /* Now determine new state and whether it has changed.
  21024. * Use some helper variables to simplify the writing
  21025. * of the expressions.
  21026. */
  21027. was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
  21028. is_reachable = pingtime <= peer->maxms;
  21029. statechanged = peer->lastms == 0 /* yes, unknown before */
  21030. || was_reachable != is_reachable;
  21031. peer->lastms = pingtime;
  21032. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  21033. if (statechanged) {
  21034. const char *s = is_reachable ? "Reachable" : "Lagged";
  21035. char str_lastms[20];
  21036. snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
  21037. ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
  21038. peer->name, s, pingtime, peer->maxms);
  21039. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  21040. if (sip_cfg.peer_rtupdate) {
  21041. ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
  21042. }
  21043. if (peer->endpoint) {
  21044. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  21045. ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_ONLINE);
  21046. blob = ast_json_pack("{s: s, s: i}",
  21047. "peer_status", s,
  21048. "time", pingtime);
  21049. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  21050. }
  21051. if (is_reachable && sip_cfg.regextenonqualify) {
  21052. register_peer_exten(peer, TRUE);
  21053. }
  21054. }
  21055. pvt_set_needdestroy(p, "got OPTIONS response");
  21056. /* Try again eventually */
  21057. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
  21058. is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
  21059. sip_poke_peer_s, peer,
  21060. sip_unref_peer(_data, "removing poke peer ref"),
  21061. sip_unref_peer(peer, "removing poke peer ref"),
  21062. sip_ref_peer(peer, "adding poke peer ref"));
  21063. }
  21064. /*!
  21065. * \internal
  21066. * \brief Handle responses to INFO messages
  21067. *
  21068. * \note The INFO method MUST NOT change the state of calls or
  21069. * related sessions (RFC 2976).
  21070. */
  21071. static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  21072. {
  21073. int sipmethod = SIP_INFO;
  21074. switch (resp) {
  21075. case 401: /* Not www-authorized on SIP method */
  21076. case 407: /* Proxy auth required */
  21077. ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
  21078. ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
  21079. break;
  21080. case 405: /* Method not allowed */
  21081. case 501: /* Not Implemented */
  21082. mark_method_unallowed(&p->allowed_methods, sipmethod);
  21083. if (p->relatedpeer) {
  21084. mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
  21085. }
  21086. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
  21087. ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
  21088. break;
  21089. default:
  21090. if (300 <= resp && resp < 700) {
  21091. ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
  21092. sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
  21093. }
  21094. break;
  21095. }
  21096. }
  21097. /*!
  21098. * \internal
  21099. * \brief Handle auth requests to a MESSAGE request
  21100. * \return TRUE if authentication failed.
  21101. */
  21102. static int do_message_auth(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  21103. {
  21104. char *header;
  21105. char *respheader;
  21106. char digest[1024];
  21107. if (p->options) {
  21108. p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
  21109. }
  21110. if (p->authtries == MAX_AUTHTRIES) {
  21111. ast_log(LOG_NOTICE, "Failed to authenticate MESSAGE with host '%s'\n",
  21112. ast_sockaddr_stringify(&p->sa));
  21113. return -1;
  21114. }
  21115. ++p->authtries;
  21116. sip_auth_headers((resp == 401 ? WWW_AUTH : PROXY_AUTH), &header, &respheader);
  21117. memset(digest, 0, sizeof(digest));
  21118. if (reply_digest(p, req, header, SIP_MESSAGE, digest, sizeof(digest))) {
  21119. /* There's nothing to use for authentication */
  21120. ast_debug(1, "Nothing to use for MESSAGE authentication\n");
  21121. return -1;
  21122. }
  21123. if (p->do_history) {
  21124. append_history(p, "MessageAuth", "Try: %d", p->authtries);
  21125. }
  21126. transmit_message(p, 0, 1);
  21127. return 0;
  21128. }
  21129. /*!
  21130. * \internal
  21131. * \brief Handle responses to MESSAGE messages
  21132. *
  21133. * \note The MESSAGE method should not change the state of calls
  21134. * or related sessions if associated with a dialog. (Implied by
  21135. * RFC 3428 Section 2).
  21136. */
  21137. static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  21138. {
  21139. int sipmethod = SIP_MESSAGE;
  21140. int in_dialog = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  21141. switch (resp) {
  21142. case 401: /* Not www-authorized on SIP method */
  21143. case 407: /* Proxy auth required */
  21144. if (do_message_auth(p, resp, rest, req, seqno) && !in_dialog) {
  21145. pvt_set_needdestroy(p, "MESSAGE authentication failed");
  21146. }
  21147. break;
  21148. case 405: /* Method not allowed */
  21149. case 501: /* Not Implemented */
  21150. mark_method_unallowed(&p->allowed_methods, sipmethod);
  21151. if (p->relatedpeer) {
  21152. mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
  21153. }
  21154. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
  21155. ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
  21156. if (!in_dialog) {
  21157. pvt_set_needdestroy(p, "MESSAGE not implemented or allowed");
  21158. }
  21159. break;
  21160. default:
  21161. if (100 <= resp && resp < 200) {
  21162. /* Must allow provisional responses for out-of-dialog requests. */
  21163. } else if (200 <= resp && resp < 300) {
  21164. p->authtries = 0; /* Reset authentication counter */
  21165. if (!in_dialog) {
  21166. pvt_set_needdestroy(p, "MESSAGE delivery accepted");
  21167. }
  21168. } else if (300 <= resp && resp < 700) {
  21169. ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
  21170. sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
  21171. if (!in_dialog) {
  21172. pvt_set_needdestroy(p, (300 <= resp && resp < 600)
  21173. ? "MESSAGE delivery failed" : "MESSAGE delivery refused");
  21174. }
  21175. }
  21176. break;
  21177. }
  21178. }
  21179. /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
  21180. static void stop_media_flows(struct sip_pvt *p)
  21181. {
  21182. /* Immediately stop RTP, VRTP and UDPTL as applicable */
  21183. if (p->rtp)
  21184. ast_rtp_instance_stop(p->rtp);
  21185. if (p->vrtp)
  21186. ast_rtp_instance_stop(p->vrtp);
  21187. if (p->trtp)
  21188. ast_rtp_instance_stop(p->trtp);
  21189. if (p->udptl)
  21190. ast_udptl_stop(p->udptl);
  21191. }
  21192. /*! \brief Handle SIP response in dialogue
  21193. \note only called by handle_incoming */
  21194. static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  21195. {
  21196. struct ast_channel *owner;
  21197. int sipmethod;
  21198. const char *c = sip_get_header(req, "Cseq");
  21199. /* 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 */
  21200. char *c_copy = ast_strdupa(c);
  21201. /* Skip the Cseq and its subsequent spaces */
  21202. const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
  21203. if (!msg)
  21204. msg = "";
  21205. sipmethod = find_sip_method(msg);
  21206. owner = p->owner;
  21207. if (owner) {
  21208. const char *rp = NULL, *rh = NULL;
  21209. ast_channel_hangupcause_set(owner, 0);
  21210. if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = sip_get_header(req, "Reason"))) {
  21211. rh = ast_skip_blanks(rh);
  21212. if (!strncasecmp(rh, "Q.850", 5)) {
  21213. int cause = ast_channel_hangupcause(owner);
  21214. rp = strstr(rh, "cause=");
  21215. if (rp && sscanf(rp + 6, "%30d", &cause) == 1) {
  21216. ast_channel_hangupcause_set(owner, cause & 0x7f);
  21217. if (req->debug)
  21218. ast_verbose("Using Reason header for cause code: %d\n", ast_channel_hangupcause(owner));
  21219. }
  21220. }
  21221. }
  21222. if (!ast_channel_hangupcause(owner))
  21223. ast_channel_hangupcause_set(owner, hangup_sip2cause(resp));
  21224. }
  21225. if (p->socket.type == AST_TRANSPORT_UDP) {
  21226. int ack_res = FALSE;
  21227. /* Acknowledge whatever it is destined for */
  21228. if ((resp >= 100) && (resp <= 199)) {
  21229. /* NON-INVITE messages do not ack a 1XX response. RFC 3261 section 17.1.2.2 */
  21230. if (sipmethod == SIP_INVITE) {
  21231. ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
  21232. }
  21233. } else {
  21234. ack_res = __sip_ack(p, seqno, 0, sipmethod);
  21235. }
  21236. if (ack_res == FALSE) {
  21237. /* RFC 3261 13.2.2.4 and 17.1.1.2 - We must re-send ACKs to re-transmitted final responses */
  21238. if (sipmethod == SIP_INVITE && resp >= 200) {
  21239. transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
  21240. }
  21241. append_history(p, "Ignore", "Ignoring this retransmit\n");
  21242. return;
  21243. }
  21244. }
  21245. /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
  21246. if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
  21247. p->pendinginvite = 0;
  21248. }
  21249. /* Get their tag if we haven't already */
  21250. if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
  21251. char tag[128];
  21252. gettag(req, "To", tag, sizeof(tag));
  21253. ast_string_field_set(p, theirtag, tag);
  21254. } else {
  21255. /* Store theirtag to track for changes when 200 responses to invites are received without SDP */
  21256. ast_string_field_set(p, theirprovtag, p->theirtag);
  21257. }
  21258. /* This needs to be configurable on a channel/peer level,
  21259. not mandatory for all communication. Sadly enough, NAT implementations
  21260. are not so stable so we can always rely on these headers.
  21261. Temporarily disabled, while waiting for fix.
  21262. Fix assigned to Rizzo :-)
  21263. */
  21264. /* check_via_response(p, req); */
  21265. /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
  21266. * in response to a BYE, then we should end the current dialog
  21267. * and session. It is known that at least one phone manufacturer
  21268. * potentially will send a 404 in response to a BYE, so we'll be
  21269. * liberal in what we accept and end the dialog and session if we
  21270. * receive any of those responses to a BYE.
  21271. */
  21272. if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
  21273. pvt_set_needdestroy(p, "received 4XX response to a BYE");
  21274. return;
  21275. }
  21276. if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
  21277. /* We don't really care what the response is, just that it replied back.
  21278. Well, as long as it's not a 100 response... since we might
  21279. need to hang around for something more "definitive" */
  21280. if (resp != 100)
  21281. handle_response_peerpoke(p, resp, req);
  21282. } else if (sipmethod == SIP_REFER && resp >= 200) {
  21283. handle_response_refer(p, resp, rest, req, seqno);
  21284. } else if (sipmethod == SIP_PUBLISH) {
  21285. /* SIP PUBLISH transcends this morass of doodoo and instead
  21286. * we just always call the response handler. Good gravy!
  21287. */
  21288. handle_response_publish(p, resp, rest, req, seqno);
  21289. } else if (sipmethod == SIP_INFO) {
  21290. /* More good gravy! */
  21291. handle_response_info(p, resp, rest, req, seqno);
  21292. } else if (sipmethod == SIP_MESSAGE) {
  21293. /* More good gravy! */
  21294. handle_response_message(p, resp, rest, req, seqno);
  21295. } else if (sipmethod == SIP_NOTIFY) {
  21296. /* The gravy train continues to roll */
  21297. handle_response_notify(p, resp, rest, req, seqno);
  21298. } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  21299. switch(resp) {
  21300. case 100: /* 100 Trying */
  21301. case 101: /* 101 Dialog establishment */
  21302. case 183: /* 183 Session Progress */
  21303. case 180: /* 180 Ringing */
  21304. case 182: /* 182 Queued */
  21305. case 181: /* 181 Call Is Being Forwarded */
  21306. if (sipmethod == SIP_INVITE)
  21307. handle_response_invite(p, resp, rest, req, seqno);
  21308. break;
  21309. case 200: /* 200 OK */
  21310. p->authtries = 0; /* Reset authentication counter */
  21311. if (sipmethod == SIP_INVITE) {
  21312. handle_response_invite(p, resp, rest, req, seqno);
  21313. } else if (sipmethod == SIP_REGISTER) {
  21314. handle_response_register(p, resp, rest, req, seqno);
  21315. } else if (sipmethod == SIP_SUBSCRIBE) {
  21316. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  21317. handle_response_subscribe(p, resp, rest, req, seqno);
  21318. } else if (sipmethod == SIP_BYE) { /* Ok, we're ready to go */
  21319. pvt_set_needdestroy(p, "received 200 response");
  21320. ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  21321. }
  21322. break;
  21323. case 401: /* Not www-authorized on SIP method */
  21324. case 407: /* Proxy auth required */
  21325. if (sipmethod == SIP_INVITE)
  21326. handle_response_invite(p, resp, rest, req, seqno);
  21327. else if (sipmethod == SIP_SUBSCRIBE)
  21328. handle_response_subscribe(p, resp, rest, req, seqno);
  21329. else if (p->registry && sipmethod == SIP_REGISTER)
  21330. handle_response_register(p, resp, rest, req, seqno);
  21331. else if (sipmethod == SIP_UPDATE) {
  21332. handle_response_update(p, resp, rest, req, seqno);
  21333. } else if (sipmethod == SIP_BYE) {
  21334. if (p->options)
  21335. p->options->auth_type = resp;
  21336. if (ast_strlen_zero(p->authname)) {
  21337. ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
  21338. msg, ast_sockaddr_stringify(&p->recv));
  21339. pvt_set_needdestroy(p, "unable to authenticate BYE");
  21340. } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
  21341. ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, sip_get_header(&p->initreq, "From"));
  21342. pvt_set_needdestroy(p, "failed to authenticate BYE");
  21343. }
  21344. } else {
  21345. ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, sip_get_header(req, "To"));
  21346. pvt_set_needdestroy(p, "received 407 response");
  21347. }
  21348. break;
  21349. case 403: /* Forbidden - we failed authentication */
  21350. if (sipmethod == SIP_INVITE)
  21351. handle_response_invite(p, resp, rest, req, seqno);
  21352. else if (sipmethod == SIP_SUBSCRIBE)
  21353. handle_response_subscribe(p, resp, rest, req, seqno);
  21354. else if (p->registry && sipmethod == SIP_REGISTER)
  21355. handle_response_register(p, resp, rest, req, seqno);
  21356. else {
  21357. ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
  21358. pvt_set_needdestroy(p, "received 403 response");
  21359. }
  21360. break;
  21361. case 404: /* Not found */
  21362. if (p->registry && sipmethod == SIP_REGISTER)
  21363. handle_response_register(p, resp, rest, req, seqno);
  21364. else if (sipmethod == SIP_INVITE)
  21365. handle_response_invite(p, resp, rest, req, seqno);
  21366. else if (sipmethod == SIP_SUBSCRIBE)
  21367. handle_response_subscribe(p, resp, rest, req, seqno);
  21368. else if (owner)
  21369. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  21370. break;
  21371. case 423: /* Interval too brief */
  21372. if (sipmethod == SIP_REGISTER)
  21373. handle_response_register(p, resp, rest, req, seqno);
  21374. break;
  21375. case 408: /* Request timeout - terminate dialog */
  21376. if (sipmethod == SIP_INVITE)
  21377. handle_response_invite(p, resp, rest, req, seqno);
  21378. else if (sipmethod == SIP_REGISTER)
  21379. handle_response_register(p, resp, rest, req, seqno);
  21380. else if (sipmethod == SIP_BYE) {
  21381. pvt_set_needdestroy(p, "received 408 response");
  21382. ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
  21383. } else {
  21384. if (owner)
  21385. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  21386. pvt_set_needdestroy(p, "received 408 response");
  21387. }
  21388. break;
  21389. case 428:
  21390. case 422: /* Session-Timers: Session Interval Too Small */
  21391. if (sipmethod == SIP_INVITE) {
  21392. handle_response_invite(p, resp, rest, req, seqno);
  21393. }
  21394. break;
  21395. case 480:
  21396. if (sipmethod == SIP_INVITE) {
  21397. handle_response_invite(p, resp, rest, req, seqno);
  21398. } else if (sipmethod == SIP_SUBSCRIBE) {
  21399. handle_response_subscribe(p, resp, rest, req, seqno);
  21400. } else if (owner) {
  21401. /* No specific handler. Default to congestion */
  21402. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  21403. }
  21404. break;
  21405. case 481: /* Call leg does not exist */
  21406. if (sipmethod == SIP_INVITE) {
  21407. handle_response_invite(p, resp, rest, req, seqno);
  21408. } else if (sipmethod == SIP_SUBSCRIBE) {
  21409. handle_response_subscribe(p, resp, rest, req, seqno);
  21410. } else if (sipmethod == SIP_BYE) {
  21411. /* The other side has no transaction to bye,
  21412. just assume it's all right then */
  21413. ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
  21414. } else if (sipmethod == SIP_CANCEL) {
  21415. /* The other side has no transaction to cancel,
  21416. just assume it's all right then */
  21417. ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
  21418. } else {
  21419. ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
  21420. /* Guessing that this is not an important request */
  21421. }
  21422. break;
  21423. case 487:
  21424. if (sipmethod == SIP_INVITE)
  21425. handle_response_invite(p, resp, rest, req, seqno);
  21426. break;
  21427. case 415: /* Unsupported media type */
  21428. case 488: /* Not acceptable here - codec error */
  21429. case 606: /* Not Acceptable */
  21430. if (sipmethod == SIP_INVITE)
  21431. handle_response_invite(p, resp, rest, req, seqno);
  21432. break;
  21433. case 491: /* Pending */
  21434. if (sipmethod == SIP_INVITE)
  21435. handle_response_invite(p, resp, rest, req, seqno);
  21436. else {
  21437. ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
  21438. pvt_set_needdestroy(p, "received 491 response");
  21439. }
  21440. break;
  21441. case 405: /* Method not allowed */
  21442. case 501: /* Not Implemented */
  21443. mark_method_unallowed(&p->allowed_methods, sipmethod);
  21444. if (p->relatedpeer) {
  21445. mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
  21446. }
  21447. if (sipmethod == SIP_INVITE)
  21448. handle_response_invite(p, resp, rest, req, seqno);
  21449. else
  21450. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
  21451. break;
  21452. default:
  21453. if ((resp >= 200) && (resp < 300)) { /* on any 2XX response do the following */
  21454. if (sipmethod == SIP_INVITE) {
  21455. handle_response_invite(p, resp, rest, req, seqno);
  21456. }
  21457. } else if ((resp >= 300) && (resp < 700)) {
  21458. /* Fatal response */
  21459. if ((resp != 487))
  21460. ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
  21461. if (sipmethod == SIP_INVITE)
  21462. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  21463. /* XXX Locking issues?? XXX */
  21464. switch(resp) {
  21465. case 300: /* Multiple Choices */
  21466. case 301: /* Moved permanently */
  21467. case 302: /* Moved temporarily */
  21468. case 305: /* Use Proxy */
  21469. if (p->owner) {
  21470. struct ast_party_redirecting redirecting;
  21471. struct ast_set_party_redirecting update_redirecting;
  21472. ast_party_redirecting_init(&redirecting);
  21473. memset(&update_redirecting, 0, sizeof(update_redirecting));
  21474. change_redirecting_information(p, req, &redirecting,
  21475. &update_redirecting, TRUE);
  21476. ast_channel_set_redirecting(p->owner, &redirecting,
  21477. &update_redirecting);
  21478. ast_party_redirecting_free(&redirecting);
  21479. }
  21480. /* Fall through */
  21481. case 486: /* Busy here */
  21482. case 600: /* Busy everywhere */
  21483. case 603: /* Decline */
  21484. if (p->owner) {
  21485. sip_handle_cc(p, req, AST_CC_CCBS);
  21486. ast_queue_control(p->owner, AST_CONTROL_BUSY);
  21487. }
  21488. break;
  21489. case 482: /* Loop Detected */
  21490. case 404: /* Not Found */
  21491. case 410: /* Gone */
  21492. case 400: /* Bad Request */
  21493. case 500: /* Server error */
  21494. if (sipmethod == SIP_SUBSCRIBE) {
  21495. handle_response_subscribe(p, resp, rest, req, seqno);
  21496. break;
  21497. }
  21498. /* Fall through */
  21499. case 502: /* Bad gateway */
  21500. case 503: /* Service Unavailable */
  21501. case 504: /* Server Timeout */
  21502. if (owner)
  21503. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  21504. break;
  21505. case 484: /* Address Incomplete */
  21506. if (owner && sipmethod != SIP_BYE) {
  21507. switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
  21508. case SIP_PAGE2_ALLOWOVERLAP_YES:
  21509. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  21510. break;
  21511. default:
  21512. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
  21513. break;
  21514. }
  21515. }
  21516. break;
  21517. default:
  21518. /* Send hangup */
  21519. if (owner && sipmethod != SIP_BYE)
  21520. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  21521. break;
  21522. }
  21523. /* ACK on invite */
  21524. if (sipmethod == SIP_INVITE)
  21525. transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  21526. sip_alreadygone(p);
  21527. if (!p->owner) {
  21528. pvt_set_needdestroy(p, "transaction completed");
  21529. }
  21530. } else if ((resp >= 100) && (resp < 200)) {
  21531. if (sipmethod == SIP_INVITE) {
  21532. if (!req->ignore && sip_cancel_destroy(p))
  21533. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  21534. if (find_sdp(req))
  21535. process_sdp(p, req, SDP_T38_NONE);
  21536. if (p->owner) {
  21537. /* Queue a progress frame */
  21538. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  21539. }
  21540. }
  21541. } else
  21542. 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));
  21543. }
  21544. } else {
  21545. /* Responses to OUTGOING SIP requests on INCOMING calls
  21546. get handled here. As well as out-of-call message responses */
  21547. if (req->debug)
  21548. ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
  21549. if (sipmethod == SIP_INVITE && resp == 200) {
  21550. /* Tags in early session is replaced by the tag in 200 OK, which is
  21551. the final reply to our INVITE */
  21552. char tag[128];
  21553. gettag(req, "To", tag, sizeof(tag));
  21554. ast_string_field_set(p, theirtag, tag);
  21555. }
  21556. switch(resp) {
  21557. case 200:
  21558. if (sipmethod == SIP_INVITE) {
  21559. handle_response_invite(p, resp, rest, req, seqno);
  21560. } else if (sipmethod == SIP_CANCEL) {
  21561. ast_debug(1, "Got 200 OK on CANCEL\n");
  21562. /* Wait for 487, then destroy */
  21563. } else if (sipmethod == SIP_BYE) {
  21564. pvt_set_needdestroy(p, "transaction completed");
  21565. }
  21566. break;
  21567. case 401: /* www-auth */
  21568. case 407:
  21569. if (sipmethod == SIP_INVITE)
  21570. handle_response_invite(p, resp, rest, req, seqno);
  21571. else if (sipmethod == SIP_BYE) {
  21572. if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
  21573. ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, sip_get_header(&p->initreq, "From"));
  21574. pvt_set_needdestroy(p, "failed to authenticate BYE");
  21575. }
  21576. }
  21577. break;
  21578. case 481: /* Call leg does not exist */
  21579. if (sipmethod == SIP_INVITE) {
  21580. /* Re-invite failed */
  21581. handle_response_invite(p, resp, rest, req, seqno);
  21582. } else if (sipmethod == SIP_BYE) {
  21583. pvt_set_needdestroy(p, "received 481 response");
  21584. } else if (sipdebug) {
  21585. ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
  21586. }
  21587. break;
  21588. case 501: /* Not Implemented */
  21589. if (sipmethod == SIP_INVITE)
  21590. handle_response_invite(p, resp, rest, req, seqno);
  21591. break;
  21592. default: /* Errors without handlers */
  21593. if ((resp >= 100) && (resp < 200)) {
  21594. if (sipmethod == SIP_INVITE) { /* re-invite */
  21595. if (!req->ignore && sip_cancel_destroy(p))
  21596. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  21597. }
  21598. } else if ((resp >= 200) && (resp < 300)) { /* on any unrecognized 2XX response do the following */
  21599. if (sipmethod == SIP_INVITE) {
  21600. handle_response_invite(p, resp, rest, req, seqno);
  21601. }
  21602. } else if ((resp >= 300) && (resp < 700)) {
  21603. if ((resp != 487))
  21604. ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
  21605. switch(resp) {
  21606. case 415: /* Unsupported media type */
  21607. case 488: /* Not acceptable here - codec error */
  21608. case 603: /* Decline */
  21609. case 500: /* Server error */
  21610. case 502: /* Bad gateway */
  21611. case 503: /* Service Unavailable */
  21612. case 504: /* Server timeout */
  21613. /* re-invite failed */
  21614. if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
  21615. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  21616. break;
  21617. }
  21618. }
  21619. break;
  21620. }
  21621. }
  21622. }
  21623. /*! \brief SIP pickup support function
  21624. * Starts in a new thread, then pickup the call
  21625. */
  21626. static void *sip_pickup_thread(void *stuff)
  21627. {
  21628. struct ast_channel *chan;
  21629. chan = stuff;
  21630. if (ast_pickup_call(chan)) {
  21631. ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
  21632. } else {
  21633. ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
  21634. }
  21635. ast_hangup(chan);
  21636. ast_channel_unref(chan);
  21637. chan = NULL;
  21638. return NULL;
  21639. }
  21640. /*! \brief Pickup a call using the subsystem in features.c
  21641. * This is executed in a separate thread
  21642. */
  21643. static int sip_pickup(struct ast_channel *chan)
  21644. {
  21645. pthread_t threadid;
  21646. ast_channel_ref(chan);
  21647. if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
  21648. ast_debug(1, "Unable to start Group pickup thread on channel %s\n", ast_channel_name(chan));
  21649. ast_channel_unref(chan);
  21650. return -1;
  21651. }
  21652. ast_debug(1, "Started Group pickup thread on channel %s\n", ast_channel_name(chan));
  21653. return 0;
  21654. }
  21655. /*! \brief Get tag from packet
  21656. *
  21657. * \return Returns the pointer to the provided tag buffer,
  21658. * or NULL if the tag was not found.
  21659. */
  21660. static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
  21661. {
  21662. const char *thetag;
  21663. if (!tagbuf)
  21664. return NULL;
  21665. tagbuf[0] = '\0'; /* reset the buffer */
  21666. thetag = sip_get_header(req, header);
  21667. thetag = strcasestr(thetag, ";tag=");
  21668. if (thetag) {
  21669. thetag += 5;
  21670. ast_copy_string(tagbuf, thetag, tagbufsize);
  21671. return strsep(&tagbuf, ";");
  21672. }
  21673. return NULL;
  21674. }
  21675. static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
  21676. {
  21677. struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
  21678. find_sip_monitor_instance_by_subscription_pvt, pvt);
  21679. const char *status = get_content_line(req, "cc-state", ':');
  21680. struct cc_epa_entry *cc_entry;
  21681. char *uri;
  21682. if (!monitor_instance) {
  21683. transmit_response(pvt, "400 Bad Request", req);
  21684. return -1;
  21685. }
  21686. if (ast_strlen_zero(status)) {
  21687. ao2_ref(monitor_instance, -1);
  21688. transmit_response(pvt, "400 Bad Request", req);
  21689. return -1;
  21690. }
  21691. if (!strcmp(status, "queued")) {
  21692. /* We've been told that we're queued. This is the endpoint's way of telling
  21693. * us that it has accepted our CC request. We need to alert the core of this
  21694. * development
  21695. */
  21696. ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
  21697. transmit_response(pvt, "200 OK", req);
  21698. ao2_ref(monitor_instance, -1);
  21699. return 0;
  21700. }
  21701. /* It's open! Yay! */
  21702. uri = get_content_line(req, "cc-URI", ':');
  21703. if (ast_strlen_zero(uri)) {
  21704. uri = get_in_brackets((char *)sip_get_header(req, "From"));
  21705. }
  21706. ast_string_field_set(monitor_instance, notify_uri, uri);
  21707. if (monitor_instance->suspension_entry) {
  21708. cc_entry = monitor_instance->suspension_entry->instance_data;
  21709. if (cc_entry->current_state == CC_CLOSED) {
  21710. /* If we've created a suspension entry and the current state is closed, then that means
  21711. * we got a notice from the CC core earlier to suspend monitoring, but because this particular
  21712. * call leg had not yet notified us that it was ready for recall, it meant that we
  21713. * could not yet send a PUBLISH. Now, however, we can.
  21714. */
  21715. construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
  21716. sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
  21717. transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
  21718. } else {
  21719. ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
  21720. }
  21721. } else {
  21722. ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
  21723. }
  21724. ao2_ref(monitor_instance, -1);
  21725. transmit_response(pvt, "200 OK", req);
  21726. return 0;
  21727. }
  21728. /*! \brief Handle incoming notifications */
  21729. static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
  21730. {
  21731. /* This is mostly a skeleton for future improvements */
  21732. /* Mostly created to return proper answers on notifications on outbound REFER's */
  21733. int res = 0;
  21734. const char *event = sip_get_header(req, "Event");
  21735. char *sep;
  21736. if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
  21737. *sep++ = '\0';
  21738. }
  21739. if (sipdebug)
  21740. ast_debug(2, "Got NOTIFY Event: %s\n", event);
  21741. if (!strcmp(event, "refer")) {
  21742. /* Save nesting depth for now, since there might be other events we will
  21743. support in the future */
  21744. /* Handle REFER notifications */
  21745. char *buf, *cmd, *code;
  21746. int respcode;
  21747. int success = TRUE;
  21748. /* EventID for each transfer... EventID is basically the REFER cseq
  21749. We are getting notifications on a call that we transferred
  21750. We should hangup when we are getting a 200 OK in a sipfrag
  21751. Check if we have an owner of this event */
  21752. /* Check the content type */
  21753. if (strncasecmp(sip_get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
  21754. /* We need a sipfrag */
  21755. transmit_response(p, "400 Bad request", req);
  21756. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21757. return -1;
  21758. }
  21759. /* Get the text of the attachment */
  21760. if (ast_strlen_zero(buf = get_content(req))) {
  21761. ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
  21762. transmit_response(p, "400 Bad request", req);
  21763. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21764. return -1;
  21765. }
  21766. /*
  21767. From the RFC...
  21768. A minimal, but complete, implementation can respond with a single
  21769. NOTIFY containing either the body:
  21770. SIP/2.0 100 Trying
  21771. if the subscription is pending, the body:
  21772. SIP/2.0 200 OK
  21773. if the reference was successful, the body:
  21774. SIP/2.0 503 Service Unavailable
  21775. if the reference failed, or the body:
  21776. SIP/2.0 603 Declined
  21777. if the REFER request was accepted before approval to follow the
  21778. reference could be obtained and that approval was subsequently denied
  21779. (see Section 2.4.7).
  21780. If there are several REFERs in the same dialog, we need to
  21781. match the ID of the event header...
  21782. */
  21783. ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
  21784. cmd = ast_skip_blanks(buf);
  21785. code = cmd;
  21786. /* We are at SIP/2.0 */
  21787. while(*code && (*code > 32)) { /* Search white space */
  21788. code++;
  21789. }
  21790. *code++ = '\0';
  21791. code = ast_skip_blanks(code);
  21792. sep = code;
  21793. sep++;
  21794. while(*sep && (*sep > 32)) { /* Search white space */
  21795. sep++;
  21796. }
  21797. *sep++ = '\0'; /* Response string */
  21798. respcode = atoi(code);
  21799. switch (respcode) {
  21800. case 200: /* OK: The new call is up, hangup this call */
  21801. /* Hangup the call that we are replacing */
  21802. break;
  21803. case 301: /* Moved permenantly */
  21804. case 302: /* Moved temporarily */
  21805. /* Do we get the header in the packet in this case? */
  21806. success = FALSE;
  21807. break;
  21808. case 503: /* Service Unavailable: The new call failed */
  21809. case 603: /* Declined: Not accepted */
  21810. /* Cancel transfer, continue the current call */
  21811. success = FALSE;
  21812. break;
  21813. case 0: /* Parse error */
  21814. /* Cancel transfer, continue the current call */
  21815. ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
  21816. success = FALSE;
  21817. break;
  21818. default:
  21819. if (respcode < 200) {
  21820. /* ignore provisional responses */
  21821. success = -1;
  21822. } else {
  21823. ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
  21824. success = FALSE;
  21825. }
  21826. break;
  21827. }
  21828. if (success == FALSE) {
  21829. ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
  21830. }
  21831. if (p->owner && success != -1) {
  21832. enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
  21833. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  21834. }
  21835. /* Confirm that we received this packet */
  21836. transmit_response(p, "200 OK", req);
  21837. } else if (!strcmp(event, "message-summary")) {
  21838. const char *mailbox = NULL;
  21839. char *c = ast_strdupa(get_content_line(req, "Voice-Message", ':'));
  21840. if (!p->mwi) {
  21841. struct sip_peer *peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
  21842. if (peer) {
  21843. mailbox = ast_strdupa(peer->unsolicited_mailbox);
  21844. sip_unref_peer(peer, "removing unsolicited mwi ref");
  21845. }
  21846. } else {
  21847. mailbox = p->mwi->mailbox;
  21848. }
  21849. if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
  21850. char *old = strsep(&c, " ");
  21851. char *new = strsep(&old, "/");
  21852. ast_publish_mwi_state(mailbox, "SIP_Remote", atoi(new), atoi(old));
  21853. transmit_response(p, "200 OK", req);
  21854. } else {
  21855. transmit_response(p, "489 Bad event", req);
  21856. res = -1;
  21857. }
  21858. } else if (!strcmp(event, "keep-alive")) {
  21859. /* Used by Sipura/Linksys for NAT pinhole,
  21860. * just confirm that we received the packet. */
  21861. transmit_response(p, "200 OK", req);
  21862. } else if (!strcmp(event, "call-completion")) {
  21863. res = handle_cc_notify(p, req);
  21864. } else {
  21865. /* We don't understand this event. */
  21866. transmit_response(p, "489 Bad event", req);
  21867. res = -1;
  21868. }
  21869. if (!p->lastinvite)
  21870. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21871. return res;
  21872. }
  21873. /*! \brief Handle incoming OPTIONS request
  21874. An OPTIONS request should be answered like an INVITE from the same UA, including SDP
  21875. */
  21876. static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
  21877. {
  21878. const char *msg;
  21879. enum sip_get_dest_result gotdest;
  21880. int res;
  21881. if (p->lastinvite) {
  21882. /* if this is a request in an active dialog, just confirm that the dialog exists. */
  21883. transmit_response_with_allow(p, "200 OK", req, 0);
  21884. return 0;
  21885. }
  21886. if (sip_cfg.auth_options_requests) {
  21887. /* Do authentication if this OPTIONS request began the dialog */
  21888. copy_request(&p->initreq, req);
  21889. set_pvt_allowed_methods(p, req);
  21890. res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
  21891. if (res == AUTH_CHALLENGE_SENT) {
  21892. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21893. return 0;
  21894. }
  21895. if (res < 0) { /* Something failed in authentication */
  21896. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
  21897. transmit_response(p, "403 Forbidden", req);
  21898. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21899. return 0;
  21900. }
  21901. }
  21902. /* must go through authentication before getting here */
  21903. gotdest = get_destination(p, req, NULL);
  21904. build_contact(p);
  21905. if (ast_strlen_zero(p->context))
  21906. ast_string_field_set(p, context, sip_cfg.default_context);
  21907. if (ast_shutting_down()) {
  21908. msg = "503 Unavailable";
  21909. } else {
  21910. msg = "404 Not Found";
  21911. switch (gotdest) {
  21912. case SIP_GET_DEST_INVALID_URI:
  21913. msg = "416 Unsupported URI scheme";
  21914. break;
  21915. case SIP_GET_DEST_EXTEN_MATCHMORE:
  21916. case SIP_GET_DEST_REFUSED:
  21917. case SIP_GET_DEST_EXTEN_NOT_FOUND:
  21918. //msg = "404 Not Found";
  21919. break;
  21920. case SIP_GET_DEST_EXTEN_FOUND:
  21921. msg = "200 OK";
  21922. break;
  21923. }
  21924. }
  21925. transmit_response_with_allow(p, msg, req, 0);
  21926. /* Destroy if this OPTIONS was the opening request, but not if
  21927. it's in the middle of a normal call flow. */
  21928. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21929. return 0;
  21930. }
  21931. /*! \brief Handle the transfer part of INVITE with a replaces: header,
  21932. *
  21933. * This is used for call-pickup and for attended transfers initiated on
  21934. * remote endpoints (i.e. a REFER received on a remote server).
  21935. *
  21936. * \note p and p->owner are locked upon entering this function. If the
  21937. * call pickup or attended transfer is successful, then p->owner will
  21938. * be unlocked upon exiting this function. This is communicated to the
  21939. * caller through the nounlock parameter.
  21940. *
  21941. * \param p The sip_pvt where the INVITE with Replaces was received
  21942. * \param req The incoming INVITE
  21943. * \param[out] nounlock Indicator if p->owner should remained locked. On successful transfer, this will be set true.
  21944. * \param replaces_pvt sip_pvt referenced by Replaces header
  21945. * \param replaces_chan replaces_pvt's owner channel
  21946. * \retval 0 Success
  21947. * \retval non-zero Failure
  21948. */
  21949. static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req,
  21950. int *nounlock, struct sip_pvt *replaces_pvt, struct ast_channel *replaces_chan)
  21951. {
  21952. struct ast_channel *c;
  21953. RAII_VAR(struct ast_bridge *, bridge, NULL, ao2_cleanup);
  21954. if (req->ignore) {
  21955. return 0;
  21956. }
  21957. if (!p->owner) {
  21958. /* What to do if no channel ??? */
  21959. ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
  21960. transmit_response_reliable(p, "503 Service Unavailable", req);
  21961. append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
  21962. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21963. return 1;
  21964. }
  21965. append_history(p, "Xfer", "INVITE/Replace received");
  21966. c = ast_channel_ref(p->owner);
  21967. /* Fake call progress */
  21968. transmit_response(p, "100 Trying", req);
  21969. ast_setstate(c, AST_STATE_RING);
  21970. ast_debug(4, "Invite/Replaces: preparing to replace %s with %s\n", ast_channel_name(replaces_chan), ast_channel_name(c));
  21971. *nounlock = 1;
  21972. ast_channel_unlock(c);
  21973. sip_pvt_unlock(p);
  21974. ast_raw_answer(c);
  21975. ast_channel_lock(replaces_chan);
  21976. bridge = ast_channel_get_bridge(replaces_chan);
  21977. ast_channel_unlock(replaces_chan);
  21978. if (bridge) {
  21979. if (ast_bridge_impart(bridge, c, replaces_chan, NULL,
  21980. AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
  21981. ast_hangup(c);
  21982. }
  21983. } else {
  21984. ast_channel_move(replaces_chan, c);
  21985. ast_hangup(c);
  21986. }
  21987. sip_pvt_lock(p);
  21988. return 0;
  21989. }
  21990. /*! \note No channel or pvt locks should be held while calling this function. */
  21991. static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
  21992. {
  21993. struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
  21994. struct ast_app *pickup = pbx_findapp("Pickup");
  21995. if (!pickup) {
  21996. ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
  21997. return -1;
  21998. }
  21999. ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
  22000. ast_debug(2, "About to call Pickup(%s)\n", ast_str_buffer(str));
  22001. /* There is no point in capturing the return value since pickup_exec
  22002. doesn't return anything meaningful unless the passed data is an empty
  22003. string (which in our case it will not be) */
  22004. pbx_exec(channel, pickup, ast_str_buffer(str));
  22005. return 0;
  22006. }
  22007. /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
  22008. static int sip_t38_abort(const void *data)
  22009. {
  22010. struct sip_pvt *p = (struct sip_pvt *) data;
  22011. sip_pvt_lock(p);
  22012. /* an application may have taken ownership of the T.38 negotiation on this
  22013. * channel while we were waiting to grab the lock... if it did, the scheduler
  22014. * id will have been reset to -1, which is our indication that we do *not*
  22015. * want to abort the negotiation process
  22016. */
  22017. if (p->t38id != -1) {
  22018. change_t38_state(p, T38_REJECTED);
  22019. transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
  22020. p->t38id = -1;
  22021. dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
  22022. }
  22023. sip_pvt_unlock(p);
  22024. return 0;
  22025. }
  22026. /*!
  22027. * \brief bare-bones support for SIP UPDATE
  22028. *
  22029. * XXX This is not even close to being RFC 3311-compliant. We don't advertise
  22030. * that we support the UPDATE method, so no one should ever try sending us
  22031. * an UPDATE anyway. However, Asterisk can send an UPDATE to change connected
  22032. * line information, so we need to be prepared to handle this. The way we distinguish
  22033. * such an UPDATE is through the X-Asterisk-rpid-update header.
  22034. *
  22035. * Actually updating the media session may be some future work.
  22036. */
  22037. static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
  22038. {
  22039. if (ast_strlen_zero(sip_get_header(req, "X-Asterisk-rpid-update"))) {
  22040. transmit_response(p, "501 Method Not Implemented", req);
  22041. return 0;
  22042. }
  22043. if (!p->owner) {
  22044. transmit_response(p, "481 Call/Transaction Does Not Exist", req);
  22045. return 0;
  22046. }
  22047. if (get_rpid(p, req)) {
  22048. struct ast_party_connected_line connected;
  22049. struct ast_set_party_connected_line update_connected;
  22050. ast_party_connected_line_init(&connected);
  22051. memset(&update_connected, 0, sizeof(update_connected));
  22052. update_connected.id.number = 1;
  22053. connected.id.number.valid = 1;
  22054. connected.id.number.str = (char *) p->cid_num;
  22055. connected.id.number.presentation = p->callingpres;
  22056. update_connected.id.name = 1;
  22057. connected.id.name.valid = 1;
  22058. connected.id.name.str = (char *) p->cid_name;
  22059. connected.id.name.presentation = p->callingpres;
  22060. /* Invalidate any earlier private connected id representation */
  22061. ast_set_party_id_all(&update_connected.priv);
  22062. connected.id.tag = (char *) p->cid_tag;
  22063. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
  22064. ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
  22065. }
  22066. transmit_response(p, "200 OK", req);
  22067. return 0;
  22068. }
  22069. /*
  22070. * \internal \brief Check Session Timers for an INVITE request
  22071. *
  22072. * \retval 0 ok
  22073. * \retval -1 failure
  22074. */
  22075. static int handle_request_invite_st(struct sip_pvt *p, struct sip_request *req,
  22076. const char *required, int reinvite)
  22077. {
  22078. const char *p_uac_se_hdr; /* UAC's Session-Expires header string */
  22079. const char *p_uac_min_se; /* UAC's requested Min-SE interval (char string) */
  22080. int uac_max_se = -1; /* UAC's Session-Expires in integer format */
  22081. int uac_min_se = -1; /* UAC's Min-SE in integer format */
  22082. int st_active = FALSE; /* Session-Timer on/off boolean */
  22083. int st_interval = 0; /* Session-Timer negotiated refresh interval */
  22084. enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO; /* Session-Timer refresher */
  22085. int dlg_min_se = -1;
  22086. int dlg_max_se = global_max_se;
  22087. int rtn;
  22088. /* Session-Timers */
  22089. if ((p->sipoptions & SIP_OPT_TIMER)) {
  22090. enum st_refresher_param st_ref_param = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
  22091. /* The UAC has requested session-timers for this session. Negotiate
  22092. the session refresh interval and who will be the refresher */
  22093. ast_debug(2, "Incoming INVITE with 'timer' option supported\n");
  22094. /* Allocate Session-Timers struct w/in the dialog */
  22095. if (!p->stimer) {
  22096. sip_st_alloc(p);
  22097. }
  22098. /* Parse the Session-Expires header */
  22099. p_uac_se_hdr = sip_get_header(req, "Session-Expires");
  22100. if (!ast_strlen_zero(p_uac_se_hdr)) {
  22101. ast_debug(2, "INVITE also has \"Session-Expires\" header.\n");
  22102. rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
  22103. tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
  22104. if (rtn != 0) {
  22105. transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
  22106. return -1;
  22107. }
  22108. }
  22109. /* Parse the Min-SE header */
  22110. p_uac_min_se = sip_get_header(req, "Min-SE");
  22111. if (!ast_strlen_zero(p_uac_min_se)) {
  22112. ast_debug(2, "INVITE also has \"Min-SE\" header.\n");
  22113. rtn = parse_minse(p_uac_min_se, &uac_min_se);
  22114. if (rtn != 0) {
  22115. transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
  22116. return -1;
  22117. }
  22118. }
  22119. dlg_min_se = st_get_se(p, FALSE);
  22120. switch (st_get_mode(p, 1)) {
  22121. case SESSION_TIMER_MODE_ACCEPT:
  22122. case SESSION_TIMER_MODE_ORIGINATE:
  22123. if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
  22124. transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
  22125. return -1;
  22126. }
  22127. p->stimer->st_active_peer_ua = TRUE;
  22128. st_active = TRUE;
  22129. if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
  22130. tmp_st_ref = st_get_refresher(p);
  22131. }
  22132. dlg_max_se = st_get_se(p, TRUE);
  22133. if (uac_max_se > 0) {
  22134. if (dlg_max_se >= uac_min_se) {
  22135. st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
  22136. } else {
  22137. st_interval = uac_max_se;
  22138. }
  22139. } else if (uac_min_se > 0) {
  22140. st_interval = MAX(dlg_max_se, uac_min_se);
  22141. } else {
  22142. st_interval = dlg_max_se;
  22143. }
  22144. break;
  22145. case SESSION_TIMER_MODE_REFUSE:
  22146. if (p->reqsipoptions & SIP_OPT_TIMER) {
  22147. transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
  22148. ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
  22149. return -1;
  22150. }
  22151. break;
  22152. default:
  22153. ast_log(LOG_ERROR, "Internal Error %u at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
  22154. break;
  22155. }
  22156. } else {
  22157. /* The UAC did not request session-timers. Asterisk (UAS), will now decide
  22158. (based on session-timer-mode in sip.conf) whether to run session-timers for
  22159. this session or not. */
  22160. switch (st_get_mode(p, 1)) {
  22161. case SESSION_TIMER_MODE_ORIGINATE:
  22162. st_active = TRUE;
  22163. st_interval = st_get_se(p, TRUE);
  22164. tmp_st_ref = SESSION_TIMER_REFRESHER_US;
  22165. p->stimer->st_active_peer_ua = (p->sipoptions & SIP_OPT_TIMER) ? TRUE : FALSE;
  22166. break;
  22167. default:
  22168. break;
  22169. }
  22170. }
  22171. if (reinvite == 0) {
  22172. /* Session-Timers: Start session refresh timer based on negotiation/config */
  22173. if (st_active == TRUE) {
  22174. p->stimer->st_active = TRUE;
  22175. p->stimer->st_interval = st_interval;
  22176. p->stimer->st_ref = tmp_st_ref;
  22177. }
  22178. } else {
  22179. if (p->stimer->st_active == TRUE) {
  22180. /* Session-Timers: A re-invite request sent within a dialog will serve as
  22181. a refresh request, no matter whether the re-invite was sent for refreshing
  22182. the session or modifying it.*/
  22183. ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
  22184. /* The UAC may be adjusting the session-timers mid-session */
  22185. if (st_interval > 0) {
  22186. p->stimer->st_interval = st_interval;
  22187. p->stimer->st_ref = tmp_st_ref;
  22188. }
  22189. }
  22190. }
  22191. return 0;
  22192. }
  22193. /*!
  22194. * \brief Handle incoming INVITE request
  22195. * \note If the INVITE has a Replaces header, it is part of an
  22196. * attended transfer. If so, we do not go through the dial
  22197. * plan but try to find the active call and masquerade
  22198. * into it
  22199. */
  22200. 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)
  22201. {
  22202. int res = INV_REQ_SUCCESS;
  22203. int gotdest;
  22204. const char *p_replaces;
  22205. char *replace_id = NULL;
  22206. const char *required;
  22207. unsigned int required_profile = 0;
  22208. struct ast_channel *c = NULL; /* New channel */
  22209. struct sip_peer *authpeer = NULL; /* Matching Peer */
  22210. int reinvite = 0;
  22211. struct ast_party_redirecting redirecting;
  22212. struct ast_set_party_redirecting update_redirecting;
  22213. struct {
  22214. char exten[AST_MAX_EXTENSION];
  22215. char context[AST_MAX_CONTEXT];
  22216. } pickup = {
  22217. .exten = "",
  22218. };
  22219. RAII_VAR(struct sip_pvt *, replaces_pvt, NULL, ao2_cleanup);
  22220. RAII_VAR(struct ast_channel *, replaces_chan, NULL, ao2_cleanup);
  22221. /* Find out what they support */
  22222. if (!p->sipoptions) {
  22223. const char *supported = sip_get_header(req, "Supported");
  22224. if (!ast_strlen_zero(supported)) {
  22225. p->sipoptions = parse_sip_options(supported, NULL, 0);
  22226. }
  22227. }
  22228. /* Find out what they require */
  22229. required = sip_get_header(req, "Require");
  22230. if (!ast_strlen_zero(required)) {
  22231. char unsupported[256] = { 0, };
  22232. required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
  22233. /* If there are any options required that we do not support,
  22234. * then send a 420 with only those unsupported options listed */
  22235. if (!ast_strlen_zero(unsupported)) {
  22236. transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
  22237. ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
  22238. p->invitestate = INV_COMPLETED;
  22239. if (!p->lastinvite)
  22240. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22241. res = INV_REQ_ERROR;
  22242. goto request_invite_cleanup;
  22243. }
  22244. }
  22245. /* The option tags may be present in Supported: or Require: headers.
  22246. Include the Require: option tags for further processing as well */
  22247. p->sipoptions |= required_profile;
  22248. p->reqsipoptions = required_profile;
  22249. /* Check if this is a loop */
  22250. 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) {
  22251. /* This is a call to ourself. Send ourselves an error code and stop
  22252. processing immediately, as SIP really has no good mechanism for
  22253. being able to call yourself */
  22254. /* If pedantic is on, we need to check the tags. If they're different, this is
  22255. in fact a forked call through a SIP proxy somewhere. */
  22256. int different;
  22257. const char *initial_rlpart2 = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
  22258. const char *this_rlpart2 = REQ_OFFSET_TO_STR(req, rlpart2);
  22259. if (sip_cfg.pedanticsipchecking)
  22260. different = sip_uri_cmp(initial_rlpart2, this_rlpart2);
  22261. else
  22262. different = strcmp(initial_rlpart2, this_rlpart2);
  22263. if (!different) {
  22264. transmit_response(p, "482 Loop Detected", req);
  22265. p->invitestate = INV_COMPLETED;
  22266. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22267. res = INV_REQ_FAILED;
  22268. goto request_invite_cleanup;
  22269. } else {
  22270. /*! This is a spiral. What we need to do is to just change the outgoing INVITE
  22271. * so that it now routes to the new Request URI. Since we created the INVITE ourselves
  22272. * that should be all we need to do.
  22273. *
  22274. * \todo XXX This needs to be reviewed. YOu don't change the request URI really, you route the packet
  22275. * correctly instead...
  22276. */
  22277. char *uri = ast_strdupa(this_rlpart2);
  22278. char *at = strchr(uri, '@');
  22279. char *peerorhost;
  22280. ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlpart2, this_rlpart2);
  22281. transmit_response(p, "100 Trying", req);
  22282. if (at) {
  22283. *at = '\0';
  22284. }
  22285. /* Parse out "sip:" */
  22286. if ((peerorhost = strchr(uri, ':'))) {
  22287. *peerorhost++ = '\0';
  22288. }
  22289. ast_string_field_set(p, theirtag, NULL);
  22290. /* Treat this as if there were a call forward instead...
  22291. */
  22292. ast_channel_call_forward_set(p->owner, peerorhost);
  22293. ast_queue_control(p->owner, AST_CONTROL_BUSY);
  22294. res = INV_REQ_FAILED;
  22295. goto request_invite_cleanup;
  22296. }
  22297. }
  22298. if (!req->ignore && p->pendinginvite) {
  22299. if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
  22300. /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
  22301. * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
  22302. * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
  22303. * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
  22304. * credentials based on one we challenged earlier.
  22305. *
  22306. * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
  22307. * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
  22308. * from the previous transaction from the list of outstanding packets.
  22309. */
  22310. __sip_ack(p, p->pendinginvite, 1, 0);
  22311. } else {
  22312. /* We already have a pending invite. Sorry. You are on hold. */
  22313. p->glareinvite = seqno;
  22314. transmit_response_reliable(p, "491 Request Pending", req);
  22315. check_via(p, req);
  22316. ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
  22317. /* Don't destroy dialog here */
  22318. res = INV_REQ_FAILED;
  22319. goto request_invite_cleanup;
  22320. }
  22321. }
  22322. p_replaces = sip_get_header(req, "Replaces");
  22323. if (!ast_strlen_zero(p_replaces)) {
  22324. /* We have a replaces header */
  22325. char *ptr;
  22326. char *fromtag = NULL;
  22327. char *totag = NULL;
  22328. char *start, *to;
  22329. int error = 0;
  22330. if (p->owner) {
  22331. ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
  22332. transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
  22333. check_via(p, req);
  22334. copy_request(&p->initreq, req);
  22335. /* Do not destroy existing call */
  22336. res = INV_REQ_ERROR;
  22337. goto request_invite_cleanup;
  22338. }
  22339. if (sipdebug)
  22340. ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
  22341. /* Create a buffer we can manipulate */
  22342. replace_id = ast_strdupa(p_replaces);
  22343. ast_uri_decode(replace_id, ast_uri_sip_user);
  22344. if (!p->refer && !sip_refer_alloc(p)) {
  22345. transmit_response_reliable(p, "500 Server Internal Error", req);
  22346. append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
  22347. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22348. p->invitestate = INV_COMPLETED;
  22349. res = INV_REQ_ERROR;
  22350. check_via(p, req);
  22351. copy_request(&p->initreq, req);
  22352. goto request_invite_cleanup;
  22353. }
  22354. /* Todo: (When we find phones that support this)
  22355. if the replaces header contains ";early-only"
  22356. we can only replace the call in early
  22357. stage, not after it's up.
  22358. If it's not in early mode, 486 Busy.
  22359. */
  22360. /* Skip leading whitespace */
  22361. replace_id = ast_skip_blanks(replace_id);
  22362. start = replace_id;
  22363. while ( (ptr = strsep(&start, ";")) ) {
  22364. ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
  22365. if ( (to = strcasestr(ptr, "to-tag=") ) )
  22366. totag = to + 7; /* skip the keyword */
  22367. else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
  22368. fromtag = to + 9; /* skip the keyword */
  22369. fromtag = strsep(&fromtag, "&"); /* trim what ? */
  22370. }
  22371. }
  22372. if (sipdebug)
  22373. ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
  22374. replace_id,
  22375. fromtag ? fromtag : "<no from tag>",
  22376. totag ? totag : "<no to tag>");
  22377. /* Try to find call that we are replacing.
  22378. If we have a Replaces header, we need to cancel that call if we succeed with this call.
  22379. First we cheat a little and look for a magic call-id from phones that support
  22380. dialog-info+xml so we can do technology independent pickup... */
  22381. if (strncmp(replace_id, "pickup-", 7) == 0) {
  22382. RAII_VAR(struct sip_pvt *, subscription, NULL, ao2_cleanup);
  22383. RAII_VAR(struct ast_channel *, subscription_chan, NULL, ao2_cleanup);
  22384. replace_id += 7; /* Worst case we are looking at \0 */
  22385. if (get_sip_pvt_from_replaces(replace_id, totag, fromtag, &subscription, &subscription_chan)) {
  22386. ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
  22387. transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
  22388. error = 1;
  22389. } else {
  22390. SCOPED_LOCK(lock, subscription, sip_pvt_lock, sip_pvt_unlock);
  22391. ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
  22392. ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
  22393. ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
  22394. }
  22395. }
  22396. if (!error && ast_strlen_zero(pickup.exten) && get_sip_pvt_from_replaces(replace_id,
  22397. totag, fromtag, &replaces_pvt, &replaces_chan)) {
  22398. ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
  22399. transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
  22400. error = 1;
  22401. }
  22402. /* The matched call is the call from the transferer to Asterisk .
  22403. We want to bridge the bridged part of the call to the
  22404. incoming invite, thus taking over the refered call */
  22405. if (replaces_pvt == p) {
  22406. ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
  22407. transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
  22408. error = 1;
  22409. }
  22410. if (!error && ast_strlen_zero(pickup.exten) && !replaces_chan) {
  22411. /* Oops, someting wrong anyway, no owner, no call */
  22412. ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
  22413. /* Check for better return code */
  22414. transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
  22415. error = 1;
  22416. }
  22417. if (!error && ast_strlen_zero(pickup.exten) &&
  22418. ast_channel_state(replaces_chan) != AST_STATE_RINGING &&
  22419. ast_channel_state(replaces_chan) != AST_STATE_RING &&
  22420. ast_channel_state(replaces_chan) != AST_STATE_UP) {
  22421. ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
  22422. transmit_response_reliable(p, "603 Declined (Replaces)", req);
  22423. error = 1;
  22424. }
  22425. if (error) { /* Give up this dialog */
  22426. append_history(p, "Xfer", "INVITE/Replace Failed.");
  22427. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22428. p->invitestate = INV_COMPLETED;
  22429. res = INV_REQ_ERROR;
  22430. check_via(p, req);
  22431. copy_request(&p->initreq, req);
  22432. goto request_invite_cleanup;
  22433. }
  22434. }
  22435. /* Check if this is an INVITE that sets up a new dialog or
  22436. a re-invite in an existing dialog */
  22437. if (!req->ignore) {
  22438. int newcall = (p->initreq.headers ? TRUE : FALSE);
  22439. if (sip_cancel_destroy(p))
  22440. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  22441. /* This also counts as a pending invite */
  22442. p->pendinginvite = seqno;
  22443. check_via(p, req);
  22444. copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
  22445. if (sipdebug)
  22446. ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  22447. if (!p->owner) { /* Not a re-invite */
  22448. if (req->debug)
  22449. ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
  22450. if (newcall)
  22451. append_history(p, "Invite", "New call: %s", p->callid);
  22452. parse_ok_contact(p, req);
  22453. } else { /* Re-invite on existing call */
  22454. ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
  22455. if (get_rpid(p, req)) {
  22456. struct ast_party_connected_line connected;
  22457. struct ast_set_party_connected_line update_connected;
  22458. ast_party_connected_line_init(&connected);
  22459. memset(&update_connected, 0, sizeof(update_connected));
  22460. update_connected.id.number = 1;
  22461. connected.id.number.valid = 1;
  22462. connected.id.number.str = (char *) p->cid_num;
  22463. connected.id.number.presentation = p->callingpres;
  22464. update_connected.id.name = 1;
  22465. connected.id.name.valid = 1;
  22466. connected.id.name.str = (char *) p->cid_name;
  22467. connected.id.name.presentation = p->callingpres;
  22468. /* Invalidate any earlier private connected id representation */
  22469. ast_set_party_id_all(&update_connected.priv);
  22470. connected.id.tag = (char *) p->cid_tag;
  22471. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
  22472. ast_channel_queue_connected_line_update(p->owner, &connected,
  22473. &update_connected);
  22474. }
  22475. /* Handle SDP here if we already have an owner */
  22476. if (find_sdp(req)) {
  22477. if (process_sdp(p, req, SDP_T38_INITIATE)) {
  22478. if (!ast_strlen_zero(sip_get_header(req, "Content-Encoding"))) {
  22479. /* Asterisk does not yet support any Content-Encoding methods. Always
  22480. * attempt to process the sdp, but return a 415 if a Content-Encoding header
  22481. * was present after processing failed. */
  22482. transmit_response_reliable(p, "415 Unsupported Media type", req);
  22483. } else {
  22484. transmit_response_reliable(p, "488 Not acceptable here", req);
  22485. }
  22486. if (!p->lastinvite)
  22487. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22488. res = INV_REQ_ERROR;
  22489. goto request_invite_cleanup;
  22490. }
  22491. ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
  22492. } else {
  22493. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  22494. ast_format_cap_append_from_cap(p->jointcaps, p->caps, AST_MEDIA_TYPE_UNKNOWN);
  22495. ast_debug(1, "Hm.... No sdp for the moment\n");
  22496. /* Some devices signal they want to be put off hold by sending a re-invite
  22497. *without* an SDP, which is supposed to mean "Go back to your state"
  22498. and since they put os on remote hold, we go back to off hold */
  22499. if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  22500. ast_queue_unhold(p->owner);
  22501. /* Activate a re-invite */
  22502. ast_queue_frame(p->owner, &ast_null_frame);
  22503. change_hold_state(p, req, FALSE, 0);
  22504. }
  22505. }
  22506. if (p->do_history) /* This is a response, note what it was for */
  22507. append_history(p, "ReInv", "Re-invite received");
  22508. }
  22509. } else if (req->debug)
  22510. ast_verbose("Ignoring this INVITE request\n");
  22511. if (!p->lastinvite && !req->ignore && !p->owner) {
  22512. /* This is a new invite */
  22513. /* Handle authentication if this is our first invite */
  22514. int cc_recall_core_id = -1;
  22515. set_pvt_allowed_methods(p, req);
  22516. res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
  22517. if (res == AUTH_CHALLENGE_SENT) {
  22518. p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
  22519. goto request_invite_cleanup;
  22520. }
  22521. if (res < 0) { /* Something failed in authentication */
  22522. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
  22523. transmit_response_reliable(p, "403 Forbidden", req);
  22524. p->invitestate = INV_COMPLETED;
  22525. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22526. goto request_invite_cleanup;
  22527. }
  22528. /* Successful authentication and peer matching so record the peer related to this pvt (for easy access to peer settings) */
  22529. if (p->relatedpeer) {
  22530. p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
  22531. }
  22532. if (authpeer) {
  22533. p->relatedpeer = sip_ref_peer(authpeer, "setting dialog's relatedpeer pointer");
  22534. }
  22535. req->authenticated = 1;
  22536. /* We have a successful authentication, process the SDP portion if there is one */
  22537. if (find_sdp(req)) {
  22538. if (process_sdp(p, req, SDP_T38_INITIATE)) {
  22539. /* Asterisk does not yet support any Content-Encoding methods. Always
  22540. * attempt to process the sdp, but return a 415 if a Content-Encoding header
  22541. * was present after processing fails. */
  22542. if (!ast_strlen_zero(sip_get_header(req, "Content-Encoding"))) {
  22543. transmit_response_reliable(p, "415 Unsupported Media type", req);
  22544. } else {
  22545. /* Unacceptable codecs */
  22546. transmit_response_reliable(p, "488 Not acceptable here", req);
  22547. }
  22548. p->invitestate = INV_COMPLETED;
  22549. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22550. ast_debug(1, "No compatible codecs for this SIP call.\n");
  22551. res = INV_REQ_ERROR;
  22552. goto request_invite_cleanup;
  22553. }
  22554. } else { /* No SDP in invite, call control session */
  22555. ast_format_cap_remove_by_type(p->jointcaps, AST_MEDIA_TYPE_UNKNOWN);
  22556. ast_format_cap_append_from_cap(p->jointcaps, p->caps, AST_MEDIA_TYPE_UNKNOWN);
  22557. ast_debug(2, "No SDP in Invite, third party call control\n");
  22558. }
  22559. /* Initialize the context if it hasn't been already */
  22560. if (ast_strlen_zero(p->context))
  22561. ast_string_field_set(p, context, sip_cfg.default_context);
  22562. /* Check number of concurrent calls -vs- incoming limit HERE */
  22563. ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
  22564. if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
  22565. if (res < 0) {
  22566. ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
  22567. transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
  22568. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22569. p->invitestate = INV_COMPLETED;
  22570. res = AUTH_SESSION_LIMIT;
  22571. }
  22572. goto request_invite_cleanup;
  22573. }
  22574. gotdest = get_destination(p, NULL, &cc_recall_core_id); /* Get destination right away */
  22575. extract_uri(p, req); /* Get the Contact URI */
  22576. build_contact(p); /* Build our contact header */
  22577. if (p->rtp) {
  22578. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  22579. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  22580. }
  22581. if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) { /* No matching extension found */
  22582. switch(gotdest) {
  22583. case SIP_GET_DEST_INVALID_URI:
  22584. transmit_response_reliable(p, "416 Unsupported URI scheme", req);
  22585. break;
  22586. case SIP_GET_DEST_EXTEN_MATCHMORE:
  22587. if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
  22588. == SIP_PAGE2_ALLOWOVERLAP_YES) {
  22589. transmit_response_reliable(p, "484 Address Incomplete", req);
  22590. break;
  22591. }
  22592. /*
  22593. * XXX We would have to implement collecting more digits in
  22594. * chan_sip for any other schemes of overlap dialing.
  22595. *
  22596. * For SIP_PAGE2_ALLOWOVERLAP_DTMF it is better to do this in
  22597. * the dialplan using the Incomplete application rather than
  22598. * having the channel driver do it.
  22599. */
  22600. /* Fall through */
  22601. case SIP_GET_DEST_EXTEN_NOT_FOUND:
  22602. {
  22603. char *decoded_exten = ast_strdupa(p->exten);
  22604. transmit_response_reliable(p, "404 Not Found", req);
  22605. ast_uri_decode(decoded_exten, ast_uri_sip_user);
  22606. ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
  22607. " '%s' rejected because extension not found in context '%s'.\n",
  22608. S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
  22609. }
  22610. break;
  22611. case SIP_GET_DEST_REFUSED:
  22612. default:
  22613. transmit_response_reliable(p, "403 Forbidden", req);
  22614. } /* end switch */
  22615. p->invitestate = INV_COMPLETED;
  22616. update_call_counter(p, DEC_CALL_LIMIT);
  22617. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22618. res = INV_REQ_FAILED;
  22619. goto request_invite_cleanup;
  22620. } else {
  22621. /* If no extension was specified, use the s one */
  22622. /* Basically for calling to IP/Host name only */
  22623. if (ast_strlen_zero(p->exten))
  22624. ast_string_field_set(p, exten, "s");
  22625. /* Initialize our tag */
  22626. make_our_tag(p);
  22627. if (handle_request_invite_st(p, req, required, reinvite)) {
  22628. p->invitestate = INV_COMPLETED;
  22629. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22630. res = INV_REQ_ERROR;
  22631. goto request_invite_cleanup;
  22632. }
  22633. /* First invitation - create the channel. Allocation
  22634. * failures are handled below. */
  22635. c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL, NULL, p->logger_callid);
  22636. if (cc_recall_core_id != -1) {
  22637. ast_setup_cc_recall_datastore(c, cc_recall_core_id);
  22638. ast_cc_agent_set_interfaces_chanvar(c);
  22639. }
  22640. *recount = 1;
  22641. /* Save Record-Route for any later requests we make on this dialogue */
  22642. build_route(p, req, 0, 0);
  22643. if (c) {
  22644. ast_party_redirecting_init(&redirecting);
  22645. memset(&update_redirecting, 0, sizeof(update_redirecting));
  22646. change_redirecting_information(p, req, &redirecting, &update_redirecting,
  22647. FALSE); /*Will return immediately if no Diversion header is present */
  22648. ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
  22649. ast_party_redirecting_free(&redirecting);
  22650. }
  22651. }
  22652. } else {
  22653. ast_party_redirecting_init(&redirecting);
  22654. memset(&update_redirecting, 0, sizeof(update_redirecting));
  22655. if (sipdebug) {
  22656. if (!req->ignore)
  22657. ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
  22658. else
  22659. ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
  22660. }
  22661. if (!req->ignore)
  22662. reinvite = 1;
  22663. if (handle_request_invite_st(p, req, required, reinvite)) {
  22664. p->invitestate = INV_COMPLETED;
  22665. if (!p->lastinvite) {
  22666. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22667. }
  22668. res = INV_REQ_ERROR;
  22669. goto request_invite_cleanup;
  22670. }
  22671. c = p->owner;
  22672. change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE); /*Will return immediately if no Diversion header is present */
  22673. if (c) {
  22674. ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
  22675. }
  22676. ast_party_redirecting_free(&redirecting);
  22677. }
  22678. /* Check if OLI/ANI-II is present in From: */
  22679. parse_oli(req, p->owner);
  22680. if (reinvite && p->stimer->st_active == TRUE) {
  22681. restart_session_timer(p);
  22682. }
  22683. if (!req->ignore && p)
  22684. p->lastinvite = seqno;
  22685. if (c && replace_id) { /* Attended transfer or call pickup - we're the target */
  22686. if (!ast_strlen_zero(pickup.exten)) {
  22687. append_history(p, "Xfer", "INVITE/Replace received");
  22688. /* Let the caller know we're giving it a shot */
  22689. transmit_response(p, "100 Trying", req);
  22690. p->invitestate = INV_PROCEEDING;
  22691. ast_setstate(c, AST_STATE_RING);
  22692. /* Do the pickup itself */
  22693. ast_channel_unlock(c);
  22694. *nounlock = 1;
  22695. /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
  22696. * magic pickup and ast_hangup. Both of these functions will attempt to lock
  22697. * p->owner again, which can cause a deadlock if we already hold a lock on p.
  22698. * Locking order is, channel then pvt. Dead lock avoidance must be used if
  22699. * called the other way around. */
  22700. sip_pvt_unlock(p);
  22701. do_magic_pickup(c, pickup.exten, pickup.context);
  22702. /* Now we're either masqueraded or we failed to pickup, in either case we... */
  22703. ast_hangup(c);
  22704. sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
  22705. res = INV_REQ_FAILED;
  22706. goto request_invite_cleanup;
  22707. } else {
  22708. /* Go and take over the target call */
  22709. if (sipdebug)
  22710. ast_debug(4, "Sending this call to the invite/replaces handler %s\n", p->callid);
  22711. res = handle_invite_replaces(p, req, nounlock, replaces_pvt, replaces_chan);
  22712. goto request_invite_cleanup;
  22713. }
  22714. }
  22715. if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
  22716. enum ast_channel_state c_state = ast_channel_state(c);
  22717. RAII_VAR(struct ast_features_pickup_config *, pickup_cfg, ast_get_chan_features_pickup_config(c), ao2_cleanup);
  22718. const char *pickupexten;
  22719. if (!pickup_cfg) {
  22720. ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
  22721. pickupexten = "";
  22722. } else {
  22723. pickupexten = ast_strdupa(pickup_cfg->pickupexten);
  22724. }
  22725. if (c_state != AST_STATE_UP && reinvite &&
  22726. (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
  22727. /* If these conditions are true, and the channel is still in the 'ringing'
  22728. * state, then this likely means that we have a situation where the initial
  22729. * INVITE transaction has completed *but* the channel's state has not yet been
  22730. * changed to UP. The reason this could happen is if the reinvite is received
  22731. * on the SIP socket prior to an application calling ast_read on this channel
  22732. * to read the answer frame we earlier queued on it. In this case, the reinvite
  22733. * is completely legitimate so we need to handle this the same as if the channel
  22734. * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
  22735. */
  22736. c_state = AST_STATE_UP;
  22737. }
  22738. switch(c_state) {
  22739. case AST_STATE_DOWN:
  22740. ast_debug(2, "%s: New call is still down.... Trying... \n", ast_channel_name(c));
  22741. transmit_provisional_response(p, "100 Trying", req, 0);
  22742. p->invitestate = INV_PROCEEDING;
  22743. ast_setstate(c, AST_STATE_RING);
  22744. if (strcmp(p->exten, pickupexten)) { /* Call to extension -start pbx on this call */
  22745. enum ast_pbx_result result;
  22746. result = ast_pbx_start(c);
  22747. switch(result) {
  22748. case AST_PBX_FAILED:
  22749. ast_log(LOG_WARNING, "Failed to start PBX :(\n");
  22750. p->invitestate = INV_COMPLETED;
  22751. transmit_response_reliable(p, "503 Unavailable", req);
  22752. break;
  22753. case AST_PBX_CALL_LIMIT:
  22754. ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
  22755. p->invitestate = INV_COMPLETED;
  22756. transmit_response_reliable(p, "480 Temporarily Unavailable", req);
  22757. res = AUTH_SESSION_LIMIT;
  22758. break;
  22759. case AST_PBX_SUCCESS:
  22760. /* nothing to do */
  22761. break;
  22762. }
  22763. if (result) {
  22764. /* Unlock locks so ast_hangup can do its magic */
  22765. ast_channel_unlock(c);
  22766. *nounlock = 1;
  22767. sip_pvt_unlock(p);
  22768. ast_hangup(c);
  22769. sip_pvt_lock(p);
  22770. c = NULL;
  22771. }
  22772. } else { /* Pickup call in call group */
  22773. if (sip_pickup(c)) {
  22774. ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", ast_channel_name(c));
  22775. transmit_response_reliable(p, "480 Temporarily Unavailable", req);
  22776. sip_alreadygone(p);
  22777. ast_channel_hangupcause_set(c, AST_CAUSE_FAILURE);
  22778. /* Unlock locks so ast_hangup can do its magic */
  22779. ast_channel_unlock(c);
  22780. *nounlock = 1;
  22781. p->invitestate = INV_COMPLETED;
  22782. sip_pvt_unlock(p);
  22783. ast_hangup(c);
  22784. sip_pvt_lock(p);
  22785. c = NULL;
  22786. }
  22787. }
  22788. break;
  22789. case AST_STATE_RING:
  22790. transmit_provisional_response(p, "100 Trying", req, 0);
  22791. p->invitestate = INV_PROCEEDING;
  22792. break;
  22793. case AST_STATE_RINGING:
  22794. transmit_provisional_response(p, "180 Ringing", req, 0);
  22795. p->invitestate = INV_PROCEEDING;
  22796. break;
  22797. case AST_STATE_UP:
  22798. ast_debug(2, "%s: This call is UP.... \n", ast_channel_name(c));
  22799. transmit_response(p, "100 Trying", req);
  22800. if (p->t38.state == T38_PEER_REINVITE) {
  22801. if (p->t38id > -1) {
  22802. /* reset t38 abort timer */
  22803. AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
  22804. }
  22805. 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."));
  22806. } else if (p->t38.state == T38_ENABLED) {
  22807. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  22808. transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
  22809. } else if ((p->t38.state == T38_DISABLED) || (p->t38.state == T38_REJECTED)) {
  22810. /* If this is not a re-invite or something to ignore - it's critical */
  22811. if (p->srtp && !ast_test_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK)) {
  22812. ast_log(LOG_WARNING, "Target does not support required crypto\n");
  22813. transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
  22814. } else {
  22815. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  22816. transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
  22817. ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
  22818. }
  22819. }
  22820. p->invitestate = INV_TERMINATED;
  22821. break;
  22822. default:
  22823. ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %u\n", ast_channel_state(c));
  22824. transmit_response(p, "100 Trying", req);
  22825. break;
  22826. }
  22827. } else {
  22828. if (!req->ignore && p && (p->autokillid == -1)) {
  22829. const char *msg;
  22830. if ((!ast_format_cap_count(p->jointcaps)))
  22831. msg = "488 Not Acceptable Here (codec error)";
  22832. else {
  22833. ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
  22834. msg = "503 Unavailable";
  22835. }
  22836. transmit_response_reliable(p, msg, req);
  22837. p->invitestate = INV_COMPLETED;
  22838. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22839. }
  22840. }
  22841. request_invite_cleanup:
  22842. if (authpeer) {
  22843. authpeer = sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_invite authpeer");
  22844. }
  22845. return res;
  22846. }
  22847. /*! \brief Check for the presence of OLI tag(s) in the From header and set on the channel
  22848. */
  22849. static void parse_oli(struct sip_request *req, struct ast_channel *chan)
  22850. {
  22851. const char *from = NULL;
  22852. const char *s = NULL;
  22853. int ani2 = 0;
  22854. if (!chan || !req) {
  22855. /* null pointers are not helpful */
  22856. return;
  22857. }
  22858. from = sip_get_header(req, "From");
  22859. if (ast_strlen_zero(from)) {
  22860. /* no From header */
  22861. return;
  22862. }
  22863. /* Look for the possible OLI tags. */
  22864. if ((s = strcasestr(from, ";isup-oli="))) {
  22865. s += 10;
  22866. } else if ((s = strcasestr(from, ";ss7-oli="))) {
  22867. s += 9;
  22868. } else if ((s = strcasestr(from, ";oli="))) {
  22869. s += 5;
  22870. }
  22871. if (ast_strlen_zero(s)) {
  22872. /* OLI tag is missing, or present with nothing following the '=' sign */
  22873. return;
  22874. }
  22875. /* just in case OLI is quoted */
  22876. if (*s == '\"') {
  22877. s++;
  22878. }
  22879. if (sscanf(s, "%d", &ani2)) {
  22880. ast_channel_caller(chan)->ani2 = ani2;
  22881. }
  22882. return;
  22883. }
  22884. /*! \brief Find all call legs and bridge transferee with target
  22885. * called from handle_request_refer
  22886. *
  22887. * \note this function assumes two locks to begin with, sip_pvt transferer and current.chan1 (the pvt's owner)...
  22888. * 2 additional locks are held at the beginning of the function, targetcall_pvt, and targetcall_pvt's owner
  22889. * channel (which is stored in target.chan1). These 2 locks _MUST_ be let go by the end of the function. Do
  22890. * not be confused into thinking a pvt's owner is the same thing as the channels locked at the beginning of
  22891. * this function, after the masquerade this may not be true. Be consistent and unlock only the exact same
  22892. * pointers that were locked to begin with.
  22893. *
  22894. * If this function is successful, only the transferer pvt lock will remain on return. Setting nounlock indicates
  22895. * to handle_request_do() that the pvt's owner it locked does not require an unlock.
  22896. */
  22897. static int local_attended_transfer(struct sip_pvt *transferer, struct ast_channel *transferer_chan, uint32_t seqno, int *nounlock)
  22898. {
  22899. RAII_VAR(struct sip_pvt *, targetcall_pvt, NULL, ao2_cleanup);
  22900. RAII_VAR(struct ast_channel *, targetcall_chan, NULL, ao2_cleanup);
  22901. enum ast_transfer_result transfer_res;
  22902. /* Check if the call ID of the replaces header does exist locally */
  22903. if (get_sip_pvt_from_replaces(transferer->refer->replaces_callid,
  22904. transferer->refer->replaces_callid_totag,
  22905. transferer->refer->replaces_callid_fromtag,
  22906. &targetcall_pvt, &targetcall_chan)) {
  22907. if (transferer->refer->localtransfer) {
  22908. /* We did not find the refered call. Sorry, can't accept then */
  22909. /* Let's fake a response from someone else in order
  22910. to follow the standard */
  22911. transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
  22912. append_history(transferer, "Xfer", "Refer failed");
  22913. ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
  22914. transferer->refer->status = REFER_FAILED;
  22915. return -1;
  22916. }
  22917. /* Fall through for remote transfers that we did not find locally */
  22918. ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
  22919. return 0;
  22920. }
  22921. if (!targetcall_chan) { /* No active channel */
  22922. ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
  22923. /* Cancel transfer */
  22924. transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
  22925. append_history(transferer, "Xfer", "Refer failed");
  22926. ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
  22927. transferer->refer->status = REFER_FAILED;
  22928. return -1;
  22929. }
  22930. ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
  22931. sip_pvt_unlock(transferer);
  22932. ast_channel_unlock(transferer_chan);
  22933. *nounlock = 1;
  22934. transfer_res = ast_bridge_transfer_attended(transferer_chan, targetcall_chan);
  22935. sip_pvt_lock(transferer);
  22936. switch (transfer_res) {
  22937. case AST_BRIDGE_TRANSFER_SUCCESS:
  22938. transferer->refer->status = REFER_200OK;
  22939. transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
  22940. append_history(transferer, "Xfer", "Refer succeeded");
  22941. return 1;
  22942. case AST_BRIDGE_TRANSFER_FAIL:
  22943. transferer->refer->status = REFER_FAILED;
  22944. transmit_notify_with_sipfrag(transferer, seqno, "500 Internal Server Error", TRUE);
  22945. append_history(transferer, "Xfer", "Refer failed (internal error)");
  22946. ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  22947. return -1;
  22948. case AST_BRIDGE_TRANSFER_INVALID:
  22949. transferer->refer->status = REFER_FAILED;
  22950. transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
  22951. append_history(transferer, "Xfer", "Refer failed (invalid bridge state)");
  22952. ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  22953. return -1;
  22954. case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
  22955. transferer->refer->status = REFER_FAILED;
  22956. transmit_notify_with_sipfrag(transferer, seqno, "403 Forbidden", TRUE);
  22957. append_history(transferer, "Xfer", "Refer failed (operation not permitted)");
  22958. ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  22959. return -1;
  22960. default:
  22961. break;
  22962. }
  22963. return 1;
  22964. }
  22965. /*!
  22966. * Data to set on a channel that runs dialplan
  22967. * at the completion of a blind transfer
  22968. */
  22969. struct blind_transfer_cb_data {
  22970. /*! Contents of the REFER's Referred-by header */
  22971. const char *referred_by;
  22972. /*! Domain of the URI in the REFER's Refer-To header */
  22973. const char *domain;
  22974. /*! Contents of what to place in a Replaces header of an INVITE */
  22975. const char *replaces;
  22976. /*! Redirecting information to set on the channel */
  22977. struct ast_party_redirecting redirecting;
  22978. /*! Parts of the redirecting structure that are to be updated */
  22979. struct ast_set_party_redirecting update_redirecting;
  22980. };
  22981. /*!
  22982. * \internal
  22983. * \brief Callback called on new outbound channel during blind transfer
  22984. *
  22985. * We use this opportunity to populate the channel with data from the REFER
  22986. * so that, if necessary, we can include proper information on any new INVITE
  22987. * we may send out.
  22988. *
  22989. * \param chan The new outbound channel
  22990. * \param user_data A blind_transfer_cb_data struct
  22991. * \param transfer_type Unused
  22992. */
  22993. static void blind_transfer_cb(struct ast_channel *chan, struct transfer_channel_data *user_data_wrapper,
  22994. enum ast_transfer_type transfer_type)
  22995. {
  22996. struct blind_transfer_cb_data *cb_data = user_data_wrapper->data;
  22997. pbx_builtin_setvar_helper(chan, "SIPTRANSFER", "yes");
  22998. pbx_builtin_setvar_helper(chan, "SIPTRANSFER_REFERER", cb_data->referred_by);
  22999. pbx_builtin_setvar_helper(chan, "SIPTRANSFER_REPLACES", cb_data->replaces);
  23000. pbx_builtin_setvar_helper(chan, "SIPDOMAIN", cb_data->domain);
  23001. ast_channel_update_redirecting(chan, &cb_data->redirecting, &cb_data->update_redirecting);
  23002. }
  23003. /*! \brief Handle incoming REFER request */
  23004. /*! \page SIP_REFER SIP transfer Support (REFER)
  23005. REFER is used for call transfer in SIP. We get a REFER
  23006. to place a new call with an INVITE somwhere and then
  23007. keep the transferor up-to-date of the transfer. If the
  23008. transfer fails, get back on line with the orginal call.
  23009. - REFER can be sent outside or inside of a dialog.
  23010. Asterisk only accepts REFER inside of a dialog.
  23011. - If we get a replaces header, it is an attended transfer
  23012. \par Blind transfers
  23013. The transferor provides the transferee
  23014. with the transfer targets contact. The signalling between
  23015. transferer or transferee should not be cancelled, so the
  23016. call is recoverable if the transfer target can not be reached
  23017. by the transferee.
  23018. In this case, Asterisk receives a TRANSFER from
  23019. the transferor, thus is the transferee. We should
  23020. try to set up a call to the contact provided
  23021. and if that fails, re-connect the current session.
  23022. If the new call is set up, we issue a hangup.
  23023. In this scenario, we are following section 5.2
  23024. in the SIP CC Transfer draft. (Transfer without
  23025. a GRUU)
  23026. \par Transfer with consultation hold
  23027. In this case, the transferor
  23028. talks to the transfer target before the transfer takes place.
  23029. This is implemented with SIP hold and transfer.
  23030. Note: The invite From: string could indicate a transfer.
  23031. (Section 6. Transfer with consultation hold)
  23032. The transferor places the transferee on hold, starts a call
  23033. with the transfer target to alert them to the impending
  23034. transfer, terminates the connection with the target, then
  23035. proceeds with the transfer (as in Blind transfer above)
  23036. \par Attended transfer
  23037. The transferor places the transferee
  23038. on hold, calls the transfer target to alert them,
  23039. places the target on hold, then proceeds with the transfer
  23040. using a Replaces header field in the Refer-to header. This
  23041. will force the transfee to send an Invite to the target,
  23042. with a replaces header that instructs the target to
  23043. hangup the call between the transferor and the target.
  23044. In this case, the Refer/to: uses the AOR address. (The same
  23045. URI that the transferee used to establish the session with
  23046. the transfer target (To: ). The Require: replaces header should
  23047. be in the INVITE to avoid the wrong UA in a forked SIP proxy
  23048. scenario to answer and have no call to replace with.
  23049. The referred-by header is *NOT* required, but if we get it,
  23050. can be copied into the INVITE to the transfer target to
  23051. inform the target about the transferor
  23052. "Any REFER request has to be appropriately authenticated.".
  23053. We can't destroy dialogs, since we want the call to continue.
  23054. */
  23055. static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock)
  23056. {
  23057. char *refer_to = NULL;
  23058. char *refer_to_context = NULL;
  23059. int res = 0;
  23060. struct blind_transfer_cb_data cb_data;
  23061. enum ast_transfer_result transfer_res;
  23062. RAII_VAR(struct ast_channel *, transferer, NULL, ast_channel_cleanup);
  23063. RAII_VAR(struct ast_str *, replaces_str, NULL, ast_free_ptr);
  23064. if (req->debug) {
  23065. ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
  23066. p->callid,
  23067. ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
  23068. }
  23069. if (!p->owner) {
  23070. /* This is a REFER outside of an existing SIP dialog */
  23071. /* We can't handle that, so decline it */
  23072. ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
  23073. transmit_response(p, "603 Declined (No dialog)", req);
  23074. if (!req->ignore) {
  23075. append_history(p, "Xfer", "Refer failed. Outside of dialog.");
  23076. sip_alreadygone(p);
  23077. pvt_set_needdestroy(p, "outside of dialog");
  23078. }
  23079. return 0;
  23080. }
  23081. /* Check if transfer is allowed from this device */
  23082. if (p->allowtransfer == TRANSFER_CLOSED ) {
  23083. /* Transfer not allowed, decline */
  23084. transmit_response(p, "603 Declined (policy)", req);
  23085. append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
  23086. /* Do not destroy SIP session */
  23087. return 0;
  23088. }
  23089. if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
  23090. /* Already have a pending REFER */
  23091. transmit_response(p, "491 Request pending", req);
  23092. append_history(p, "Xfer", "Refer failed. Request pending.");
  23093. return 0;
  23094. }
  23095. /* Allocate memory for call transfer data */
  23096. if (!p->refer && !sip_refer_alloc(p)) {
  23097. transmit_response(p, "500 Internal Server Error", req);
  23098. append_history(p, "Xfer", "Refer failed. Memory allocation error.");
  23099. return -3;
  23100. }
  23101. res = get_refer_info(p, req); /* Extract headers */
  23102. p->refer->status = REFER_SENT;
  23103. if (res != 0) {
  23104. switch (res) {
  23105. case -2: /* Syntax error */
  23106. transmit_response(p, "400 Bad Request (Refer-to missing)", req);
  23107. append_history(p, "Xfer", "Refer failed. Refer-to missing.");
  23108. if (req->debug) {
  23109. ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
  23110. }
  23111. break;
  23112. case -3:
  23113. transmit_response(p, "603 Declined (Non sip: uri)", req);
  23114. append_history(p, "Xfer", "Refer failed. Non SIP uri");
  23115. if (req->debug) {
  23116. ast_debug(1, "SIP transfer to non-SIP uri denied\n");
  23117. }
  23118. break;
  23119. default:
  23120. /* Refer-to extension not found, fake a failed transfer */
  23121. transmit_response(p, "202 Accepted", req);
  23122. append_history(p, "Xfer", "Refer failed. Bad extension.");
  23123. transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
  23124. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  23125. if (req->debug) {
  23126. ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
  23127. }
  23128. break;
  23129. }
  23130. return 0;
  23131. }
  23132. if (ast_strlen_zero(p->context)) {
  23133. ast_string_field_set(p, context, sip_cfg.default_context);
  23134. }
  23135. /* If we do not support SIP domains, all transfers are local */
  23136. if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
  23137. p->refer->localtransfer = 1;
  23138. if (sipdebug) {
  23139. ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
  23140. }
  23141. } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
  23142. /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
  23143. p->refer->localtransfer = 1;
  23144. } else if (sipdebug) {
  23145. ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
  23146. }
  23147. /* Is this a repeat of a current request? Ignore it */
  23148. /* Don't know what else to do right now. */
  23149. if (req->ignore) {
  23150. return 0;
  23151. }
  23152. /* Get the transferer's channel */
  23153. transferer = ast_channel_ref(p->owner);
  23154. if (sipdebug) {
  23155. ast_debug(3, "SIP %s transfer: Transferer channel %s\n",
  23156. p->refer->attendedtransfer ? "attended" : "blind",
  23157. ast_channel_name(transferer));
  23158. }
  23159. ast_set_flag(&p->flags[0], SIP_GOTREFER);
  23160. /* From here on failures will be indicated with NOTIFY requests */
  23161. transmit_response(p, "202 Accepted", req);
  23162. /* Attended transfer: Find all call legs and bridge transferee with target*/
  23163. if (p->refer->attendedtransfer) {
  23164. /* both p and p->owner _MUST_ be locked while calling local_attended_transfer */
  23165. if ((res = local_attended_transfer(p, transferer, seqno, nounlock))) {
  23166. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  23167. return res;
  23168. }
  23169. /* Fall through for remote transfers that we did not find locally */
  23170. if (sipdebug) {
  23171. ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
  23172. }
  23173. /* Fallthrough if we can't find the call leg internally */
  23174. }
  23175. /* Copy data we can not safely access after letting the pvt lock go. */
  23176. refer_to = ast_strdupa(p->refer->refer_to);
  23177. refer_to_context = ast_strdupa(p->refer->refer_to_context);
  23178. ast_party_redirecting_init(&cb_data.redirecting);
  23179. memset(&cb_data.update_redirecting, 0, sizeof(cb_data.update_redirecting));
  23180. change_redirecting_information(p, req, &cb_data.redirecting, &cb_data.update_redirecting, 0);
  23181. cb_data.domain = ast_strdupa(p->refer->refer_to_domain);
  23182. cb_data.referred_by = ast_strdupa(p->refer->referred_by);
  23183. if (!ast_strlen_zero(p->refer->replaces_callid)) {
  23184. replaces_str = ast_str_create(128);
  23185. if (!replaces_str) {
  23186. ast_log(LOG_NOTICE, "Unable to create Replaces string for remote attended transfer. Transfer failed\n");
  23187. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  23188. ast_party_redirecting_free(&cb_data.redirecting);
  23189. return -1;
  23190. }
  23191. ast_str_append(&replaces_str, 0, "%s%s%s%s%s", p->refer->replaces_callid,
  23192. !ast_strlen_zero(p->refer->replaces_callid_totag) ? ";to-tag=" : "",
  23193. S_OR(p->refer->replaces_callid_totag, ""),
  23194. !ast_strlen_zero(p->refer->replaces_callid_fromtag) ? ";from-tag=" : "",
  23195. S_OR(p->refer->replaces_callid_fromtag, ""));
  23196. cb_data.replaces = ast_str_buffer(replaces_str);
  23197. } else {
  23198. cb_data.replaces = NULL;
  23199. }
  23200. if (!*nounlock) {
  23201. ast_channel_unlock(p->owner);
  23202. *nounlock = 1;
  23203. }
  23204. ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23205. sip_pvt_unlock(p);
  23206. transfer_res = ast_bridge_transfer_blind(1, transferer, refer_to, refer_to_context, blind_transfer_cb, &cb_data);
  23207. sip_pvt_lock(p);
  23208. switch (transfer_res) {
  23209. case AST_BRIDGE_TRANSFER_INVALID:
  23210. res = -1;
  23211. p->refer->status = REFER_FAILED;
  23212. transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
  23213. append_history(p, "Xfer", "Refer failed (only bridged calls).");
  23214. ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23215. break;
  23216. case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
  23217. res = -1;
  23218. p->refer->status = REFER_FAILED;
  23219. transmit_notify_with_sipfrag(p, seqno, "403 Forbidden", TRUE);
  23220. append_history(p, "Xfer", "Refer failed (bridge does not permit transfers)");
  23221. ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23222. break;
  23223. case AST_BRIDGE_TRANSFER_FAIL:
  23224. res = -1;
  23225. p->refer->status = REFER_FAILED;
  23226. transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
  23227. append_history(p, "Xfer", "Refer failed (internal error)");
  23228. ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  23229. break;
  23230. case AST_BRIDGE_TRANSFER_SUCCESS:
  23231. res = 0;
  23232. p->refer->status = REFER_200OK;
  23233. transmit_notify_with_sipfrag(p, seqno, "200 OK", TRUE);
  23234. append_history(p, "Xfer", "Refer succeeded.");
  23235. break;
  23236. default:
  23237. break;
  23238. }
  23239. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  23240. ast_party_redirecting_free(&cb_data.redirecting);
  23241. return res;
  23242. }
  23243. /*! \brief Handle incoming CANCEL request */
  23244. static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
  23245. {
  23246. check_via(p, req);
  23247. sip_alreadygone(p);
  23248. if (p->owner && ast_channel_state(p->owner) == AST_STATE_UP) {
  23249. /* This call is up, cancel is ignored, we need a bye */
  23250. transmit_response(p, "200 OK", req);
  23251. ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
  23252. return 0;
  23253. }
  23254. /* At this point, we could have cancelled the invite at the same time
  23255. as the other side sends a CANCEL. Our final reply with error code
  23256. might not have been received by the other side before the CANCEL
  23257. was sent, so let's just give up retransmissions and waiting for
  23258. ACK on our error code. The call is hanging up any way. */
  23259. if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
  23260. __sip_pretend_ack(p);
  23261. }
  23262. if (p->invitestate != INV_TERMINATED)
  23263. p->invitestate = INV_CANCELLED;
  23264. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
  23265. update_call_counter(p, DEC_CALL_LIMIT);
  23266. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  23267. if (p->owner) {
  23268. sip_queue_hangup_cause(p, 0);
  23269. } else {
  23270. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  23271. }
  23272. if (ast_str_strlen(p->initreq.data) > 0) {
  23273. struct sip_pkt *pkt, *prev_pkt;
  23274. /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
  23275. * a reliable 487, then we don't want to schedule another one on top of the previous
  23276. * one.
  23277. *
  23278. * As odd as this may sound, we can't rely on the previously-transmitted "reliable"
  23279. * response in this situation. What if we've sent all of our reliable responses
  23280. * already and now all of a sudden, we get this second CANCEL?
  23281. *
  23282. * The only way to do this correctly is to cancel our previously-scheduled reliably-
  23283. * transmitted response and send a new one in its place.
  23284. */
  23285. for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
  23286. if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
  23287. AST_SCHED_DEL(sched, pkt->retransid);
  23288. UNLINK(pkt, p->packets, prev_pkt);
  23289. dialog_unref(pkt->owner, "unref packet->owner from dialog");
  23290. if (pkt->data) {
  23291. ast_free(pkt->data);
  23292. }
  23293. ast_free(pkt);
  23294. break;
  23295. }
  23296. }
  23297. transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
  23298. transmit_response(p, "200 OK", req);
  23299. return 1;
  23300. } else {
  23301. transmit_response(p, "481 Call Leg Does Not Exist", req);
  23302. return 0;
  23303. }
  23304. }
  23305. /*! \brief Handle incoming BYE request */
  23306. static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
  23307. {
  23308. struct ast_channel *c=NULL;
  23309. int res;
  23310. const char *required;
  23311. RAII_VAR(struct ast_channel *, peer_channel, NULL, ast_channel_cleanup);
  23312. char quality_buf[AST_MAX_USER_FIELD], *quality;
  23313. /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
  23314. if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
  23315. transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
  23316. }
  23317. __sip_pretend_ack(p);
  23318. p->invitestate = INV_TERMINATED;
  23319. copy_request(&p->initreq, req);
  23320. if (sipdebug)
  23321. ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  23322. check_via(p, req);
  23323. sip_alreadygone(p);
  23324. if (p->owner) {
  23325. RAII_VAR(struct ast_channel *, owner_relock, NULL, ast_channel_cleanup);
  23326. RAII_VAR(struct ast_channel *, owner_ref, NULL, ast_channel_cleanup);
  23327. /* Grab a reference to p->owner to prevent it from going away */
  23328. owner_ref = ast_channel_ref(p->owner);
  23329. /* Established locking order here is bridge, channel, pvt
  23330. * and the bridge will be locked during ast_channel_bridge_peer */
  23331. ast_channel_unlock(owner_ref);
  23332. sip_pvt_unlock(p);
  23333. peer_channel = ast_channel_bridge_peer(owner_ref);
  23334. owner_relock = sip_pvt_lock_full(p);
  23335. if (!owner_relock) {
  23336. ast_debug(3, "Unable to reacquire owner channel lock, channel is gone\n");
  23337. return 0;
  23338. }
  23339. }
  23340. /* Get RTCP quality before end of call */
  23341. if (p->rtp) {
  23342. if (p->do_history) {
  23343. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  23344. append_history(p, "RTCPaudio", "Quality:%s", quality);
  23345. }
  23346. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
  23347. append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
  23348. }
  23349. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
  23350. append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
  23351. }
  23352. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
  23353. append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
  23354. }
  23355. }
  23356. if (p->owner) {
  23357. RAII_VAR(struct ast_channel *, owner_relock, NULL, ast_channel_cleanup);
  23358. RAII_VAR(struct ast_channel *, owner_ref, NULL, ast_channel_cleanup);
  23359. struct ast_rtp_instance *p_rtp;
  23360. /* Grab a reference to p->owner to prevent it from going away */
  23361. owner_ref = ast_channel_ref(p->owner);
  23362. p_rtp = p->rtp;
  23363. ao2_ref(p_rtp, +1);
  23364. /* Established locking order here is bridge, channel, pvt
  23365. * and the bridge and channel will be locked during
  23366. * ast_rtp_instance_set_stats_vars */
  23367. ast_channel_unlock(owner_ref);
  23368. sip_pvt_unlock(p);
  23369. ast_rtp_instance_set_stats_vars(owner_ref, p_rtp);
  23370. ao2_ref(p_rtp, -1);
  23371. if (peer_channel) {
  23372. ast_channel_lock(peer_channel);
  23373. if (IS_SIP_TECH(ast_channel_tech(peer_channel))) {
  23374. struct sip_pvt *peer_pvt;
  23375. peer_pvt = ast_channel_tech_pvt(peer_channel);
  23376. if (peer_pvt) {
  23377. ao2_ref(peer_pvt, +1);
  23378. sip_pvt_lock(peer_pvt);
  23379. if (peer_pvt->rtp) {
  23380. struct ast_rtp_instance *peer_rtp;
  23381. peer_rtp = peer_pvt->rtp;
  23382. ao2_ref(peer_rtp, +1);
  23383. ast_channel_unlock(peer_channel);
  23384. sip_pvt_unlock(peer_pvt);
  23385. ast_rtp_instance_set_stats_vars(peer_channel, peer_rtp);
  23386. ao2_ref(peer_rtp, -1);
  23387. ast_channel_lock(peer_channel);
  23388. sip_pvt_lock(peer_pvt);
  23389. }
  23390. sip_pvt_unlock(peer_pvt);
  23391. ao2_ref(peer_pvt, -1);
  23392. }
  23393. }
  23394. ast_channel_unlock(peer_channel);
  23395. }
  23396. owner_relock = sip_pvt_lock_full(p);
  23397. if (!owner_relock) {
  23398. ast_debug(3, "Unable to reacquire owner channel lock, channel is gone\n");
  23399. return 0;
  23400. }
  23401. }
  23402. }
  23403. if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  23404. if (p->do_history) {
  23405. append_history(p, "RTCPvideo", "Quality:%s", quality);
  23406. }
  23407. if (p->owner) {
  23408. pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
  23409. }
  23410. }
  23411. if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  23412. if (p->do_history) {
  23413. append_history(p, "RTCPtext", "Quality:%s", quality);
  23414. }
  23415. if (p->owner) {
  23416. pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
  23417. }
  23418. }
  23419. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  23420. if (p->stimer) {
  23421. stop_session_timer(p); /* Stop Session-Timer */
  23422. }
  23423. if (!ast_strlen_zero(sip_get_header(req, "Also"))) {
  23424. ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
  23425. ast_sockaddr_stringify(&p->recv));
  23426. if (ast_strlen_zero(p->context))
  23427. ast_string_field_set(p, context, sip_cfg.default_context);
  23428. res = get_also_info(p, req);
  23429. if (!res) {
  23430. c = p->owner;
  23431. if (c) {
  23432. if (peer_channel) {
  23433. RAII_VAR(struct ast_channel *, owner_relock, NULL, ast_channel_cleanup);
  23434. char *local_context = ast_strdupa(p->context);
  23435. char *local_refer_to = ast_strdupa(p->refer->refer_to);
  23436. /* Grab a reference to p->owner to prevent it from going away */
  23437. ast_channel_ref(c);
  23438. /* Don't actually hangup here... */
  23439. ast_queue_unhold(c);
  23440. ast_channel_unlock(c); /* async_goto can do a masquerade, no locks can be held during a masq */
  23441. sip_pvt_unlock(p);
  23442. ast_async_goto(peer_channel, local_context, local_refer_to, 1);
  23443. owner_relock = sip_pvt_lock_full(p);
  23444. ast_channel_cleanup(c);
  23445. if (!owner_relock) {
  23446. ast_debug(3, "Unable to reacquire owner channel lock, channel is gone\n");
  23447. return 0;
  23448. }
  23449. } else {
  23450. ast_queue_hangup(p->owner);
  23451. }
  23452. }
  23453. } else {
  23454. ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
  23455. if (p->owner)
  23456. ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
  23457. }
  23458. } else if (p->owner) {
  23459. sip_queue_hangup_cause(p, 0);
  23460. sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
  23461. ast_debug(3, "Received bye, issuing owner hangup\n");
  23462. } else {
  23463. sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
  23464. ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
  23465. }
  23466. ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  23467. /* Find out what they require */
  23468. required = sip_get_header(req, "Require");
  23469. if (!ast_strlen_zero(required)) {
  23470. char unsupported[256] = { 0, };
  23471. parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
  23472. /* If there are any options required that we do not support,
  23473. * then send a 420 with only those unsupported options listed */
  23474. if (!ast_strlen_zero(unsupported)) {
  23475. transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
  23476. ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
  23477. } else {
  23478. transmit_response(p, "200 OK", req);
  23479. }
  23480. } else {
  23481. transmit_response(p, "200 OK", req);
  23482. }
  23483. /* Destroy any pending invites so we won't try to do another
  23484. * scheduled reINVITE. */
  23485. AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "decrement refcount from sip_destroy because waitid won't be scheduled"));
  23486. return 1;
  23487. }
  23488. /*! \brief Handle incoming MESSAGE request */
  23489. static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
  23490. {
  23491. if (!req->ignore) {
  23492. if (req->debug)
  23493. ast_verbose("Receiving message!\n");
  23494. receive_message(p, req, addr, e);
  23495. } else
  23496. transmit_response(p, "202 Accepted", req);
  23497. return 1;
  23498. }
  23499. static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from);
  23500. static const struct ast_msg_tech sip_msg_tech = {
  23501. .name = "sip",
  23502. .msg_send = sip_msg_send,
  23503. };
  23504. /*!
  23505. * \internal
  23506. * \brief Check if the given header name is blocked.
  23507. *
  23508. * \details Determine if the given header name from the user is
  23509. * blocked for outgoing MESSAGE packets.
  23510. *
  23511. * \param header_name Name of header to see if it is blocked.
  23512. *
  23513. * \retval TRUE if the given header is blocked.
  23514. */
  23515. static int block_msg_header(const char *header_name)
  23516. {
  23517. int idx;
  23518. /*
  23519. * Don't block Content-Type or Max-Forwards headers because the
  23520. * user can override them.
  23521. */
  23522. static const char *hdr[] = {
  23523. "To",
  23524. "From",
  23525. "Via",
  23526. "Route",
  23527. "Contact",
  23528. "Call-ID",
  23529. "CSeq",
  23530. "Allow",
  23531. "Content-Length",
  23532. "Request-URI",
  23533. };
  23534. for (idx = 0; idx < ARRAY_LEN(hdr); ++idx) {
  23535. if (!strcasecmp(header_name, hdr[idx])) {
  23536. /* Block addition of this header. */
  23537. return 1;
  23538. }
  23539. }
  23540. return 0;
  23541. }
  23542. static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from)
  23543. {
  23544. struct sip_pvt *pvt;
  23545. int res;
  23546. char *to_uri;
  23547. char *to_host;
  23548. char *to_user;
  23549. const char *var;
  23550. const char *val;
  23551. struct ast_msg_var_iterator *iter;
  23552. struct sip_peer *peer_ptr;
  23553. if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_MESSAGE, NULL, NULL))) {
  23554. return -1;
  23555. }
  23556. for (iter = ast_msg_var_iterator_init(msg);
  23557. ast_msg_var_iterator_next(msg, iter, &var, &val);
  23558. ast_msg_var_unref_current(iter)) {
  23559. if (!strcasecmp(var, "Request-URI")) {
  23560. ast_string_field_set(pvt, fullcontact, val);
  23561. break;
  23562. }
  23563. }
  23564. ast_msg_var_iterator_destroy(iter);
  23565. to_uri = ast_strdupa(to);
  23566. to_uri = get_in_brackets(to_uri);
  23567. parse_uri(to_uri, "sip:,sips:", &to_user, NULL, &to_host, NULL);
  23568. if (ast_strlen_zero(to_host)) {
  23569. ast_log(LOG_WARNING, "MESSAGE(to) is invalid for SIP - '%s'\n", to);
  23570. dialog_unlink_all(pvt);
  23571. dialog_unref(pvt, "MESSAGE(to) is invalid for SIP");
  23572. return -1;
  23573. }
  23574. if (!ast_strlen_zero(from)) {
  23575. if ((peer_ptr = sip_find_peer(from, NULL, 0, 1, 0, 0))) {
  23576. ast_string_field_set(pvt, fromname, S_OR(peer_ptr->cid_name, peer_ptr->name));
  23577. ast_string_field_set(pvt, fromuser, S_OR(peer_ptr->cid_num, peer_ptr->name));
  23578. sip_unref_peer(peer_ptr, "sip_unref_peer, from sip_msg_send, sip_find_peer");
  23579. } else if (strchr(from, '<')) { /* from is callerid-style */
  23580. char *sender;
  23581. char *name = NULL, *location = NULL, *user = NULL, *domain = NULL;
  23582. sender = ast_strdupa(from);
  23583. ast_callerid_parse(sender, &name, &location);
  23584. if (ast_strlen_zero(location)) {
  23585. /* This can occur if either
  23586. * 1) A name-addr style From header does not close the angle brackets
  23587. * properly.
  23588. * 2) The From header is not in name-addr style and the content of the
  23589. * From contains characters other than 0-9, *, #, or +.
  23590. *
  23591. * In both cases, ast_callerid_parse() should have parsed the From header
  23592. * as a name rather than a number. So we just need to set the location
  23593. * to what was parsed as a name, and set the name NULL since there was
  23594. * no name present.
  23595. */
  23596. location = name;
  23597. name = NULL;
  23598. }
  23599. ast_string_field_set(pvt, fromname, name);
  23600. if (strchr(location, ':')) { /* Must be a URI */
  23601. parse_uri(location, "sip:,sips:", &user, NULL, &domain, NULL);
  23602. SIP_PEDANTIC_DECODE(user);
  23603. SIP_PEDANTIC_DECODE(domain);
  23604. extract_host_from_hostport(&domain);
  23605. ast_string_field_set(pvt, fromuser, user);
  23606. ast_string_field_set(pvt, fromdomain, domain);
  23607. } else { /* Treat it as an exten/user */
  23608. ast_string_field_set(pvt, fromuser, location);
  23609. }
  23610. } else { /* assume we just have the name, use defaults for the rest */
  23611. ast_string_field_set(pvt, fromname, from);
  23612. }
  23613. }
  23614. sip_pvt_lock(pvt);
  23615. /* Look up the host to contact */
  23616. if (create_addr(pvt, to_host, NULL, TRUE)) {
  23617. sip_pvt_unlock(pvt);
  23618. dialog_unlink_all(pvt);
  23619. dialog_unref(pvt, "create_addr failed sending a MESSAGE");
  23620. return -1;
  23621. }
  23622. if (!ast_strlen_zero(to_user)) {
  23623. ast_string_field_set(pvt, username, to_user);
  23624. }
  23625. ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
  23626. build_via(pvt);
  23627. ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
  23628. /* XXX Does pvt->expiry need to be set? */
  23629. /* Save additional MESSAGE headers in case of authentication request. */
  23630. for (iter = ast_msg_var_iterator_init(msg);
  23631. ast_msg_var_iterator_next(msg, iter, &var, &val);
  23632. ast_msg_var_unref_current(iter)) {
  23633. if (!strcasecmp(var, "Max-Forwards")) {
  23634. /* Decrement Max-Forwards for SIP loop prevention. */
  23635. if (sscanf(val, "%30d", &pvt->maxforwards) != 1 || pvt->maxforwards < 1) {
  23636. ast_msg_var_iterator_destroy(iter);
  23637. sip_pvt_unlock(pvt);
  23638. dialog_unlink_all(pvt);
  23639. dialog_unref(pvt, "MESSAGE(Max-Forwards) reached zero.");
  23640. ast_log(LOG_NOTICE,
  23641. "MESSAGE(Max-Forwards) reached zero. MESSAGE not sent.\n");
  23642. return -1;
  23643. }
  23644. --pvt->maxforwards;
  23645. continue;
  23646. }
  23647. if (block_msg_header(var)) {
  23648. /* Block addition of this header. */
  23649. continue;
  23650. }
  23651. add_msg_header(pvt, var, val);
  23652. }
  23653. ast_msg_var_iterator_destroy(iter);
  23654. ast_string_field_set(pvt, msg_body, ast_msg_get_body(msg));
  23655. res = transmit_message(pvt, 1, 0);
  23656. sip_pvt_unlock(pvt);
  23657. sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
  23658. dialog_unref(pvt, "sent a MESSAGE");
  23659. return res;
  23660. }
  23661. 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)
  23662. {
  23663. int etag_present = !ast_strlen_zero(etag);
  23664. int body_present = req->lines > 0;
  23665. ast_assert(expires_int != NULL);
  23666. if (ast_strlen_zero(expires)) {
  23667. /* Section 6, item 4, second bullet point of RFC 3903 says to
  23668. * use a locally-configured default expiration if none is provided
  23669. * in the request
  23670. */
  23671. *expires_int = DEFAULT_PUBLISH_EXPIRES;
  23672. } else if (sscanf(expires, "%30d", expires_int) != 1) {
  23673. return SIP_PUBLISH_UNKNOWN;
  23674. }
  23675. if (*expires_int == 0) {
  23676. return SIP_PUBLISH_REMOVE;
  23677. } else if (!etag_present && body_present) {
  23678. return SIP_PUBLISH_INITIAL;
  23679. } else if (etag_present && !body_present) {
  23680. return SIP_PUBLISH_REFRESH;
  23681. } else if (etag_present && body_present) {
  23682. return SIP_PUBLISH_MODIFY;
  23683. }
  23684. return SIP_PUBLISH_UNKNOWN;
  23685. }
  23686. #ifdef HAVE_LIBXML2
  23687. static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
  23688. {
  23689. const char *id;
  23690. int status_found = FALSE;
  23691. struct ast_xml_node *tuple_children;
  23692. struct ast_xml_node *tuple_children_iterator;
  23693. /* Tuples have to have an id attribute or they're invalid */
  23694. if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
  23695. ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
  23696. return FALSE;
  23697. }
  23698. /* We don't care what it actually is, just that it's there */
  23699. ast_xml_free_attr(id);
  23700. /* This is a tuple. It must have a status element */
  23701. if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
  23702. /* The tuple has no children. It sucks */
  23703. ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
  23704. return FALSE;
  23705. }
  23706. for (tuple_children_iterator = tuple_children; tuple_children_iterator;
  23707. tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
  23708. /* Similar to the wording used regarding tuples, the status element should appear
  23709. * first. However, we will once again relax things and accept the status at any
  23710. * position. We will enforce that only a single status element can be present.
  23711. */
  23712. if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
  23713. /* Not the status, we don't care */
  23714. continue;
  23715. }
  23716. if (status_found == TRUE) {
  23717. /* THERE CAN BE ONLY ONE!!! */
  23718. ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
  23719. return FALSE;
  23720. }
  23721. status_found = TRUE;
  23722. }
  23723. return status_found;
  23724. }
  23725. static int pidf_validate_presence(struct ast_xml_doc *doc)
  23726. {
  23727. struct ast_xml_node *presence_node = ast_xml_get_root(doc);
  23728. struct ast_xml_node *child_nodes;
  23729. struct ast_xml_node *node_iterator;
  23730. struct ast_xml_ns *ns;
  23731. const char *entity;
  23732. const char *namespace;
  23733. const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
  23734. if (!presence_node) {
  23735. ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
  23736. return FALSE;
  23737. }
  23738. /* Okay, we managed to open the document! YAY! Now, let's start making sure it's all PIDF-ified
  23739. * correctly.
  23740. */
  23741. if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
  23742. ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
  23743. return FALSE;
  23744. }
  23745. /* The presence element must have an entity attribute and an xmlns attribute. Furthermore
  23746. * the xmlns attribute must be "urn:ietf:params:xml:ns:pidf"
  23747. */
  23748. if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
  23749. ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
  23750. return FALSE;
  23751. }
  23752. /* We're not interested in what the entity is, just that it exists */
  23753. ast_xml_free_attr(entity);
  23754. if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
  23755. ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
  23756. return FALSE;
  23757. }
  23758. namespace = ast_xml_get_ns_href(ns);
  23759. if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
  23760. ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
  23761. return FALSE;
  23762. }
  23763. if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
  23764. ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
  23765. return FALSE;
  23766. }
  23767. /* Check for tuple elements. RFC 3863 says that PIDF documents can have any number of
  23768. * tuples, including 0. The big thing here is that if there are tuple elements present,
  23769. * they have to have a single status element within.
  23770. *
  23771. * The RFC is worded such that tuples should appear as the first elements as children of
  23772. * the presence element. However, we'll be accepting of documents which may place other elements
  23773. * before the tuple(s).
  23774. */
  23775. for (node_iterator = child_nodes; node_iterator;
  23776. node_iterator = ast_xml_node_get_next(node_iterator)) {
  23777. if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
  23778. /* Not a tuple. We don't give a rat's hind quarters */
  23779. continue;
  23780. }
  23781. if (pidf_validate_tuple(node_iterator) == FALSE) {
  23782. ast_log(LOG_WARNING, "Unable to validate tuple\n");
  23783. return FALSE;
  23784. }
  23785. }
  23786. return TRUE;
  23787. }
  23788. /*!
  23789. * \brief Makes sure that body is properly formatted PIDF
  23790. *
  23791. * Specifically, we check that the document has a "presence" element
  23792. * at the root and that within that, there is at least one "tuple" element
  23793. * that contains a "status" element.
  23794. *
  23795. * XXX This function currently assumes a default namespace is used. Of course
  23796. * if you're not using a default namespace, you're probably a stupid jerk anyway.
  23797. *
  23798. * \param req The SIP request to check
  23799. * \param[out] pidf_doc The validated PIDF doc.
  23800. * \retval FALSE The XML was malformed or the basic PIDF structure was marred
  23801. * \retval TRUE The PIDF document is of a valid format
  23802. */
  23803. static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
  23804. {
  23805. struct ast_xml_doc *doc;
  23806. const char *content_type = sip_get_header(req, "Content-Type");
  23807. char *pidf_body;
  23808. int res;
  23809. if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
  23810. ast_log(LOG_WARNING, "Content type is not PIDF\n");
  23811. return FALSE;
  23812. }
  23813. if (!(pidf_body = get_content(req))) {
  23814. ast_log(LOG_WARNING, "Unable to get PIDF body\n");
  23815. return FALSE;
  23816. }
  23817. if (!(doc = ast_xml_read_memory(pidf_body, strlen(pidf_body)))) {
  23818. ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
  23819. return FALSE;
  23820. }
  23821. res = pidf_validate_presence(doc);
  23822. if (res == TRUE) {
  23823. *pidf_doc = doc;
  23824. } else {
  23825. ast_xml_close(doc);
  23826. }
  23827. return res;
  23828. }
  23829. 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)
  23830. {
  23831. const char *uri = REQ_OFFSET_TO_STR(req, rlpart2);
  23832. struct ast_cc_agent *agent;
  23833. struct sip_cc_agent_pvt *agent_pvt;
  23834. struct ast_xml_doc *pidf_doc = NULL;
  23835. const char *basic_status = NULL;
  23836. struct ast_xml_node *presence_node;
  23837. struct ast_xml_node *presence_children;
  23838. struct ast_xml_node *tuple_node;
  23839. struct ast_xml_node *tuple_children;
  23840. struct ast_xml_node *status_node;
  23841. struct ast_xml_node *status_children;
  23842. struct ast_xml_node *basic_node;
  23843. int res = 0;
  23844. if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
  23845. ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
  23846. transmit_response(pvt, "412 Conditional Request Failed", req);
  23847. return -1;
  23848. }
  23849. agent_pvt = agent->private_data;
  23850. if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
  23851. res = -1;
  23852. goto cc_publish_cleanup;
  23853. }
  23854. /* It's important to note that the PIDF validation routine has no knowledge
  23855. * of what we specifically want in this instance. A valid PIDF document could
  23856. * have no tuples, or it could have tuples whose status element has no basic
  23857. * element contained within. While not violating the PIDF spec, these are
  23858. * insufficient for our needs in this situation
  23859. */
  23860. presence_node = ast_xml_get_root(pidf_doc);
  23861. if (!(presence_children = ast_xml_node_get_children(presence_node))) {
  23862. ast_log(LOG_WARNING, "No tuples within presence element.\n");
  23863. res = -1;
  23864. goto cc_publish_cleanup;
  23865. }
  23866. if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
  23867. ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
  23868. res = -1;
  23869. goto cc_publish_cleanup;
  23870. }
  23871. /* We already made sure that the tuple has a status node when we validated the PIDF
  23872. * document earlier. So there's no need to enclose this operation in an if statement.
  23873. */
  23874. tuple_children = ast_xml_node_get_children(tuple_node);
  23875. /* coverity[null_returns: FALSE] */
  23876. status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
  23877. if (!(status_children = ast_xml_node_get_children(status_node))) {
  23878. ast_log(LOG_WARNING, "No basic elements within status element.\n");
  23879. res = -1;
  23880. goto cc_publish_cleanup;
  23881. }
  23882. if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
  23883. ast_log(LOG_WARNING, "Couldn't find basic node?\n");
  23884. res = -1;
  23885. goto cc_publish_cleanup;
  23886. }
  23887. basic_status = ast_xml_get_text(basic_node);
  23888. if (ast_strlen_zero(basic_status)) {
  23889. ast_log(LOG_NOTICE, "NOthing in basic node?\n");
  23890. res = -1;
  23891. goto cc_publish_cleanup;
  23892. }
  23893. if (!strcmp(basic_status, "open")) {
  23894. agent_pvt->is_available = TRUE;
  23895. ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
  23896. agent->device_name);
  23897. } else if (!strcmp(basic_status, "closed")) {
  23898. agent_pvt->is_available = FALSE;
  23899. ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
  23900. agent->device_name);
  23901. } else {
  23902. ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
  23903. }
  23904. cc_publish_cleanup:
  23905. if (basic_status) {
  23906. ast_xml_free_text(basic_status);
  23907. }
  23908. if (pidf_doc) {
  23909. ast_xml_close(pidf_doc);
  23910. }
  23911. ao2_ref(agent, -1);
  23912. if (res) {
  23913. transmit_response(pvt, "400 Bad Request", req);
  23914. }
  23915. return res;
  23916. }
  23917. #endif /* HAVE_LIBXML2 */
  23918. static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
  23919. {
  23920. struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
  23921. int res = 0;
  23922. if (!esc_entry) {
  23923. transmit_response(p, "503 Internal Server Failure", req);
  23924. return -1;
  23925. }
  23926. if (esc->callbacks->initial_handler) {
  23927. res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
  23928. }
  23929. if (!res) {
  23930. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
  23931. }
  23932. ao2_ref(esc_entry, -1);
  23933. return res;
  23934. }
  23935. 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)
  23936. {
  23937. struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
  23938. int expires_ms = expires * 1000;
  23939. int res = 0;
  23940. if (!esc_entry) {
  23941. transmit_response(p, "412 Conditional Request Failed", req);
  23942. return -1;
  23943. }
  23944. AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
  23945. ao2_ref(_data, -1),
  23946. ao2_ref(esc_entry, -1),
  23947. ao2_ref(esc_entry, +1));
  23948. if (esc->callbacks->refresh_handler) {
  23949. res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
  23950. }
  23951. if (!res) {
  23952. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
  23953. }
  23954. ao2_ref(esc_entry, -1);
  23955. return res;
  23956. }
  23957. 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)
  23958. {
  23959. struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
  23960. int expires_ms = expires * 1000;
  23961. int res = 0;
  23962. if (!esc_entry) {
  23963. transmit_response(p, "412 Conditional Request Failed", req);
  23964. return -1;
  23965. }
  23966. AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
  23967. ao2_ref(_data, -1),
  23968. ao2_ref(esc_entry, -1),
  23969. ao2_ref(esc_entry, +1));
  23970. if (esc->callbacks->modify_handler) {
  23971. res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
  23972. }
  23973. if (!res) {
  23974. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
  23975. }
  23976. ao2_ref(esc_entry, -1);
  23977. return res;
  23978. }
  23979. static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
  23980. {
  23981. struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
  23982. int res = 0;
  23983. if (!esc_entry) {
  23984. transmit_response(p, "412 Conditional Request Failed", req);
  23985. return -1;
  23986. }
  23987. AST_SCHED_DEL(sched, esc_entry->sched_id);
  23988. /* Scheduler's ref of the esc_entry */
  23989. ao2_ref(esc_entry, -1);
  23990. if (esc->callbacks->remove_handler) {
  23991. res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
  23992. }
  23993. if (!res) {
  23994. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
  23995. }
  23996. /* Ref from finding the esc_entry earlier in function */
  23997. ao2_unlink(esc->compositor, esc_entry);
  23998. ao2_ref(esc_entry, -1);
  23999. return res;
  24000. }
  24001. static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
  24002. {
  24003. const char *etag = sip_get_header(req, "SIP-If-Match");
  24004. const char *event = sip_get_header(req, "Event");
  24005. struct event_state_compositor *esc;
  24006. enum sip_publish_type publish_type;
  24007. const char *expires_str = sip_get_header(req, "Expires");
  24008. int expires_int;
  24009. int auth_result;
  24010. int handler_result = -1;
  24011. if (ast_strlen_zero(event)) {
  24012. transmit_response(p, "489 Bad Event", req);
  24013. pvt_set_needdestroy(p, "missing Event: header");
  24014. return -1;
  24015. }
  24016. if (!(esc = get_esc(event))) {
  24017. transmit_response(p, "489 Bad Event", req);
  24018. pvt_set_needdestroy(p, "unknown event package in publish");
  24019. return -1;
  24020. }
  24021. auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_UNRELIABLE, addr);
  24022. if (auth_result == AUTH_CHALLENGE_SENT) {
  24023. p->lastinvite = seqno;
  24024. return 0;
  24025. } else if (auth_result < 0) {
  24026. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
  24027. transmit_response(p, "403 Forbidden", req);
  24028. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  24029. ast_string_field_set(p, theirtag, NULL);
  24030. return 0;
  24031. } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
  24032. /* We need to stop retransmitting the 401 */
  24033. __sip_ack(p, p->lastinvite, 1, 0);
  24034. }
  24035. publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
  24036. if (expires_int > max_expiry) {
  24037. expires_int = max_expiry;
  24038. } else if (expires_int < min_expiry && expires_int > 0) {
  24039. transmit_response_with_minexpires(p, "423 Interval too small", req, min_expiry);
  24040. pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
  24041. return 0;
  24042. }
  24043. p->expiry = expires_int;
  24044. /* It is the responsibility of these handlers to formulate any response
  24045. * sent for a PUBLISH
  24046. */
  24047. switch (publish_type) {
  24048. case SIP_PUBLISH_UNKNOWN:
  24049. transmit_response(p, "400 Bad Request", req);
  24050. break;
  24051. case SIP_PUBLISH_INITIAL:
  24052. handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
  24053. break;
  24054. case SIP_PUBLISH_REFRESH:
  24055. handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
  24056. break;
  24057. case SIP_PUBLISH_MODIFY:
  24058. handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
  24059. break;
  24060. case SIP_PUBLISH_REMOVE:
  24061. handler_result = handle_sip_publish_remove(p, req, esc, etag);
  24062. break;
  24063. default:
  24064. transmit_response(p, "400 Impossible Condition", req);
  24065. break;
  24066. }
  24067. if (!handler_result && p->expiry > 0) {
  24068. sip_scheddestroy(p, (p->expiry + 10) * 1000);
  24069. } else {
  24070. pvt_set_needdestroy(p, "forcing expiration");
  24071. }
  24072. return handler_result;
  24073. }
  24074. /*!
  24075. * \internal
  24076. * \brief Subscribe to MWI events for the specified peer
  24077. *
  24078. * \note The peer cannot be locked during this method. sip_send_mwi_peer will
  24079. * attempt to lock the peer after the event subscription lock is held; if the peer is locked during
  24080. * this method then we will attempt to lock the event subscription lock but after the peer, creating
  24081. * a locking inversion.
  24082. */
  24083. static void add_peer_mwi_subs(struct sip_peer *peer)
  24084. {
  24085. struct sip_mailbox *mailbox;
  24086. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  24087. struct stasis_topic *mailbox_specific_topic;
  24088. mailbox->event_sub = stasis_unsubscribe(mailbox->event_sub);
  24089. mailbox_specific_topic = ast_mwi_topic(mailbox->id);
  24090. if (mailbox_specific_topic) {
  24091. char *peer_name = ast_strdup(peer->name);
  24092. if (!peer_name) {
  24093. return;
  24094. }
  24095. mailbox->event_sub = stasis_subscribe(mailbox_specific_topic, mwi_event_cb, peer_name);
  24096. }
  24097. }
  24098. }
  24099. static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
  24100. {
  24101. const char *uri = REQ_OFFSET_TO_STR(req, rlpart2);
  24102. char *param_separator;
  24103. struct ast_cc_agent *agent;
  24104. struct sip_cc_agent_pvt *agent_pvt;
  24105. const char *expires_str = sip_get_header(req, "Expires");
  24106. int expires = -1; /* Just need it to be non-zero */
  24107. if (!ast_strlen_zero(expires_str)) {
  24108. sscanf(expires_str, "%30d", &expires);
  24109. }
  24110. if ((param_separator = strchr(uri, ';'))) {
  24111. *param_separator = '\0';
  24112. }
  24113. p->subscribed = CALL_COMPLETION;
  24114. if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
  24115. if (!expires) {
  24116. /* Typically, if a 0 Expires reaches us and we can't find
  24117. * the corresponding agent, it means that the CC transaction
  24118. * has completed and so the calling side is just trying to
  24119. * clean up its subscription. We'll just respond with a
  24120. * 200 OK and be done with it
  24121. */
  24122. transmit_response(p, "200 OK", req);
  24123. return 0;
  24124. }
  24125. ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
  24126. transmit_response(p, "404 Not Found", req);
  24127. return -1;
  24128. }
  24129. agent_pvt = agent->private_data;
  24130. if (!expires) {
  24131. /* We got sent a SUBSCRIBE and found an agent. This means that CC
  24132. * is being canceled.
  24133. */
  24134. ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
  24135. transmit_response(p, "200 OK", req);
  24136. ao2_ref(agent, -1);
  24137. return 0;
  24138. }
  24139. agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
  24140. ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
  24141. agent->device_name);
  24142. /* We don't send a response here. That is done in the agent's ack callback or in the
  24143. * agent destructor, should a failure occur before we have responded
  24144. */
  24145. ao2_ref(agent, -1);
  24146. return 0;
  24147. }
  24148. /*! \brief Handle incoming SUBSCRIBE request */
  24149. static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
  24150. {
  24151. int res = 0;
  24152. struct sip_peer *authpeer = NULL;
  24153. char *event = ast_strdupa(sip_get_header(req, "Event")); /* Get Event package name */
  24154. int resubscribe = (p->subscribed != NONE) && !req->ignore;
  24155. char *options;
  24156. if (p->initreq.headers) {
  24157. /* We already have a dialog */
  24158. if (p->initreq.method != SIP_SUBSCRIBE) {
  24159. /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
  24160. /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
  24161. transmit_response(p, "403 Forbidden (within dialog)", req);
  24162. /* Do not destroy session, since we will break the call if we do */
  24163. 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);
  24164. return 0;
  24165. } else if (req->debug) {
  24166. if (resubscribe)
  24167. ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
  24168. else
  24169. ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
  24170. }
  24171. }
  24172. /* Check if we have a global disallow setting on subscriptions.
  24173. if so, we don't have to check peer settings after auth, which saves a lot of processing
  24174. */
  24175. if (!sip_cfg.allowsubscribe) {
  24176. transmit_response(p, "403 Forbidden (policy)", req);
  24177. pvt_set_needdestroy(p, "forbidden");
  24178. return 0;
  24179. }
  24180. if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
  24181. const char *to = sip_get_header(req, "To");
  24182. char totag[128];
  24183. set_pvt_allowed_methods(p, req);
  24184. /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
  24185. if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
  24186. if (req->debug)
  24187. ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
  24188. transmit_response(p, "481 Subscription does not exist", req);
  24189. pvt_set_needdestroy(p, "subscription does not exist");
  24190. return 0;
  24191. }
  24192. /* Use this as the basis */
  24193. if (req->debug)
  24194. ast_verbose("Creating new subscription\n");
  24195. copy_request(&p->initreq, req);
  24196. if (sipdebug)
  24197. ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  24198. check_via(p, req);
  24199. build_route(p, req, 0, 0);
  24200. } else if (req->debug && req->ignore)
  24201. ast_verbose("Ignoring this SUBSCRIBE request\n");
  24202. /* Find parameters to Event: header value and remove them for now */
  24203. if (ast_strlen_zero(event)) {
  24204. transmit_response(p, "489 Bad Event", req);
  24205. ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
  24206. pvt_set_needdestroy(p, "unknown event package in subscribe");
  24207. return 0;
  24208. }
  24209. if ((options = strchr(event, ';')) != NULL) {
  24210. *options++ = '\0';
  24211. }
  24212. /* Handle authentication if we're new and not a retransmission. We can't just
  24213. * use if !req->ignore, because then we'll end up sending
  24214. * a 200 OK if someone retransmits without sending auth */
  24215. if (p->subscribed == NONE || resubscribe) {
  24216. res = check_user_full(p, req, SIP_SUBSCRIBE, e, XMIT_UNRELIABLE, addr, &authpeer);
  24217. /* if an authentication response was sent, we are done here */
  24218. if (res == AUTH_CHALLENGE_SENT) /* authpeer = NULL here */
  24219. return 0;
  24220. if (res != AUTH_SUCCESSFUL) {
  24221. ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", sip_get_header(req, "From"));
  24222. transmit_response(p, "403 Forbidden", req);
  24223. pvt_set_needdestroy(p, "authentication failed");
  24224. return 0;
  24225. }
  24226. }
  24227. /* At this point, we hold a reference to authpeer (if not NULL). It
  24228. * must be released when done.
  24229. */
  24230. /* Check if this device is allowed to subscribe at all */
  24231. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
  24232. transmit_response(p, "403 Forbidden (policy)", req);
  24233. pvt_set_needdestroy(p, "subscription not allowed");
  24234. if (authpeer) {
  24235. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 1)");
  24236. }
  24237. return 0;
  24238. }
  24239. /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
  24240. parse_ok_contact(p, req);
  24241. build_contact(p);
  24242. /* Initialize tag for new subscriptions */
  24243. if (ast_strlen_zero(p->tag)) {
  24244. make_our_tag(p);
  24245. }
  24246. if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
  24247. int gotdest;
  24248. const char *accept;
  24249. int start = 0;
  24250. enum subscriptiontype subscribed = NONE;
  24251. const char *unknown_accept = NULL;
  24252. /* Get destination right away */
  24253. gotdest = get_destination(p, NULL, NULL);
  24254. if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
  24255. if (gotdest == SIP_GET_DEST_INVALID_URI) {
  24256. transmit_response(p, "416 Unsupported URI scheme", req);
  24257. } else {
  24258. transmit_response(p, "404 Not Found", req);
  24259. }
  24260. pvt_set_needdestroy(p, "subscription target not found");
  24261. if (authpeer) {
  24262. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
  24263. }
  24264. return 0;
  24265. }
  24266. /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
  24267. accept = __get_header(req, "Accept", &start);
  24268. while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
  24269. if (strstr(accept, "application/pidf+xml")) {
  24270. if (strstr(p->useragent, "Polycom")) {
  24271. subscribed = XPIDF_XML; /* Older versions of Polycom firmware will claim pidf+xml, but really they only support xpidf+xml */
  24272. } else {
  24273. subscribed = PIDF_XML; /* RFC 3863 format */
  24274. }
  24275. } else if (strstr(accept, "application/dialog-info+xml")) {
  24276. subscribed = DIALOG_INFO_XML;
  24277. /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
  24278. } else if (strstr(accept, "application/cpim-pidf+xml")) {
  24279. subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
  24280. } else if (strstr(accept, "application/xpidf+xml")) {
  24281. subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
  24282. } else {
  24283. unknown_accept = accept;
  24284. }
  24285. /* check to see if there is another Accept header present */
  24286. accept = __get_header(req, "Accept", &start);
  24287. }
  24288. if (!start) {
  24289. if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
  24290. transmit_response(p, "489 Bad Event", req);
  24291. ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
  24292. "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
  24293. "'%s', subscribeuri: '%s'\n",
  24294. p->stateid,
  24295. p->laststate,
  24296. p->dialogver,
  24297. p->subscribecontext,
  24298. p->subscribeuri);
  24299. pvt_set_needdestroy(p, "no Accept header");
  24300. if (authpeer) {
  24301. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
  24302. }
  24303. return 0;
  24304. }
  24305. /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
  24306. so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
  24307. } else if (subscribed == NONE) {
  24308. /* Can't find a format for events that we know about */
  24309. char buf[200];
  24310. if (!ast_strlen_zero(unknown_accept)) {
  24311. snprintf(buf, sizeof(buf), "489 Bad Event (format %s)", unknown_accept);
  24312. } else {
  24313. snprintf(buf, sizeof(buf), "489 Bad Event");
  24314. }
  24315. transmit_response(p, buf, req);
  24316. ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
  24317. "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
  24318. "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
  24319. unknown_accept,
  24320. (int)p->subscribed,
  24321. p->stateid,
  24322. p->laststate,
  24323. p->dialogver,
  24324. p->subscribecontext,
  24325. p->subscribeuri);
  24326. pvt_set_needdestroy(p, "unrecognized format");
  24327. if (authpeer) {
  24328. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
  24329. }
  24330. return 0;
  24331. } else {
  24332. p->subscribed = subscribed;
  24333. }
  24334. } else if (!strcmp(event, "message-summary")) {
  24335. int start = 0;
  24336. int found_supported = 0;
  24337. const char *accept;
  24338. accept = __get_header(req, "Accept", &start);
  24339. while (!found_supported && !ast_strlen_zero(accept)) {
  24340. found_supported = strcmp(accept, "application/simple-message-summary") ? 0 : 1;
  24341. if (!found_supported) {
  24342. ast_debug(3, "Received SIP mailbox subscription for unknown format: %s\n", accept);
  24343. }
  24344. accept = __get_header(req, "Accept", &start);
  24345. }
  24346. /* If !start, there is no Accept header at all */
  24347. if (start && !found_supported) {
  24348. /* Format requested that we do not support */
  24349. transmit_response(p, "406 Not Acceptable", req);
  24350. ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", accept);
  24351. pvt_set_needdestroy(p, "unknown format");
  24352. if (authpeer) {
  24353. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 3)");
  24354. }
  24355. return 0;
  24356. }
  24357. /* Looks like they actually want a mailbox status
  24358. This version of Asterisk supports mailbox subscriptions
  24359. The subscribed URI needs to exist in the dial plan
  24360. In most devices, this is configurable to the voicemailmain extension you use
  24361. */
  24362. if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
  24363. if (!authpeer) {
  24364. transmit_response(p, "404 Not found", req);
  24365. } else {
  24366. transmit_response(p, "404 Not found (no mailbox)", req);
  24367. ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
  24368. }
  24369. pvt_set_needdestroy(p, "received 404 response");
  24370. if (authpeer) {
  24371. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 3)");
  24372. }
  24373. return 0;
  24374. }
  24375. p->subscribed = MWI_NOTIFICATION;
  24376. if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
  24377. ao2_unlock(p);
  24378. add_peer_mwi_subs(authpeer);
  24379. ao2_lock(p);
  24380. }
  24381. if (authpeer->mwipvt != p) { /* Destroy old PVT if this is a new one */
  24382. /* We only allow one subscription per peer */
  24383. if (authpeer->mwipvt) {
  24384. dialog_unlink_all(authpeer->mwipvt);
  24385. authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
  24386. }
  24387. authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
  24388. }
  24389. if (p->relatedpeer != authpeer) {
  24390. if (p->relatedpeer) {
  24391. sip_unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
  24392. }
  24393. p->relatedpeer = sip_ref_peer(authpeer, "setting dialog's relatedpeer pointer");
  24394. }
  24395. /* Do not release authpeer here */
  24396. } else if (!strcmp(event, "call-completion")) {
  24397. handle_cc_subscribe(p, req);
  24398. } else { /* At this point, Asterisk does not understand the specified event */
  24399. transmit_response(p, "489 Bad Event", req);
  24400. ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
  24401. pvt_set_needdestroy(p, "unknown event package");
  24402. if (authpeer) {
  24403. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 5)");
  24404. }
  24405. return 0;
  24406. }
  24407. if (!req->ignore) {
  24408. p->lastinvite = seqno;
  24409. }
  24410. if (!p->needdestroy) {
  24411. p->expiry = atoi(sip_get_header(req, "Expires"));
  24412. /* check if the requested expiry-time is within the approved limits from sip.conf */
  24413. if (p->expiry > max_subexpiry) {
  24414. p->expiry = max_subexpiry;
  24415. } else if (p->expiry < min_subexpiry && p->expiry > 0) {
  24416. transmit_response_with_minexpires(p, "423 Interval too small", req, min_subexpiry);
  24417. ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
  24418. "with Expire header less than 'subminexpire' limit. Received \"Expire: %d\" min is %d\n",
  24419. p->exten, p->context, p->expiry, min_subexpiry);
  24420. pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
  24421. if (authpeer) {
  24422. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 6)");
  24423. }
  24424. return 0;
  24425. }
  24426. if (sipdebug) {
  24427. const char *action = p->expiry > 0 ? "Adding" : "Removing";
  24428. if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
  24429. ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
  24430. action, p->relatedpeer->name);
  24431. } else if (p->subscribed == CALL_COMPLETION) {
  24432. ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
  24433. } else {
  24434. ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
  24435. action, p->exten, p->context, p->username);
  24436. }
  24437. }
  24438. if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
  24439. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  24440. if (p->expiry > 0)
  24441. sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
  24442. if (p->subscribed == MWI_NOTIFICATION) {
  24443. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  24444. transmit_response(p, "200 OK", req);
  24445. if (p->relatedpeer) { /* Send first notification */
  24446. struct sip_peer *peer = p->relatedpeer;
  24447. sip_ref_peer(peer, "ensure a peer ref is held during MWI sending");
  24448. ao2_unlock(p);
  24449. sip_send_mwi_to_peer(peer, 0);
  24450. ao2_lock(p);
  24451. sip_unref_peer(peer, "release a peer ref now that MWI is sent");
  24452. }
  24453. } else if (p->subscribed != CALL_COMPLETION) {
  24454. struct state_notify_data data = { 0, };
  24455. char *subtype = NULL;
  24456. char *message = NULL;
  24457. struct ao2_container *device_state_info = NULL;
  24458. if (p->expiry > 0 && !resubscribe) {
  24459. /* Add subscription for extension state from the PBX core */
  24460. if (p->stateid != -1) {
  24461. ast_extension_state_del(p->stateid, cb_extensionstate);
  24462. }
  24463. dialog_ref(p, "copying dialog ptr into extension state struct");
  24464. p->stateid = ast_extension_state_add_destroy_extended(p->context, p->exten, cb_extensionstate, cb_extensionstate_destroy, p);
  24465. if (p->stateid == -1) {
  24466. dialog_unref(p, "copying dialog ptr into extension state struct failed");
  24467. }
  24468. }
  24469. sip_pvt_unlock(p);
  24470. data.state = ast_extension_state_extended(NULL, p->context, p->exten, &device_state_info);
  24471. sip_pvt_lock(p);
  24472. if (data.state < 0) {
  24473. ao2_cleanup(device_state_info);
  24474. if (p->expiry > 0) {
  24475. 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));
  24476. }
  24477. transmit_response(p, "404 Not found", req);
  24478. pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
  24479. if (authpeer) {
  24480. sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 6)");
  24481. }
  24482. return 0;
  24483. }
  24484. if (allow_notify_user_presence(p)) {
  24485. data.presence_state = ast_hint_presence_state(NULL, p->context, p->exten, &subtype, &message);
  24486. data.presence_subtype = subtype;
  24487. data.presence_message = message;
  24488. }
  24489. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  24490. transmit_response(p, "200 OK", req);
  24491. /* RFC 3265: A notification must be sent on every subscribe, so force it */
  24492. data.device_state_info = device_state_info;
  24493. if (data.state & AST_EXTENSION_RINGING) {
  24494. /* save last_ringing_channel_time if this state really contains a ringing channel
  24495. * because extensionstate_update() doesn't do it if forced
  24496. */
  24497. struct ast_channel *ringing = find_ringing_channel(data.device_state_info, p);
  24498. if (ringing) {
  24499. p->last_ringing_channel_time = ast_channel_creationtime(ringing);
  24500. ao2_ref(ringing, -1);
  24501. }
  24502. /* If there is no channel, this likely indicates that the ringing indication
  24503. * is due to a custom device state. These do not have associated channels.
  24504. */
  24505. }
  24506. extensionstate_update(p->context, p->exten, &data, p, TRUE);
  24507. append_history(p, "Subscribestatus", "%s", ast_extension_state2str(data.state));
  24508. /* hide the 'complete' exten/context in the refer_to field for later display */
  24509. ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
  24510. /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
  24511. ao2_cleanup(device_state_info);
  24512. ast_free(subtype);
  24513. ast_free(message);
  24514. }
  24515. if (!p->expiry) {
  24516. pvt_set_needdestroy(p, "forcing expiration");
  24517. }
  24518. }
  24519. if (authpeer) {
  24520. sip_unref_peer(authpeer, "unref pointer into (*authpeer)");
  24521. }
  24522. return 1;
  24523. }
  24524. /*! \brief Handle incoming REGISTER request */
  24525. static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
  24526. {
  24527. enum check_auth_result res;
  24528. /* If this is not the intial request, and the initial request isn't
  24529. * a register, something screwy happened, so bail */
  24530. if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
  24531. ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
  24532. return -1;
  24533. }
  24534. /* Use this as the basis */
  24535. copy_request(&p->initreq, req);
  24536. if (sipdebug)
  24537. ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  24538. check_via(p, req);
  24539. if ((res = register_verify(p, addr, req, e)) < 0) {
  24540. const char *reason;
  24541. switch (res) {
  24542. case AUTH_SECRET_FAILED:
  24543. reason = "Wrong password";
  24544. break;
  24545. case AUTH_USERNAME_MISMATCH:
  24546. reason = "Username/auth name mismatch";
  24547. break;
  24548. case AUTH_NOT_FOUND:
  24549. reason = "No matching peer found";
  24550. break;
  24551. case AUTH_UNKNOWN_DOMAIN:
  24552. reason = "Not a local domain";
  24553. break;
  24554. case AUTH_PEER_NOT_DYNAMIC:
  24555. reason = "Peer is not supposed to register";
  24556. break;
  24557. case AUTH_ACL_FAILED:
  24558. reason = "Device does not match ACL";
  24559. break;
  24560. case AUTH_BAD_TRANSPORT:
  24561. reason = "Device not configured to use this transport type";
  24562. break;
  24563. case AUTH_RTP_FAILED:
  24564. reason = "RTP initialization failed";
  24565. break;
  24566. default:
  24567. reason = "Unknown failure";
  24568. break;
  24569. }
  24570. ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
  24571. sip_get_header(req, "To"), ast_sockaddr_stringify(addr),
  24572. reason);
  24573. append_history(p, "RegRequest", "Failed : Account %s : %s", sip_get_header(req, "To"), reason);
  24574. } else {
  24575. req->authenticated = 1;
  24576. append_history(p, "RegRequest", "Succeeded : Account %s", sip_get_header(req, "To"));
  24577. }
  24578. if (res != AUTH_CHALLENGE_SENT) {
  24579. /* Destroy the session, but keep us around for just a bit in case they don't
  24580. get our 200 OK */
  24581. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  24582. }
  24583. return res;
  24584. }
  24585. /*!
  24586. * \brief Handle incoming SIP requests (methods)
  24587. * \note
  24588. * This is where all incoming requests go first.
  24589. * \note
  24590. * called with p and p->owner locked
  24591. */
  24592. static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
  24593. {
  24594. /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
  24595. relatively static */
  24596. const char *cmd;
  24597. const char *cseq;
  24598. const char *useragent;
  24599. const char *via;
  24600. const char *callid;
  24601. int via_pos = 0;
  24602. uint32_t seqno;
  24603. int len;
  24604. int respid;
  24605. int res = 0;
  24606. const char *e;
  24607. int error = 0;
  24608. int oldmethod = p->method;
  24609. int acked = 0;
  24610. /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
  24611. * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
  24612. * so we can check to make sure these fields exist for all requests and responses */
  24613. cseq = sip_get_header(req, "Cseq");
  24614. cmd = REQ_OFFSET_TO_STR(req, header[0]);
  24615. /* Save the via_pos so we can check later that responses only have 1 Via header */
  24616. via = __get_header(req, "Via", &via_pos);
  24617. /* This must exist already because we've called find_call by now */
  24618. callid = sip_get_header(req, "Call-ID");
  24619. /* Must have Cseq */
  24620. if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
  24621. ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
  24622. error = 1;
  24623. }
  24624. if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
  24625. ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
  24626. error = 1;
  24627. }
  24628. if (error) {
  24629. if (!p->initreq.headers) { /* New call */
  24630. pvt_set_needdestroy(p, "no headers");
  24631. }
  24632. return -1;
  24633. }
  24634. /* Get the command XXX */
  24635. cmd = REQ_OFFSET_TO_STR(req, rlpart1);
  24636. e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
  24637. /* Save useragent of the client */
  24638. useragent = sip_get_header(req, "User-Agent");
  24639. if (!ast_strlen_zero(useragent))
  24640. ast_string_field_set(p, useragent, useragent);
  24641. /* Find out SIP method for incoming request */
  24642. if (req->method == SIP_RESPONSE) { /* Response to our request */
  24643. /* ignore means "don't do anything with it" but still have to
  24644. * respond appropriately.
  24645. * But in this case this is a response already, so we really
  24646. * have nothing to do with this message, and even setting the
  24647. * ignore flag is pointless.
  24648. */
  24649. if (ast_strlen_zero(e)) {
  24650. return 0;
  24651. }
  24652. if (sscanf(e, "%30d %n", &respid, &len) != 1) {
  24653. ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
  24654. return 0;
  24655. }
  24656. if (respid <= 0) {
  24657. ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
  24658. return 0;
  24659. }
  24660. /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
  24661. * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
  24662. * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
  24663. if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
  24664. ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
  24665. return 0;
  24666. }
  24667. if (p->ocseq && (p->ocseq < seqno)) {
  24668. ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
  24669. return -1;
  24670. } else {
  24671. if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
  24672. extract_uri(p, req);
  24673. }
  24674. if (p->owner) {
  24675. struct ast_control_pvt_cause_code *cause_code;
  24676. int data_size = sizeof(*cause_code);
  24677. /* size of the string making up the cause code is "SIP " + cause length */
  24678. data_size += 4 + strlen(REQ_OFFSET_TO_STR(req, rlpart2));
  24679. cause_code = ast_alloca(data_size);
  24680. memset(cause_code, 0, data_size);
  24681. ast_copy_string(cause_code->chan_name, ast_channel_name(p->owner), AST_CHANNEL_NAME);
  24682. snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %s", REQ_OFFSET_TO_STR(req, rlpart2));
  24683. cause_code->ast_cause = hangup_sip2cause(respid);
  24684. if (global_store_sip_cause) {
  24685. cause_code->emulate_sip_cause = 1;
  24686. }
  24687. ast_queue_control_data(p->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
  24688. ast_channel_hangupcause_hash_set(p->owner, cause_code, data_size);
  24689. }
  24690. handle_response(p, respid, e + len, req, seqno);
  24691. }
  24692. return 0;
  24693. }
  24694. /* New SIP request coming in
  24695. (could be new request in existing SIP dialog as well...)
  24696. */
  24697. p->method = req->method; /* Find out which SIP method they are using */
  24698. ast_debug(4, "**** Received %s (%u) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
  24699. if (p->icseq && (p->icseq > seqno) ) {
  24700. if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
  24701. ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
  24702. } else {
  24703. ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
  24704. if (req->method == SIP_INVITE) {
  24705. unsigned int ran = (ast_random() % 10) + 1;
  24706. char seconds[4];
  24707. snprintf(seconds, sizeof(seconds), "%u", ran);
  24708. 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 */
  24709. } else if (req->method != SIP_ACK) {
  24710. transmit_response(p, "500 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
  24711. }
  24712. return -1;
  24713. }
  24714. } else if (p->icseq &&
  24715. p->icseq == seqno &&
  24716. req->method != SIP_ACK &&
  24717. (p->method != SIP_CANCEL || p->alreadygone)) {
  24718. /* ignore means "don't do anything with it" but still have to
  24719. respond appropriately. We do this if we receive a repeat of
  24720. the last sequence number */
  24721. req->ignore = 1;
  24722. ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
  24723. }
  24724. /* RFC 3261 section 9. "CANCEL has no effect on a request to which a UAS has
  24725. * already given a final response." */
  24726. if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
  24727. transmit_response(p, "481 Call/Transaction Does Not Exist", req);
  24728. return res;
  24729. }
  24730. if (seqno >= p->icseq)
  24731. /* Next should follow monotonically (but not necessarily
  24732. incrementally -- thanks again to the genius authors of SIP --
  24733. increasing */
  24734. p->icseq = seqno;
  24735. /* Find their tag if we haven't got it */
  24736. if (ast_strlen_zero(p->theirtag)) {
  24737. char tag[128];
  24738. gettag(req, "From", tag, sizeof(tag));
  24739. ast_string_field_set(p, theirtag, tag);
  24740. }
  24741. snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
  24742. if (sip_cfg.pedanticsipchecking) {
  24743. /* If this is a request packet without a from tag, it's not
  24744. correct according to RFC 3261 */
  24745. /* Check if this a new request in a new dialog with a totag already attached to it,
  24746. RFC 3261 - section 12.2 - and we don't want to mess with recovery */
  24747. if (!p->initreq.headers && req->has_to_tag) {
  24748. /* If this is a first request and it got a to-tag, it is not for us */
  24749. if (!req->ignore && req->method == SIP_INVITE) {
  24750. /* Just because we think this is a dialog-starting INVITE with a to-tag
  24751. * doesn't mean it actually is. It could be a reinvite for an established, but
  24752. * unknown dialog. In such a case, we need to change our tag to the
  24753. * incoming INVITE's to-tag so that they will recognize the 481 we send and
  24754. * so that we will properly match their incoming ACK.
  24755. */
  24756. char totag[128];
  24757. gettag(req, "To", totag, sizeof(totag));
  24758. ast_string_field_set(p, tag, totag);
  24759. p->pendinginvite = p->icseq;
  24760. transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
  24761. /* Will cease to exist after ACK */
  24762. return res;
  24763. } else if (req->method != SIP_ACK) {
  24764. transmit_response(p, "481 Call/Transaction Does Not Exist", req);
  24765. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  24766. return res;
  24767. }
  24768. /* Otherwise, this is an ACK. It will always have a to-tag */
  24769. }
  24770. }
  24771. if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
  24772. transmit_response(p, "400 Bad request", req);
  24773. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  24774. return -1;
  24775. }
  24776. /* Handle various incoming SIP methods in requests */
  24777. switch (p->method) {
  24778. case SIP_OPTIONS:
  24779. res = handle_request_options(p, req, addr, e);
  24780. break;
  24781. case SIP_INVITE:
  24782. res = handle_request_invite(p, req, addr, seqno, recount, e, nounlock);
  24783. if (res < 9) {
  24784. sip_report_security_event(p, req, res);
  24785. }
  24786. switch (res) {
  24787. case INV_REQ_SUCCESS:
  24788. res = 1;
  24789. break;
  24790. case INV_REQ_FAILED:
  24791. res = 0;
  24792. break;
  24793. case INV_REQ_ERROR:
  24794. res = -1;
  24795. break;
  24796. default:
  24797. res = 0;
  24798. break;
  24799. }
  24800. break;
  24801. case SIP_REFER:
  24802. res = handle_request_refer(p, req, seqno, nounlock);
  24803. break;
  24804. case SIP_CANCEL:
  24805. res = handle_request_cancel(p, req);
  24806. break;
  24807. case SIP_BYE:
  24808. res = handle_request_bye(p, req);
  24809. break;
  24810. case SIP_MESSAGE:
  24811. res = handle_request_message(p, req, addr, e);
  24812. break;
  24813. case SIP_PUBLISH:
  24814. res = handle_request_publish(p, req, addr, seqno, e);
  24815. break;
  24816. case SIP_SUBSCRIBE:
  24817. res = handle_request_subscribe(p, req, addr, seqno, e);
  24818. break;
  24819. case SIP_REGISTER:
  24820. res = handle_request_register(p, req, addr, e);
  24821. sip_report_security_event(p, req, res);
  24822. break;
  24823. case SIP_INFO:
  24824. if (req->debug)
  24825. ast_verbose("Receiving INFO!\n");
  24826. if (!req->ignore)
  24827. handle_request_info(p, req);
  24828. else /* if ignoring, transmit response */
  24829. transmit_response(p, "200 OK", req);
  24830. break;
  24831. case SIP_NOTIFY:
  24832. res = handle_request_notify(p, req, addr, seqno, e);
  24833. break;
  24834. case SIP_UPDATE:
  24835. res = handle_request_update(p, req);
  24836. break;
  24837. case SIP_ACK:
  24838. /* Make sure we don't ignore this */
  24839. if (seqno == p->pendinginvite) {
  24840. p->invitestate = INV_TERMINATED;
  24841. p->pendinginvite = 0;
  24842. acked = __sip_ack(p, seqno, 1 /* response */, 0);
  24843. if (p->owner && find_sdp(req)) {
  24844. if (process_sdp(p, req, SDP_T38_NONE)) {
  24845. return -1;
  24846. }
  24847. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  24848. ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
  24849. }
  24850. }
  24851. check_pendings(p);
  24852. } else if (p->glareinvite == seqno) {
  24853. /* handle ack for the 491 pending sent for glareinvite */
  24854. p->glareinvite = 0;
  24855. acked = __sip_ack(p, seqno, 1, 0);
  24856. }
  24857. if (!acked) {
  24858. /* Got an ACK that did not match anything. Ignore
  24859. * silently and restore previous method */
  24860. p->method = oldmethod;
  24861. }
  24862. if (!p->lastinvite && ast_strlen_zero(p->nonce)) {
  24863. pvt_set_needdestroy(p, "unmatched ACK");
  24864. }
  24865. break;
  24866. default:
  24867. transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
  24868. ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
  24869. cmd, ast_sockaddr_stringify(&p->sa));
  24870. /* If this is some new method, and we don't have a call, destroy it now */
  24871. if (!p->initreq.headers) {
  24872. pvt_set_needdestroy(p, "unimplemented method");
  24873. }
  24874. break;
  24875. }
  24876. return res;
  24877. }
  24878. /*! \brief Read data from SIP UDP socket
  24879. \note sipsock_read locks the owner channel while we are processing the SIP message
  24880. \return 1 on error, 0 on success
  24881. \note Successful messages is connected to SIP call and forwarded to handle_incoming()
  24882. */
  24883. static int sipsock_read(int *id, int fd, short events, void *ignore)
  24884. {
  24885. struct sip_request req;
  24886. struct ast_sockaddr addr;
  24887. int res;
  24888. static char readbuf[65535];
  24889. memset(&req, 0, sizeof(req));
  24890. res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
  24891. if (res < 0) {
  24892. #if !defined(__FreeBSD__)
  24893. if (errno == EAGAIN)
  24894. ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
  24895. else
  24896. #endif
  24897. if (errno != ECONNREFUSED)
  24898. ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
  24899. return 1;
  24900. }
  24901. readbuf[res] = '\0';
  24902. if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
  24903. return 1;
  24904. }
  24905. if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
  24906. return -1;
  24907. }
  24908. req.socket.fd = sipsock;
  24909. set_socket_transport(&req.socket, AST_TRANSPORT_UDP);
  24910. req.socket.tcptls_session = NULL;
  24911. req.socket.port = htons(ast_sockaddr_port(&bindaddr));
  24912. handle_request_do(&req, &addr);
  24913. deinit_req(&req);
  24914. return 1;
  24915. }
  24916. /*! \brief Handle incoming SIP message - request or response
  24917. This is used for all transports (udp, tcp and tcp/tls)
  24918. */
  24919. static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
  24920. {
  24921. struct sip_pvt *p;
  24922. struct ast_channel *owner_chan_ref = NULL;
  24923. int recount = 0;
  24924. int nounlock = 0;
  24925. if (sip_debug_test_addr(addr)) /* Set the debug flag early on packet level */
  24926. req->debug = 1;
  24927. if (sip_cfg.pedanticsipchecking)
  24928. lws2sws(req->data); /* Fix multiline headers */
  24929. if (req->debug) {
  24930. ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
  24931. sip_get_transport(req->socket.type), ast_sockaddr_stringify(addr), ast_str_buffer(req->data));
  24932. }
  24933. if (parse_request(req) == -1) { /* Bad packet, can't parse */
  24934. ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
  24935. return 1;
  24936. }
  24937. req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlpart1));
  24938. if (req->debug)
  24939. ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
  24940. if (req->headers < 2) { /* Must have at least two headers */
  24941. ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
  24942. return 1;
  24943. }
  24944. ast_mutex_lock(&netlock);
  24945. /* Find the active SIP dialog or create a new one */
  24946. p = find_call(req, addr, req->method); /* returns p with a reference only. _NOT_ locked*/
  24947. if (p == NULL) {
  24948. ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
  24949. ast_mutex_unlock(&netlock);
  24950. return 1;
  24951. }
  24952. if (p->logger_callid) {
  24953. ast_callid_threadassoc_add(p->logger_callid);
  24954. }
  24955. /* Lock both the pvt and the owner if owner is present. This will
  24956. * not fail. */
  24957. owner_chan_ref = sip_pvt_lock_full(p);
  24958. copy_socket_data(&p->socket, &req->socket);
  24959. ast_sockaddr_copy(&p->recv, addr);
  24960. /* if we have an owner, then this request has been authenticated */
  24961. if (p->owner) {
  24962. req->authenticated = 1;
  24963. }
  24964. if (p->do_history) /* This is a request or response, note what it was for */
  24965. append_history(p, "Rx", "%s / %s / %s", ast_str_buffer(req->data), sip_get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlpart2));
  24966. if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
  24967. /* Request failed */
  24968. ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
  24969. }
  24970. if (recount) {
  24971. ast_update_use_count();
  24972. }
  24973. if (p->owner && !nounlock) {
  24974. ast_channel_unlock(p->owner);
  24975. }
  24976. if (owner_chan_ref) {
  24977. ast_channel_unref(owner_chan_ref);
  24978. }
  24979. sip_pvt_unlock(p);
  24980. ast_mutex_unlock(&netlock);
  24981. if (p->logger_callid) {
  24982. ast_callid_threadassoc_remove();
  24983. }
  24984. ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
  24985. return 1;
  24986. }
  24987. /*! \brief Returns the port to use for this socket
  24988. *
  24989. * \param type The type of transport used
  24990. * \param port Port we are checking to see if it's the standard port.
  24991. * \note port is expected in host byte order
  24992. */
  24993. static int sip_standard_port(enum ast_transport type, int port)
  24994. {
  24995. if (type & AST_TRANSPORT_TLS)
  24996. return port == STANDARD_TLS_PORT;
  24997. else
  24998. return port == STANDARD_SIP_PORT;
  24999. }
  25000. static int threadinfo_locate_cb(void *obj, void *arg, int flags)
  25001. {
  25002. struct sip_threadinfo *th = obj;
  25003. struct ast_sockaddr *s = arg;
  25004. if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
  25005. return CMP_MATCH | CMP_STOP;
  25006. }
  25007. return 0;
  25008. }
  25009. /*!
  25010. * \brief Find thread for TCP/TLS session (based on IP/Port
  25011. *
  25012. * \note This function returns an astobj2 reference
  25013. */
  25014. static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
  25015. {
  25016. struct sip_threadinfo *th;
  25017. struct ast_tcptls_session_instance *tcptls_instance = NULL;
  25018. if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
  25019. tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
  25020. ao2_t_ref(th, -1, "decrement ref from callback");
  25021. }
  25022. return tcptls_instance;
  25023. }
  25024. /*!
  25025. * \brief Helper for dns resolution to filter by address family.
  25026. *
  25027. * \note return 0 if addr is [::] else it returns addr's family.
  25028. */
  25029. int get_address_family_filter(unsigned int transport)
  25030. {
  25031. const struct ast_sockaddr *addr = NULL;
  25032. if ((transport == AST_TRANSPORT_UDP) || !transport) {
  25033. addr = &bindaddr;
  25034. } else if (transport == AST_TRANSPORT_TCP || transport == AST_TRANSPORT_WS) {
  25035. addr = &sip_tcp_desc.local_address;
  25036. } else if (transport == AST_TRANSPORT_TLS || transport == AST_TRANSPORT_WSS) {
  25037. addr = &sip_tls_desc.local_address;
  25038. }
  25039. if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
  25040. return 0;
  25041. }
  25042. return addr->ss.ss_family;
  25043. }
  25044. /*! \todo Get socket for dialog, prepare if needed, and return file handle */
  25045. static int sip_prepare_socket(struct sip_pvt *p)
  25046. {
  25047. struct sip_socket *s = &p->socket;
  25048. static const char name[] = "SIP socket";
  25049. struct sip_threadinfo *th = NULL;
  25050. struct ast_tcptls_session_instance *tcptls_session;
  25051. struct ast_tcptls_session_args *ca;
  25052. struct ast_sockaddr sa_tmp;
  25053. pthread_t launched;
  25054. /* check to see if a socket is already active */
  25055. if ((s->fd != -1) && (s->type == AST_TRANSPORT_UDP)) {
  25056. return s->fd;
  25057. }
  25058. if ((s->type & (AST_TRANSPORT_TCP | AST_TRANSPORT_TLS)) &&
  25059. (s->tcptls_session) &&
  25060. (s->tcptls_session->fd != -1)) {
  25061. return s->tcptls_session->fd;
  25062. }
  25063. if ((s->type & (AST_TRANSPORT_WS | AST_TRANSPORT_WSS))) {
  25064. return s->ws_session ? ast_websocket_fd(s->ws_session) : -1;
  25065. }
  25066. /*! \todo Check this... This might be wrong, depending on the proxy configuration
  25067. If proxy is in "force" mode its correct.
  25068. */
  25069. if (p->outboundproxy && p->outboundproxy->transport) {
  25070. s->type = p->outboundproxy->transport;
  25071. }
  25072. if (s->type == AST_TRANSPORT_UDP) {
  25073. s->fd = sipsock;
  25074. return s->fd;
  25075. }
  25076. /* At this point we are dealing with a TCP/TLS connection
  25077. * 1. We need to check to see if a connection thread exists
  25078. * for this address, if so use that.
  25079. * 2. If a thread does not exist for this address, but the tcptls_session
  25080. * exists on the socket, the connection was closed.
  25081. * 3. If no tcptls_session thread exists for the address, and no tcptls_session
  25082. * already exists on the socket, create a new one and launch a new thread.
  25083. */
  25084. /* 1. check for existing threads */
  25085. ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
  25086. if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
  25087. s->fd = tcptls_session->fd;
  25088. if (s->tcptls_session) {
  25089. ao2_ref(s->tcptls_session, -1);
  25090. s->tcptls_session = NULL;
  25091. }
  25092. s->tcptls_session = tcptls_session;
  25093. return s->fd;
  25094. /* 2. Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
  25095. } else if (s->tcptls_session) {
  25096. return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
  25097. }
  25098. /* 3. Create a new TCP/TLS client connection */
  25099. /* create new session arguments for the client connection */
  25100. if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
  25101. !(ca->name = ast_strdup(name))) {
  25102. goto create_tcptls_session_fail;
  25103. }
  25104. ca->accept_fd = -1;
  25105. ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
  25106. /* if type is TLS, we need to create a tls cfg for this session arg */
  25107. if (s->type == AST_TRANSPORT_TLS) {
  25108. if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
  25109. goto create_tcptls_session_fail;
  25110. }
  25111. memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
  25112. if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
  25113. !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
  25114. !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
  25115. !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
  25116. !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
  25117. goto create_tcptls_session_fail;
  25118. }
  25119. /* this host is used as the common name in ssl/tls */
  25120. if (!ast_strlen_zero(p->tohost)) {
  25121. ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
  25122. }
  25123. }
  25124. /* Create a client connection for address, this does not start the connection, just sets it up. */
  25125. if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
  25126. goto create_tcptls_session_fail;
  25127. }
  25128. s->fd = s->tcptls_session->fd;
  25129. /* client connections need to have the sip_threadinfo object created before
  25130. * the thread is detached. This ensures the alert_pipe is up before it will
  25131. * be used. Note that this function links the new threadinfo object into the
  25132. * threadt container. */
  25133. if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
  25134. goto create_tcptls_session_fail;
  25135. }
  25136. /* Give the new thread a reference to the tcptls_session */
  25137. ao2_ref(s->tcptls_session, +1);
  25138. if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
  25139. ast_debug(1, "Unable to launch '%s'.", ca->name);
  25140. ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
  25141. goto create_tcptls_session_fail;
  25142. }
  25143. return s->fd;
  25144. create_tcptls_session_fail:
  25145. if (ca) {
  25146. ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
  25147. }
  25148. if (s->tcptls_session) {
  25149. ast_tcptls_close_session_file(s->tcptls_session);
  25150. s->fd = -1;
  25151. ao2_ref(s->tcptls_session, -1);
  25152. s->tcptls_session = NULL;
  25153. }
  25154. if (th) {
  25155. ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
  25156. }
  25157. return -1;
  25158. }
  25159. /*!
  25160. * \brief Get cached MWI info
  25161. * \return TRUE if found MWI in cache
  25162. */
  25163. static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
  25164. {
  25165. struct sip_mailbox *mailbox;
  25166. int in_cache;
  25167. in_cache = 0;
  25168. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  25169. RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
  25170. struct ast_mwi_state *mwi_state;
  25171. msg = stasis_cache_get(ast_mwi_state_cache(), ast_mwi_state_type(), mailbox->id);
  25172. if (!msg) {
  25173. continue;
  25174. }
  25175. mwi_state = stasis_message_data(msg);
  25176. *new += mwi_state->new_msgs;
  25177. *old += mwi_state->old_msgs;
  25178. in_cache = 1;
  25179. }
  25180. return in_cache;
  25181. }
  25182. /*! \brief Send message waiting indication to alert peer that they've got voicemail
  25183. * \note Both peer and associated sip_pvt must be unlocked prior to calling this function
  25184. * \returns -1 on failure, 0 on success
  25185. */
  25186. static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
  25187. {
  25188. /* Called with peer lock, but releases it */
  25189. struct sip_pvt *p;
  25190. int newmsgs = 0, oldmsgs = 0;
  25191. const char *vmexten = NULL;
  25192. ao2_lock(peer);
  25193. if (peer->vmexten) {
  25194. vmexten = ast_strdupa(peer->vmexten);
  25195. }
  25196. if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
  25197. update_peer_lastmsgssent(peer, -1, 1);
  25198. ao2_unlock(peer);
  25199. return -1;
  25200. }
  25201. /* Do we have an IP address? If not, skip this peer */
  25202. if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
  25203. update_peer_lastmsgssent(peer, -1, 1);
  25204. ao2_unlock(peer);
  25205. return -1;
  25206. }
  25207. /* Attempt to use cached mwi to get message counts. */
  25208. if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
  25209. /* Fall back to manually checking the mailbox if not cache_only and get_cached_mwi failed */
  25210. struct ast_str *mailbox_str = ast_str_alloca(512);
  25211. peer_mailboxes_to_str(&mailbox_str, peer);
  25212. /* if there is no mailbox do nothing */
  25213. if (!ast_str_strlen(mailbox_str)) {
  25214. ao2_unlock(peer);
  25215. return -1;
  25216. }
  25217. ao2_unlock(peer);
  25218. /* If there is no mailbox do nothing */
  25219. if (!ast_str_strlen(mailbox_str)) {
  25220. update_peer_lastmsgssent(peer, -1, 0);
  25221. return 0;
  25222. }
  25223. ast_app_inboxcount(ast_str_buffer(mailbox_str), &newmsgs, &oldmsgs);
  25224. ao2_lock(peer);
  25225. }
  25226. if (peer->mwipvt) {
  25227. /* Base message on subscription */
  25228. p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
  25229. ao2_unlock(peer);
  25230. } else {
  25231. ao2_unlock(peer);
  25232. /* Build temporary dialog for this message */
  25233. if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
  25234. update_peer_lastmsgssent(peer, -1, 0);
  25235. return -1;
  25236. }
  25237. /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
  25238. * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy
  25239. * the peer's socket information to the sip_pvt we just allocated
  25240. */
  25241. set_socket_transport(&p->socket, 0);
  25242. if (create_addr_from_peer(p, peer)) {
  25243. /* Maybe they're not registered, etc. */
  25244. dialog_unlink_all(p);
  25245. dialog_unref(p, "unref dialog p just created via sip_alloc");
  25246. update_peer_lastmsgssent(peer, -1, 0);
  25247. return -1;
  25248. }
  25249. /* Recalculate our side, and recalculate Call ID */
  25250. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  25251. build_via(p);
  25252. ao2_lock(peer);
  25253. if (!ast_strlen_zero(peer->mwi_from)) {
  25254. ast_string_field_set(p, mwi_from, peer->mwi_from);
  25255. } else if (!ast_strlen_zero(default_mwi_from)) {
  25256. ast_string_field_set(p, mwi_from, default_mwi_from);
  25257. }
  25258. ao2_unlock(peer);
  25259. /* Change the dialog callid. */
  25260. change_callid_pvt(p, NULL);
  25261. /* Destroy this session after 32 secs */
  25262. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  25263. }
  25264. /* 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,
  25265. we really need to have a lock on it */
  25266. sip_pvt_lock(p);
  25267. /* Send MWI */
  25268. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  25269. /* the following will decrement the refcount on p as it finishes */
  25270. transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
  25271. sip_pvt_unlock(p);
  25272. dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
  25273. update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
  25274. return 0;
  25275. }
  25276. static struct ast_manager_event_blob *session_timeout_to_ami(struct stasis_message *msg)
  25277. {
  25278. RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
  25279. struct ast_channel_blob *obj = stasis_message_data(msg);
  25280. const char *source = ast_json_string_get(ast_json_object_get(obj->blob, "source"));
  25281. channel_string = ast_manager_build_channel_state_string(obj->snapshot);
  25282. if (!channel_string) {
  25283. return NULL;
  25284. }
  25285. return ast_manager_event_blob_create(EVENT_FLAG_CALL, "SessionTimeout",
  25286. "%s"
  25287. "Source: %s\r\n",
  25288. ast_str_buffer(channel_string), source);
  25289. }
  25290. /*! \brief Sends a session timeout channel blob used to produce SessionTimeout AMI messages */
  25291. static void send_session_timeout(struct ast_channel *chan, const char *source)
  25292. {
  25293. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  25294. ast_assert(chan != NULL);
  25295. ast_assert(source != NULL);
  25296. blob = ast_json_pack("{s: s}", "source", source);
  25297. if (!blob) {
  25298. return;
  25299. }
  25300. ast_channel_publish_blob(chan, session_timeout_type(), blob);
  25301. }
  25302. /*!
  25303. * \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked
  25304. *
  25305. * \return CMP_MATCH for items to be unlinked from dialogs_rtpcheck.
  25306. */
  25307. static int check_rtp_timeout(struct sip_pvt *dialog, time_t t)
  25308. {
  25309. int timeout;
  25310. int hold_timeout;
  25311. int keepalive;
  25312. if (!dialog->rtp) {
  25313. /*
  25314. * We have no RTP. Since we don't do much with video RTP for
  25315. * now, stop checking this dialog.
  25316. */
  25317. return CMP_MATCH;
  25318. }
  25319. /* If we have no active owner, no need to check timers */
  25320. if (!dialog->owner) {
  25321. return CMP_MATCH;
  25322. }
  25323. /* If the call is redirected outside Asterisk, no need to check timers */
  25324. if (!ast_sockaddr_isnull(&dialog->redirip)) {
  25325. return CMP_MATCH;
  25326. }
  25327. /* If the call is involved in a T38 fax session do not check RTP timeout */
  25328. if (dialog->t38.state == T38_ENABLED) {
  25329. return CMP_MATCH;
  25330. }
  25331. /* If the call is not in UP state return for later check. */
  25332. if (ast_channel_state(dialog->owner) != AST_STATE_UP) {
  25333. return 0;
  25334. }
  25335. /* Store these values locally to avoid multiple function calls */
  25336. timeout = ast_rtp_instance_get_timeout(dialog->rtp);
  25337. hold_timeout = ast_rtp_instance_get_hold_timeout(dialog->rtp);
  25338. keepalive = ast_rtp_instance_get_keepalive(dialog->rtp);
  25339. /* If we have no timers set, return now */
  25340. if (!keepalive && !timeout && !hold_timeout) {
  25341. return CMP_MATCH;
  25342. }
  25343. /* Check AUDIO RTP keepalives */
  25344. if (dialog->lastrtptx && keepalive && (t > dialog->lastrtptx + keepalive)) {
  25345. /* Need to send an empty RTP packet */
  25346. dialog->lastrtptx = time(NULL);
  25347. ast_rtp_instance_sendcng(dialog->rtp, 0);
  25348. }
  25349. /*! \todo Check video RTP keepalives
  25350. Do we need to move the lastrtptx to the RTP structure to have one for audio and one
  25351. for video? It really does belong to the RTP structure.
  25352. */
  25353. /* Check AUDIO RTP timers */
  25354. if (dialog->lastrtprx && (timeout || hold_timeout) && (t > dialog->lastrtprx + timeout)) {
  25355. if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (hold_timeout && (t > dialog->lastrtprx + hold_timeout))) {
  25356. /* Needs a hangup */
  25357. if (timeout) {
  25358. if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
  25359. /*
  25360. * Don't block, just try again later.
  25361. * If there was no owner, the call is dead already.
  25362. */
  25363. return 0;
  25364. }
  25365. ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
  25366. ast_channel_name(dialog->owner), (long) (t - dialog->lastrtprx));
  25367. send_session_timeout(dialog->owner, "RTPTimeout");
  25368. /* Issue a softhangup */
  25369. ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
  25370. ast_channel_unlock(dialog->owner);
  25371. /* forget the timeouts for this call, since a hangup
  25372. has already been requested and we don't want to
  25373. repeatedly request hangups
  25374. */
  25375. ast_rtp_instance_set_timeout(dialog->rtp, 0);
  25376. ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
  25377. if (dialog->vrtp) {
  25378. ast_rtp_instance_set_timeout(dialog->vrtp, 0);
  25379. ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
  25380. }
  25381. /* finally unlink the dialog from dialogs_rtpcheck. */
  25382. return CMP_MATCH;
  25383. }
  25384. }
  25385. }
  25386. return 0;
  25387. }
  25388. /*! \brief The SIP monitoring thread
  25389. \note This thread monitors all the SIP sessions and peers that needs notification of mwi
  25390. (and thus do not have a separate thread) indefinitely
  25391. */
  25392. static void *do_monitor(void *data)
  25393. {
  25394. int res;
  25395. time_t t;
  25396. int reloading;
  25397. /* Add an I/O event to our SIP UDP socket */
  25398. if (sipsock > -1) {
  25399. sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
  25400. }
  25401. /* From here on out, we die whenever asked */
  25402. for(;;) {
  25403. /* Check for a reload request */
  25404. ast_mutex_lock(&sip_reload_lock);
  25405. reloading = sip_reloading;
  25406. sip_reloading = FALSE;
  25407. ast_mutex_unlock(&sip_reload_lock);
  25408. if (reloading) {
  25409. ast_verb(1, "Reloading SIP\n");
  25410. sip_do_reload(sip_reloadreason);
  25411. /* Change the I/O fd of our UDP socket */
  25412. if (sipsock > -1) {
  25413. if (sipsock_read_id) {
  25414. sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
  25415. } else {
  25416. sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
  25417. }
  25418. } else if (sipsock_read_id) {
  25419. ast_io_remove(io, sipsock_read_id);
  25420. sipsock_read_id = NULL;
  25421. }
  25422. }
  25423. /* Check for dialogs needing to be killed */
  25424. t = time(NULL);
  25425. /*
  25426. * Check dialogs with rtp and rtptimeout.
  25427. * All dialogs which have rtp are in dialogs_rtpcheck.
  25428. */
  25429. ao2_t_callback(dialogs_rtpcheck, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
  25430. dialog_checkrtp_cb, &t,
  25431. "callback to check rtptimeout and hangup calls if necessary");
  25432. /*
  25433. * Check dialogs marked to be destroyed.
  25434. * All dialogs with needdestroy set are in dialogs_needdestroy.
  25435. */
  25436. ao2_t_callback(dialogs_needdestroy, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy,
  25437. NULL, "callback to check dialogs which need to be destroyed");
  25438. /* XXX TODO The scheduler usage in this module does not have sufficient
  25439. * synchronization being done between running the scheduler and places
  25440. * scheduling tasks. As it is written, any scheduled item may not run
  25441. * any sooner than about 1 second, regardless of whether a sooner time
  25442. * was asked for. */
  25443. pthread_testcancel();
  25444. /* Wait for sched or io */
  25445. res = ast_sched_wait(sched);
  25446. if ((res < 0) || (res > 1000)) {
  25447. res = 1000;
  25448. }
  25449. res = ast_io_wait(io, res);
  25450. if (res > 20) {
  25451. ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
  25452. }
  25453. ast_mutex_lock(&monlock);
  25454. res = ast_sched_runq(sched);
  25455. if (res >= 20) {
  25456. ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
  25457. }
  25458. ast_mutex_unlock(&monlock);
  25459. }
  25460. /* Never reached */
  25461. return NULL;
  25462. }
  25463. /*! \brief Start the channel monitor thread */
  25464. static int restart_monitor(void)
  25465. {
  25466. /* If we're supposed to be stopped -- stay stopped */
  25467. if (monitor_thread == AST_PTHREADT_STOP)
  25468. return 0;
  25469. ast_mutex_lock(&monlock);
  25470. if (monitor_thread == pthread_self()) {
  25471. ast_mutex_unlock(&monlock);
  25472. ast_log(LOG_WARNING, "Cannot kill myself\n");
  25473. return -1;
  25474. }
  25475. if (monitor_thread != AST_PTHREADT_NULL) {
  25476. /* Wake up the thread */
  25477. pthread_kill(monitor_thread, SIGURG);
  25478. } else {
  25479. /* Start a new monitor */
  25480. if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
  25481. ast_mutex_unlock(&monlock);
  25482. ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
  25483. return -1;
  25484. }
  25485. }
  25486. ast_mutex_unlock(&monlock);
  25487. return 0;
  25488. }
  25489. static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
  25490. struct stasis_message *message)
  25491. {
  25492. if (stasis_message_type(message) != ast_named_acl_change_type()) {
  25493. return;
  25494. }
  25495. ast_log(LOG_NOTICE, "Reloading chan_sip in response to ACL change event.\n");
  25496. ast_mutex_lock(&sip_reload_lock);
  25497. if (sip_reloading) {
  25498. ast_verbose("Previous SIP reload not yet done\n");
  25499. } else {
  25500. sip_reloading = TRUE;
  25501. sip_reloadreason = CHANNEL_ACL_RELOAD;
  25502. }
  25503. ast_mutex_unlock(&sip_reload_lock);
  25504. restart_monitor();
  25505. }
  25506. /*! \brief Session-Timers: Restart session timer */
  25507. static void restart_session_timer(struct sip_pvt *p)
  25508. {
  25509. if (p->stimer->st_active == TRUE) {
  25510. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  25511. AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
  25512. dialog_unref(p, "Removing session timer ref"));
  25513. start_session_timer(p);
  25514. }
  25515. }
  25516. /*! \brief Session-Timers: Stop session timer */
  25517. static void stop_session_timer(struct sip_pvt *p)
  25518. {
  25519. if (p->stimer->st_active == TRUE) {
  25520. p->stimer->st_active = FALSE;
  25521. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  25522. AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
  25523. dialog_unref(p, "removing session timer ref"));
  25524. }
  25525. }
  25526. /*! \brief Session-Timers: Start session timer */
  25527. static void start_session_timer(struct sip_pvt *p)
  25528. {
  25529. unsigned int timeout_ms;
  25530. if (p->stimer->st_schedid > -1) {
  25531. /* in the event a timer is already going, stop it */
  25532. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  25533. AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
  25534. dialog_unref(p, "unref stimer->st_schedid from dialog"));
  25535. }
  25536. /*
  25537. * RFC 4028 Section 10
  25538. * If the side not performing refreshes does not receive a
  25539. * session refresh request before the session expiration, it SHOULD send
  25540. * a BYE to terminate the session, slightly before the session
  25541. * expiration. The minimum of 32 seconds and one third of the session
  25542. * interval is RECOMMENDED.
  25543. */
  25544. timeout_ms = (1000 * p->stimer->st_interval);
  25545. if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
  25546. timeout_ms /= 2;
  25547. } else {
  25548. timeout_ms -= MIN(timeout_ms / 3, 32000);
  25549. }
  25550. p->stimer->st_schedid = ast_sched_add(sched, timeout_ms, proc_session_timer,
  25551. dialog_ref(p, "adding session timer ref"));
  25552. if (p->stimer->st_schedid < 0) {
  25553. dialog_unref(p, "removing session timer ref");
  25554. ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
  25555. } else {
  25556. p->stimer->st_active = TRUE;
  25557. ast_debug(2, "Session timer started: %d - %s %ums\n", p->stimer->st_schedid, p->callid, timeout_ms);
  25558. }
  25559. }
  25560. /*! \brief Session-Timers: Process session refresh timeout event */
  25561. static int proc_session_timer(const void *vp)
  25562. {
  25563. struct sip_pvt *p = (struct sip_pvt *) vp;
  25564. int res = 0;
  25565. if (!p->stimer) {
  25566. ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
  25567. goto return_unref;
  25568. }
  25569. ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
  25570. if (!p->owner) {
  25571. goto return_unref;
  25572. }
  25573. if ((p->stimer->st_active != TRUE) || (ast_channel_state(p->owner) != AST_STATE_UP)) {
  25574. goto return_unref;
  25575. }
  25576. if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
  25577. res = 1;
  25578. if (T38_ENABLED == p->t38.state) {
  25579. transmit_reinvite_with_sdp(p, TRUE, TRUE);
  25580. } else {
  25581. transmit_reinvite_with_sdp(p, FALSE, TRUE);
  25582. }
  25583. } else {
  25584. if (p->stimer->quit_flag) {
  25585. goto return_unref;
  25586. }
  25587. ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
  25588. sip_pvt_lock(p);
  25589. while (p->owner && ast_channel_trylock(p->owner)) {
  25590. sip_pvt_unlock(p);
  25591. usleep(1);
  25592. if (p->stimer && p->stimer->quit_flag) {
  25593. goto return_unref;
  25594. }
  25595. sip_pvt_lock(p);
  25596. }
  25597. send_session_timeout(p->owner, "SIPSessionTimer");
  25598. ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
  25599. ast_channel_unlock(p->owner);
  25600. sip_pvt_unlock(p);
  25601. }
  25602. return_unref:
  25603. if (!res) {
  25604. /* An error occurred. Stop session timer processing */
  25605. if (p->stimer) {
  25606. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  25607. /* Don't pass go, don't collect $200.. we are the scheduled
  25608. * callback. We can rip ourself out here. */
  25609. p->stimer->st_schedid = -1;
  25610. /* Calling stop_session_timer is nice for consistent debug
  25611. * logs. */
  25612. stop_session_timer(p);
  25613. }
  25614. /* If we are not asking to be rescheduled, then we need to release our
  25615. * reference to the dialog. */
  25616. dialog_unref(p, "removing session timer ref");
  25617. }
  25618. return res;
  25619. }
  25620. /*! \brief Session-Timers: Function for parsing Min-SE header */
  25621. int parse_minse (const char *p_hdrval, int *const p_interval)
  25622. {
  25623. if (ast_strlen_zero(p_hdrval)) {
  25624. ast_log(LOG_WARNING, "Null Min-SE header\n");
  25625. return -1;
  25626. }
  25627. *p_interval = 0;
  25628. p_hdrval = ast_skip_blanks(p_hdrval);
  25629. if (!sscanf(p_hdrval, "%30d", p_interval)) {
  25630. ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
  25631. return -1;
  25632. }
  25633. ast_debug(2, "Received Min-SE: %d\n", *p_interval);
  25634. return 0;
  25635. }
  25636. /*! \brief Session-Timers: Function for parsing Session-Expires header */
  25637. int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
  25638. {
  25639. char *p_token;
  25640. int ref_idx;
  25641. char *p_se_hdr;
  25642. if (ast_strlen_zero(p_hdrval)) {
  25643. ast_log(LOG_WARNING, "Null Session-Expires header\n");
  25644. return -1;
  25645. }
  25646. *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
  25647. *p_interval = 0;
  25648. p_se_hdr = ast_strdupa(p_hdrval);
  25649. p_se_hdr = ast_skip_blanks(p_se_hdr);
  25650. while ((p_token = strsep(&p_se_hdr, ";"))) {
  25651. p_token = ast_skip_blanks(p_token);
  25652. if (!sscanf(p_token, "%30d", p_interval)) {
  25653. ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
  25654. return -1;
  25655. }
  25656. ast_debug(2, "Session-Expires: %d\n", *p_interval);
  25657. if (!p_se_hdr)
  25658. continue;
  25659. p_se_hdr = ast_skip_blanks(p_se_hdr);
  25660. ref_idx = strlen("refresher=");
  25661. if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
  25662. p_se_hdr += ref_idx;
  25663. p_se_hdr = ast_skip_blanks(p_se_hdr);
  25664. if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
  25665. *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
  25666. ast_debug(2, "Refresher: UAC\n");
  25667. } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
  25668. *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
  25669. ast_debug(2, "Refresher: UAS\n");
  25670. } else {
  25671. ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
  25672. return -1;
  25673. }
  25674. break;
  25675. }
  25676. }
  25677. return 0;
  25678. }
  25679. /*! \brief Handle 422 response to INVITE with session-timer requested
  25680. Session-Timers: An INVITE originated by Asterisk that asks for session-timers support
  25681. from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
  25682. server tells Asterisk that the session refresh interval offered by Asterisk is too low
  25683. for them. The proc_422_rsp() function handles a 422 response. It extracts the Min-SE
  25684. header that comes back in 422 and sends a new INVITE accordingly. */
  25685. static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
  25686. {
  25687. int rtn;
  25688. const char *p_hdrval;
  25689. int minse;
  25690. p_hdrval = sip_get_header(rsp, "Min-SE");
  25691. if (ast_strlen_zero(p_hdrval)) {
  25692. ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
  25693. return;
  25694. }
  25695. rtn = parse_minse(p_hdrval, &minse);
  25696. if (rtn != 0) {
  25697. ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
  25698. return;
  25699. }
  25700. p->stimer->st_cached_min_se = minse;
  25701. if (p->stimer->st_interval < minse) {
  25702. p->stimer->st_interval = minse;
  25703. }
  25704. transmit_invite(p, SIP_INVITE, 1, 2, NULL);
  25705. }
  25706. /*! \brief Get Max or Min SE (session timer expiry)
  25707. * \param p pointer to the SIP dialog
  25708. * \param max if true, get max se, otherwise min se
  25709. */
  25710. int st_get_se(struct sip_pvt *p, int max)
  25711. {
  25712. if (max == TRUE) {
  25713. if (p->stimer->st_cached_max_se) {
  25714. return p->stimer->st_cached_max_se;
  25715. }
  25716. if (p->relatedpeer) {
  25717. p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
  25718. return (p->stimer->st_cached_max_se);
  25719. }
  25720. p->stimer->st_cached_max_se = global_max_se;
  25721. return (p->stimer->st_cached_max_se);
  25722. }
  25723. /* Find Min SE timer */
  25724. if (p->stimer->st_cached_min_se) {
  25725. return p->stimer->st_cached_min_se;
  25726. }
  25727. if (p->relatedpeer) {
  25728. p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
  25729. return (p->stimer->st_cached_min_se);
  25730. }
  25731. p->stimer->st_cached_min_se = global_min_se;
  25732. return (p->stimer->st_cached_min_se);
  25733. }
  25734. /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
  25735. * \note This is only called when processing an INVITE, so in that case Asterisk is
  25736. * always currently the UAS. If this is ever used to process responses, the
  25737. * function will have to be changed.
  25738. * \param p pointer to the SIP dialog
  25739. */
  25740. enum st_refresher st_get_refresher(struct sip_pvt *p)
  25741. {
  25742. if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
  25743. return p->stimer->st_cached_ref;
  25744. }
  25745. if (p->relatedpeer) {
  25746. p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
  25747. return p->stimer->st_cached_ref;
  25748. }
  25749. p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
  25750. return p->stimer->st_cached_ref;
  25751. }
  25752. /*!
  25753. * \brief Get the session-timer mode
  25754. * \param p pointer to the SIP dialog
  25755. * \param no_cached Set this to true in order to force a peername lookup on
  25756. * the session timer mode.
  25757. */
  25758. enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
  25759. {
  25760. if (!p->stimer) {
  25761. sip_st_alloc(p);
  25762. if (!p->stimer) {
  25763. return SESSION_TIMER_MODE_INVALID;
  25764. }
  25765. }
  25766. if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
  25767. return p->stimer->st_cached_mode;
  25768. if (p->relatedpeer) {
  25769. p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
  25770. return p->stimer->st_cached_mode;
  25771. }
  25772. p->stimer->st_cached_mode = global_st_mode;
  25773. return global_st_mode;
  25774. }
  25775. /*! \brief Send keep alive packet to peer */
  25776. static int sip_send_keepalive(const void *data)
  25777. {
  25778. struct sip_peer *peer = (struct sip_peer*) data;
  25779. int res = 0;
  25780. const char keepalive[] = "\r\n";
  25781. peer->keepalivesend = -1;
  25782. if (!peer->keepalive || ast_sockaddr_isnull(&peer->addr)) {
  25783. sip_unref_peer(peer, "release keepalive peer ref");
  25784. return 0;
  25785. }
  25786. /* Send the packet out using the proper method for this peer */
  25787. if ((peer->socket.fd != -1) && (peer->socket.type == AST_TRANSPORT_UDP)) {
  25788. res = ast_sendto(peer->socket.fd, keepalive, sizeof(keepalive), 0, &peer->addr);
  25789. } else if ((peer->socket.type & (AST_TRANSPORT_TCP | AST_TRANSPORT_TLS)) &&
  25790. (peer->socket.tcptls_session) &&
  25791. (peer->socket.tcptls_session->fd != -1)) {
  25792. res = sip_tcptls_write(peer->socket.tcptls_session, keepalive, sizeof(keepalive));
  25793. } else if (peer->socket.type == AST_TRANSPORT_UDP) {
  25794. res = ast_sendto(sipsock, keepalive, sizeof(keepalive), 0, &peer->addr);
  25795. }
  25796. if (res == -1) {
  25797. switch (errno) {
  25798. case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
  25799. case EHOSTUNREACH: /* Host can't be reached */
  25800. case ENETDOWN: /* Interface down */
  25801. case ENETUNREACH: /* Network failure */
  25802. case ECONNREFUSED: /* ICMP port unreachable */
  25803. res = XMIT_ERROR; /* Don't bother with trying to transmit again */
  25804. }
  25805. }
  25806. if (res != sizeof(keepalive)) {
  25807. ast_log(LOG_WARNING, "sip_send_keepalive to %s returned %d: %s\n", ast_sockaddr_stringify(&peer->addr), res, strerror(errno));
  25808. }
  25809. AST_SCHED_REPLACE_UNREF(peer->keepalivesend, sched,
  25810. peer->keepalive * 1000, sip_send_keepalive, peer,
  25811. sip_unref_peer(_data, "removing keepalive peer ref"),
  25812. sip_unref_peer(peer, "removing keepalive peer ref"),
  25813. sip_ref_peer(peer, "adding keepalive peer ref"));
  25814. sip_unref_peer(peer, "release keepalive peer ref");
  25815. return 0;
  25816. }
  25817. /*! \brief React to lack of answer to Qualify poke */
  25818. static int sip_poke_noanswer(const void *data)
  25819. {
  25820. struct sip_peer *peer = (struct sip_peer *)data;
  25821. peer->pokeexpire = -1;
  25822. if (peer->lastms > -1) {
  25823. ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
  25824. if (sip_cfg.peer_rtupdate) {
  25825. ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
  25826. }
  25827. if (peer->endpoint) {
  25828. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  25829. ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_OFFLINE);
  25830. blob = ast_json_pack("{s: s, s: s}",
  25831. "peer_status", "Unreachable",
  25832. "time", "-1");
  25833. ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
  25834. }
  25835. if (sip_cfg.regextenonqualify) {
  25836. register_peer_exten(peer, FALSE);
  25837. }
  25838. }
  25839. if (peer->call) {
  25840. dialog_unlink_all(peer->call);
  25841. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  25842. /* peer->call = sip_destroy(peer->call);*/
  25843. }
  25844. /* Don't send a devstate change if nothing changed. */
  25845. if (peer->lastms > -1) {
  25846. peer->lastms = -1;
  25847. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  25848. }
  25849. /* Try again quickly */
  25850. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
  25851. DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
  25852. sip_unref_peer(_data, "removing poke peer ref"),
  25853. sip_unref_peer(peer, "removing poke peer ref"),
  25854. sip_ref_peer(peer, "adding poke peer ref"));
  25855. /* Release the ref held by the running scheduler entry */
  25856. sip_unref_peer(peer, "release peer poke noanswer ref");
  25857. return 0;
  25858. }
  25859. /*! \brief Check availability of peer, also keep NAT open
  25860. \note This is done with 60 seconds between each ping,
  25861. unless forced by cli or manager. If peer is unreachable,
  25862. we check every 10th second by default.
  25863. \note Do *not* hold a pvt lock while calling this function.
  25864. This function calls sip_alloc, which can cause a deadlock
  25865. if another sip_pvt is held.
  25866. */
  25867. static int sip_poke_peer(struct sip_peer *peer, int force)
  25868. {
  25869. struct sip_pvt *p;
  25870. int xmitres = 0;
  25871. if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
  25872. /* IF we have no IP, or this isn't to be monitored, return
  25873. immediately after clearing things out */
  25874. AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
  25875. sip_unref_peer(peer, "removing poke peer ref"));
  25876. peer->lastms = 0;
  25877. if (peer->call) {
  25878. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  25879. }
  25880. return 0;
  25881. }
  25882. if (peer->call) {
  25883. if (sipdebug) {
  25884. ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
  25885. }
  25886. dialog_unlink_all(peer->call);
  25887. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  25888. /* peer->call = sip_destroy(peer->call); */
  25889. }
  25890. if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL, NULL))) {
  25891. return -1;
  25892. }
  25893. peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
  25894. p->sa = peer->addr;
  25895. p->recv = peer->addr;
  25896. copy_socket_data(&p->socket, &peer->socket);
  25897. ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
  25898. ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  25899. ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  25900. sip_route_copy(&p->route, &peer->path);
  25901. if (!sip_route_empty(&p->route)) {
  25902. /* Parse SIP URI of first route-set hop and use it as target address */
  25903. __set_address_from_contact(sip_route_first_uri(&p->route), &p->sa, p->socket.type == AST_TRANSPORT_TLS ? 1 : 0);
  25904. }
  25905. /* Get the outbound proxy information */
  25906. ref_proxy(p, obproxy_get(p, peer));
  25907. /* Send OPTIONs to peer's fullcontact */
  25908. if (!ast_strlen_zero(peer->fullcontact)) {
  25909. ast_string_field_set(p, fullcontact, peer->fullcontact);
  25910. }
  25911. if (!ast_strlen_zero(peer->fromuser)) {
  25912. ast_string_field_set(p, fromuser, peer->fromuser);
  25913. }
  25914. if (!ast_strlen_zero(peer->tohost)) {
  25915. ast_string_field_set(p, tohost, peer->tohost);
  25916. } else {
  25917. ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
  25918. }
  25919. /* Recalculate our side, and recalculate Call ID */
  25920. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  25921. build_via(p);
  25922. /* Change the dialog callid. */
  25923. change_callid_pvt(p, NULL);
  25924. AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
  25925. sip_unref_peer(peer, "removing poke peer ref"));
  25926. if (p->relatedpeer)
  25927. p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
  25928. p->relatedpeer = sip_ref_peer(peer, "setting the relatedpeer field in the dialog");
  25929. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  25930. #ifdef VOCAL_DATA_HACK
  25931. ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
  25932. xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL); /* sinks the p refcount */
  25933. #else
  25934. xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL); /* sinks the p refcount */
  25935. #endif
  25936. peer->ps = ast_tvnow();
  25937. if (xmitres == XMIT_ERROR) {
  25938. /* Immediately unreachable, network problems */
  25939. sip_poke_noanswer(sip_ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
  25940. } else if (!force) {
  25941. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
  25942. sip_unref_peer(_data, "removing poke peer ref"),
  25943. sip_unref_peer(peer, "removing poke peer ref"),
  25944. sip_ref_peer(peer, "adding poke peer ref"));
  25945. }
  25946. dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
  25947. return 0;
  25948. }
  25949. /*! \brief Part of PBX channel interface
  25950. \note
  25951. \par Return values:---
  25952. If we have qualify on and the device is not reachable, regardless of registration
  25953. state we return AST_DEVICE_UNAVAILABLE
  25954. For peers with call limit:
  25955. - not registered AST_DEVICE_UNAVAILABLE
  25956. - registered, no call AST_DEVICE_NOT_INUSE
  25957. - registered, active calls AST_DEVICE_INUSE
  25958. - registered, call limit reached AST_DEVICE_BUSY
  25959. - registered, onhold AST_DEVICE_ONHOLD
  25960. - registered, ringing AST_DEVICE_RINGING
  25961. For peers without call limit:
  25962. - not registered AST_DEVICE_UNAVAILABLE
  25963. - registered AST_DEVICE_NOT_INUSE
  25964. - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
  25965. Peers that does not have a known call and can't be reached by OPTIONS
  25966. - unreachable AST_DEVICE_UNAVAILABLE
  25967. If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
  25968. out a state by walking the channel list.
  25969. The queue system (\ref app_queue.c) treats a member as "active"
  25970. if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
  25971. When placing a call to the queue member, queue system sets a member to busy if
  25972. != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
  25973. */
  25974. static int sip_devicestate(const char *data)
  25975. {
  25976. char *host;
  25977. char *tmp;
  25978. struct sip_peer *p;
  25979. int res = AST_DEVICE_INVALID;
  25980. /* make sure data is not null. Maybe unnecessary, but better be safe */
  25981. host = ast_strdupa(data ? data : "");
  25982. if ((tmp = strchr(host, '@')))
  25983. host = tmp + 1;
  25984. ast_debug(3, "Checking device state for peer %s\n", host);
  25985. /* If sip_find_peer asks for a realtime peer, then this breaks rtautoclear. This
  25986. * is because when a peer tries to autoexpire, the last thing it does is to
  25987. * queue up an event telling the system that the devicestate has changed
  25988. * (presumably to unavailable). If we ask for a realtime peer here, this would
  25989. * load it BACK into memory, thus defeating the point of trying to clear dead
  25990. * hosts out of memory.
  25991. */
  25992. if ((p = sip_find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
  25993. if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
  25994. /* we have an address for the peer */
  25995. /* Check status in this order
  25996. - Hold
  25997. - Ringing
  25998. - Busy (enforced only by call limit)
  25999. - Inuse (we have a call)
  26000. - Unreachable (qualify)
  26001. If we don't find any of these state, report AST_DEVICE_NOT_INUSE
  26002. for registered devices */
  26003. if (p->onhold)
  26004. /* First check for hold or ring states */
  26005. res = AST_DEVICE_ONHOLD;
  26006. else if (p->ringing) {
  26007. if (p->ringing == p->inuse)
  26008. res = AST_DEVICE_RINGING;
  26009. else
  26010. res = AST_DEVICE_RINGINUSE;
  26011. } else if (p->call_limit && (p->inuse == p->call_limit))
  26012. /* check call limit */
  26013. res = AST_DEVICE_BUSY;
  26014. else if (p->call_limit && p->busy_level && p->inuse >= p->busy_level)
  26015. /* We're forcing busy before we've reached the call limit */
  26016. res = AST_DEVICE_BUSY;
  26017. else if (p->call_limit && p->inuse)
  26018. /* Not busy, but we do have a call */
  26019. res = AST_DEVICE_INUSE;
  26020. else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
  26021. /* We don't have a call. Are we reachable at all? Requires qualify= */
  26022. res = AST_DEVICE_UNAVAILABLE;
  26023. else /* Default reply if we're registered and have no other data */
  26024. res = AST_DEVICE_NOT_INUSE;
  26025. } else {
  26026. /* there is no address, it's unavailable */
  26027. res = AST_DEVICE_UNAVAILABLE;
  26028. }
  26029. sip_unref_peer(p, "sip_unref_peer, from sip_devicestate, release ref from sip_find_peer");
  26030. }
  26031. return res;
  26032. }
  26033. /*! \brief PBX interface function -build SIP pvt structure
  26034. * SIP calls initiated by the PBX arrive here.
  26035. *
  26036. * \verbatim
  26037. * SIP Dial string syntax:
  26038. * SIP/devicename
  26039. * or SIP/username@domain (SIP uri)
  26040. * or SIP/username[:password[:md5secret[:authname[:transport]]]]@host[:port]
  26041. * or SIP/devicename/extension
  26042. * or SIP/devicename/extension/IPorHost
  26043. * or SIP/username@domain//IPorHost
  26044. * and there is an optional [!dnid] argument you can append to alter the
  26045. * To: header.
  26046. * \endverbatim
  26047. */
  26048. 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)
  26049. {
  26050. struct sip_pvt *p;
  26051. struct ast_channel *tmpc = NULL;
  26052. char *ext = NULL, *host;
  26053. char tmp[256];
  26054. struct ast_str *codec_buf = ast_str_alloca(64);
  26055. struct ast_str *cap_buf = ast_str_alloca(64);
  26056. char *dnid;
  26057. char *secret = NULL;
  26058. char *md5secret = NULL;
  26059. char *authname = NULL;
  26060. char *trans = NULL;
  26061. char dialstring[256];
  26062. char *remote_address;
  26063. enum ast_transport transport = 0;
  26064. struct ast_callid *callid;
  26065. AST_DECLARE_APP_ARGS(args,
  26066. AST_APP_ARG(peerorhost);
  26067. AST_APP_ARG(exten);
  26068. AST_APP_ARG(remote_address);
  26069. );
  26070. /* mask request with some set of allowed formats.
  26071. * XXX this needs to be fixed.
  26072. * The original code uses AST_FORMAT_AUDIO_MASK, but it is
  26073. * unclear what to use here. We have global_capabilities, which is
  26074. * configured from sip.conf, and sip_tech.capabilities, which is
  26075. * hardwired to all audio formats.
  26076. */
  26077. if (!(ast_format_cap_has_type(cap, AST_MEDIA_TYPE_AUDIO))) {
  26078. ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n",
  26079. ast_format_cap_get_names(cap, &codec_buf),
  26080. ast_format_cap_get_names(sip_cfg.caps, &cap_buf));
  26081. *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
  26082. return NULL;
  26083. }
  26084. ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_format_cap_get_names(cap, &codec_buf));
  26085. if (ast_strlen_zero(dest)) {
  26086. ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
  26087. *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
  26088. return NULL;
  26089. }
  26090. callid = ast_read_threadstorage_callid();
  26091. if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL, callid))) {
  26092. ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
  26093. *cause = AST_CAUSE_SWITCH_CONGESTION;
  26094. if (callid) {
  26095. ast_callid_unref(callid);
  26096. }
  26097. return NULL;
  26098. }
  26099. p->outgoing_call = TRUE;
  26100. snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
  26101. ast_string_field_set(p, dialstring, dialstring);
  26102. if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
  26103. dialog_unlink_all(p);
  26104. dialog_unref(p, "unref dialog p from mem fail");
  26105. /* sip_destroy(p); */
  26106. ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
  26107. *cause = AST_CAUSE_SWITCH_CONGESTION;
  26108. if (callid) {
  26109. ast_callid_unref(callid);
  26110. }
  26111. return NULL;
  26112. }
  26113. /* Save the destination, the SIP dial string */
  26114. ast_copy_string(tmp, dest, sizeof(tmp));
  26115. /* Find DNID and take it away */
  26116. dnid = strchr(tmp, '!');
  26117. if (dnid != NULL) {
  26118. *dnid++ = '\0';
  26119. ast_string_field_set(p, todnid, dnid);
  26120. }
  26121. /* Divvy up the items separated by slashes */
  26122. AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
  26123. /* Find at sign - @ */
  26124. host = strchr(args.peerorhost, '@');
  26125. if (host) {
  26126. *host++ = '\0';
  26127. ext = args.peerorhost;
  26128. secret = strchr(ext, ':');
  26129. }
  26130. if (secret) {
  26131. *secret++ = '\0';
  26132. md5secret = strchr(secret, ':');
  26133. }
  26134. if (md5secret) {
  26135. *md5secret++ = '\0';
  26136. authname = strchr(md5secret, ':');
  26137. }
  26138. if (authname) {
  26139. *authname++ = '\0';
  26140. trans = strchr(authname, ':');
  26141. }
  26142. if (trans) {
  26143. *trans++ = '\0';
  26144. if (!strcasecmp(trans, "tcp"))
  26145. transport = AST_TRANSPORT_TCP;
  26146. else if (!strcasecmp(trans, "tls"))
  26147. transport = AST_TRANSPORT_TLS;
  26148. else {
  26149. if (strcasecmp(trans, "udp"))
  26150. ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
  26151. transport = AST_TRANSPORT_UDP;
  26152. }
  26153. } else { /* use default */
  26154. transport = AST_TRANSPORT_UDP;
  26155. }
  26156. if (!host) {
  26157. ext = args.exten;
  26158. host = args.peerorhost;
  26159. remote_address = args.remote_address;
  26160. } else {
  26161. remote_address = args.remote_address;
  26162. if (!ast_strlen_zero(args.exten)) {
  26163. ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
  26164. }
  26165. }
  26166. if (!ast_strlen_zero(remote_address)) {
  26167. p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
  26168. if (!p->options->outboundproxy) {
  26169. ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
  26170. }
  26171. }
  26172. set_socket_transport(&p->socket, transport);
  26173. /* We now have
  26174. host = peer name, DNS host name or DNS domain (for SRV)
  26175. ext = extension (user part of URI)
  26176. dnid = destination of the call (applies to the To: header)
  26177. */
  26178. if (create_addr(p, host, NULL, 1)) {
  26179. *cause = AST_CAUSE_UNREGISTERED;
  26180. ast_debug(3, "Cant create SIP call - target device not registered\n");
  26181. dialog_unlink_all(p);
  26182. dialog_unref(p, "unref dialog p UNREGISTERED");
  26183. /* sip_destroy(p); */
  26184. if (callid) {
  26185. ast_callid_unref(callid);
  26186. }
  26187. return NULL;
  26188. }
  26189. if (ast_strlen_zero(p->peername) && ext)
  26190. ast_string_field_set(p, peername, ext);
  26191. /* Recalculate our side, and recalculate Call ID */
  26192. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  26193. /* When chan_sip is first loaded or reloaded, we need to check for NAT and set the appropiate flags
  26194. now that we have the auto_* settings. */
  26195. check_for_nat(&p->sa, p);
  26196. /* If there is a peer related to this outgoing call and it hasn't re-registered after
  26197. a reload, we need to set the peer's NAT flags accordingly. */
  26198. if (p->relatedpeer) {
  26199. if (!ast_strlen_zero(p->relatedpeer->fullcontact) && !p->natdetected &&
  26200. (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) && !ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT))) {
  26201. /* We need to make an attempt to determine if a peer is behind NAT
  26202. if the peer has the auto_force_rport flag set. */
  26203. struct ast_sockaddr tmpaddr;
  26204. __set_address_from_contact(p->relatedpeer->fullcontact, &tmpaddr, 0);
  26205. check_for_nat(&tmpaddr, p);
  26206. }
  26207. set_peer_nat(p, p->relatedpeer);
  26208. }
  26209. do_setnat(p);
  26210. build_via(p);
  26211. /* Change the dialog callid. */
  26212. change_callid_pvt(p, NULL);
  26213. /* We have an extension to call, don't use the full contact here */
  26214. /* This to enable dialing registered peers with extension dialling,
  26215. like SIP/peername/extension
  26216. SIP/peername will still use the full contact
  26217. */
  26218. if (ext) {
  26219. ast_string_field_set(p, username, ext);
  26220. ast_string_field_set(p, fullcontact, NULL);
  26221. }
  26222. if (secret && !ast_strlen_zero(secret))
  26223. ast_string_field_set(p, peersecret, secret);
  26224. if (md5secret && !ast_strlen_zero(md5secret))
  26225. ast_string_field_set(p, peermd5secret, md5secret);
  26226. if (authname && !ast_strlen_zero(authname))
  26227. ast_string_field_set(p, authname, authname);
  26228. #if 0
  26229. printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
  26230. #endif
  26231. ast_format_cap_append_from_cap(p->prefcaps, cap, AST_MEDIA_TYPE_UNKNOWN);
  26232. ast_format_cap_get_compatible(cap, p->caps, p->jointcaps);
  26233. sip_pvt_lock(p);
  26234. tmpc = sip_new(p, AST_STATE_DOWN, host, assignedids, requestor, callid); /* Place the call */
  26235. if (callid) {
  26236. callid = ast_callid_unref(callid);
  26237. }
  26238. sip_pvt_unlock(p);
  26239. if (!tmpc) {
  26240. dialog_unlink_all(p);
  26241. /* sip_destroy(p); */
  26242. } else {
  26243. ast_channel_unlock(tmpc);
  26244. }
  26245. dialog_unref(p, "toss pvt ptr at end of sip_request_call");
  26246. ast_update_use_count();
  26247. restart_monitor();
  26248. return tmpc;
  26249. }
  26250. /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
  26251. static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
  26252. {
  26253. if (ast_strlen_zero(value))
  26254. return;
  26255. if (!ast_false(value)) {
  26256. char buf[64];
  26257. char *word, *next;
  26258. ast_copy_string(buf, value, sizeof(buf));
  26259. next = buf;
  26260. while ((word = strsep(&next, ","))) {
  26261. if (!strcasecmp(word, "port"))
  26262. ast_set_flag(&flags[0], SIP_INSECURE_PORT);
  26263. else if (!strcasecmp(word, "invite"))
  26264. ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
  26265. else
  26266. ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
  26267. }
  26268. }
  26269. }
  26270. /*!
  26271. \brief Handle T.38 configuration options common to users and peers
  26272. \returns non-zero if any config options were handled, zero otherwise
  26273. */
  26274. static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
  26275. unsigned int *maxdatagram)
  26276. {
  26277. int res = 1;
  26278. if (!strcasecmp(v->name, "t38pt_udptl")) {
  26279. char *buf = ast_strdupa(v->value);
  26280. char *word, *next = buf;
  26281. ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
  26282. while ((word = strsep(&next, ","))) {
  26283. if (ast_true(word) || !strcasecmp(word, "fec")) {
  26284. ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
  26285. ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
  26286. } else if (!strcasecmp(word, "redundancy")) {
  26287. ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
  26288. ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
  26289. } else if (!strcasecmp(word, "none")) {
  26290. ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
  26291. ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
  26292. } else if (!strncasecmp(word, "maxdatagram=", 12)) {
  26293. if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
  26294. ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
  26295. *maxdatagram = global_t38_maxdatagram;
  26296. }
  26297. }
  26298. }
  26299. } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
  26300. ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
  26301. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
  26302. } else {
  26303. res = 0;
  26304. }
  26305. return res;
  26306. }
  26307. /*!
  26308. \brief Handle flag-type options common to configuration of devices - peers
  26309. \param flags array of three struct ast_flags
  26310. \param mask array of three struct ast_flags
  26311. \param v linked list of config variables to process
  26312. \returns non-zero if any config options were handled, zero otherwise
  26313. */
  26314. static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
  26315. {
  26316. int res = 1;
  26317. if (!strcasecmp(v->name, "trustrpid")) {
  26318. ast_set_flag(&mask[0], SIP_TRUSTRPID);
  26319. ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
  26320. } else if (!strcasecmp(v->name, "supportpath")) {
  26321. ast_set_flag(&mask[0], SIP_USEPATH);
  26322. ast_set2_flag(&flags[0], ast_true(v->value), SIP_USEPATH);
  26323. } else if (!strcasecmp(v->name, "sendrpid")) {
  26324. ast_set_flag(&mask[0], SIP_SENDRPID);
  26325. if (!strcasecmp(v->value, "pai")) {
  26326. ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
  26327. } else if (!strcasecmp(v->value, "rpid")) {
  26328. ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
  26329. } else if (ast_true(v->value)) {
  26330. ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
  26331. }
  26332. } else if (!strcasecmp(v->name, "rpid_update")) {
  26333. ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
  26334. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
  26335. } else if (!strcasecmp(v->name, "rpid_immediate")) {
  26336. ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
  26337. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
  26338. } else if (!strcasecmp(v->name, "trust_id_outbound")) {
  26339. ast_set_flag(&mask[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
  26340. ast_clear_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
  26341. if (!strcasecmp(v->value, "legacy")) {
  26342. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
  26343. } else if (ast_true(v->value)) {
  26344. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_YES);
  26345. } else if (ast_false(v->value)) {
  26346. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_NO);
  26347. } else {
  26348. ast_log(LOG_WARNING, "Unknown trust_id_outbound mode '%s' on line %d, using legacy\n", v->value, v->lineno);
  26349. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
  26350. }
  26351. } else if (!strcasecmp(v->name, "g726nonstandard")) {
  26352. ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
  26353. ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
  26354. } else if (!strcasecmp(v->name, "useclientcode")) {
  26355. ast_set_flag(&mask[0], SIP_USECLIENTCODE);
  26356. ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
  26357. } else if (!strcasecmp(v->name, "dtmfmode")) {
  26358. ast_set_flag(&mask[0], SIP_DTMF);
  26359. ast_clear_flag(&flags[0], SIP_DTMF);
  26360. if (!strcasecmp(v->value, "inband"))
  26361. ast_set_flag(&flags[0], SIP_DTMF_INBAND);
  26362. else if (!strcasecmp(v->value, "rfc2833"))
  26363. ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
  26364. else if (!strcasecmp(v->value, "info"))
  26365. ast_set_flag(&flags[0], SIP_DTMF_INFO);
  26366. else if (!strcasecmp(v->value, "shortinfo"))
  26367. ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
  26368. else if (!strcasecmp(v->value, "auto"))
  26369. ast_set_flag(&flags[0], SIP_DTMF_AUTO);
  26370. else {
  26371. ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
  26372. ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
  26373. }
  26374. } else if (!strcasecmp(v->name, "nat")) {
  26375. sip_parse_nat_option(v->value, mask, flags);
  26376. } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
  26377. ast_set_flag(&mask[0], SIP_REINVITE);
  26378. ast_clear_flag(&flags[0], SIP_REINVITE);
  26379. if (ast_true(v->value)) {
  26380. ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
  26381. } else if (!ast_false(v->value)) {
  26382. char buf[64];
  26383. char *word, *next = buf;
  26384. ast_copy_string(buf, v->value, sizeof(buf));
  26385. while ((word = strsep(&next, ","))) {
  26386. if (!strcasecmp(word, "update")) {
  26387. ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
  26388. } else if (!strcasecmp(word, "nonat")) {
  26389. ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
  26390. ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
  26391. } else if (!strcasecmp(word, "outgoing")) {
  26392. ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
  26393. ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
  26394. ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
  26395. } else {
  26396. ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
  26397. }
  26398. }
  26399. }
  26400. } else if (!strcasecmp(v->name, "insecure")) {
  26401. ast_set_flag(&mask[0], SIP_INSECURE);
  26402. ast_clear_flag(&flags[0], SIP_INSECURE);
  26403. set_insecure_flags(&flags[0], v->value, v->lineno);
  26404. } else if (!strcasecmp(v->name, "progressinband")) {
  26405. ast_set_flag(&mask[0], SIP_PROG_INBAND);
  26406. ast_clear_flag(&flags[0], SIP_PROG_INBAND);
  26407. if (ast_true(v->value))
  26408. ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
  26409. else if (strcasecmp(v->value, "never"))
  26410. ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
  26411. } else if (!strcasecmp(v->name, "promiscredir")) {
  26412. ast_set_flag(&mask[0], SIP_PROMISCREDIR);
  26413. ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
  26414. } else if (!strcasecmp(v->name, "videosupport")) {
  26415. if (!strcasecmp(v->value, "always")) {
  26416. ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
  26417. ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
  26418. } else {
  26419. ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
  26420. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
  26421. }
  26422. } else if (!strcasecmp(v->name, "textsupport")) {
  26423. ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
  26424. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
  26425. res = 1;
  26426. } else if (!strcasecmp(v->name, "allowoverlap")) {
  26427. ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
  26428. ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
  26429. if (ast_true(v->value)) {
  26430. ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
  26431. } else if (!strcasecmp(v->value, "dtmf")){
  26432. ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
  26433. }
  26434. } else if (!strcasecmp(v->name, "allowsubscribe")) {
  26435. ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
  26436. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
  26437. } else if (!strcasecmp(v->name, "ignoresdpversion")) {
  26438. ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
  26439. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
  26440. } else if (!strcasecmp(v->name, "faxdetect")) {
  26441. ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
  26442. if (ast_true(v->value)) {
  26443. ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
  26444. } else if (ast_false(v->value)) {
  26445. ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
  26446. } else {
  26447. char *buf = ast_strdupa(v->value);
  26448. char *word, *next = buf;
  26449. while ((word = strsep(&next, ","))) {
  26450. if (!strcasecmp(word, "cng")) {
  26451. ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
  26452. } else if (!strcasecmp(word, "t38")) {
  26453. ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
  26454. } else {
  26455. ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
  26456. }
  26457. }
  26458. }
  26459. } else if (!strcasecmp(v->name, "rfc2833compensate")) {
  26460. ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
  26461. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
  26462. } else if (!strcasecmp(v->name, "buggymwi")) {
  26463. ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
  26464. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
  26465. } else
  26466. res = 0;
  26467. return res;
  26468. }
  26469. /*! \brief Add SIP domain to list of domains we are responsible for */
  26470. static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
  26471. {
  26472. struct domain *d;
  26473. if (ast_strlen_zero(domain)) {
  26474. ast_log(LOG_WARNING, "Zero length domain.\n");
  26475. return 1;
  26476. }
  26477. if (!(d = ast_calloc(1, sizeof(*d))))
  26478. return 0;
  26479. ast_copy_string(d->domain, domain, sizeof(d->domain));
  26480. if (!ast_strlen_zero(context))
  26481. ast_copy_string(d->context, context, sizeof(d->context));
  26482. d->mode = mode;
  26483. AST_LIST_LOCK(&domain_list);
  26484. AST_LIST_INSERT_TAIL(&domain_list, d, list);
  26485. AST_LIST_UNLOCK(&domain_list);
  26486. if (sipdebug)
  26487. ast_debug(1, "Added local SIP domain '%s'\n", domain);
  26488. return 1;
  26489. }
  26490. /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
  26491. static int check_sip_domain(const char *domain, char *context, size_t len)
  26492. {
  26493. struct domain *d;
  26494. int result = 0;
  26495. AST_LIST_LOCK(&domain_list);
  26496. AST_LIST_TRAVERSE(&domain_list, d, list) {
  26497. if (strcasecmp(d->domain, domain)) {
  26498. continue;
  26499. }
  26500. if (len && !ast_strlen_zero(d->context))
  26501. ast_copy_string(context, d->context, len);
  26502. result = 1;
  26503. break;
  26504. }
  26505. AST_LIST_UNLOCK(&domain_list);
  26506. return result;
  26507. }
  26508. /*! \brief Clear our domain list (at reload) */
  26509. static void clear_sip_domains(void)
  26510. {
  26511. struct domain *d;
  26512. AST_LIST_LOCK(&domain_list);
  26513. while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
  26514. ast_free(d);
  26515. AST_LIST_UNLOCK(&domain_list);
  26516. }
  26517. /*!
  26518. * \internal
  26519. * \brief Realm authentication container destructor.
  26520. *
  26521. * \param obj Container object to destroy.
  26522. *
  26523. * \return Nothing
  26524. */
  26525. static void destroy_realm_authentication(void *obj)
  26526. {
  26527. struct sip_auth_container *credentials = obj;
  26528. struct sip_auth *auth;
  26529. while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
  26530. ast_free(auth);
  26531. }
  26532. }
  26533. /*!
  26534. * \internal
  26535. * \brief Add realm authentication to credentials.
  26536. *
  26537. * \param credentials Realm authentication container to create/add authentication credentials.
  26538. * \param configuration Credential configuration value.
  26539. * \param lineno Line number in config file.
  26540. *
  26541. * \return Nothing
  26542. */
  26543. static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
  26544. {
  26545. char *authcopy;
  26546. char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
  26547. struct sip_auth *auth;
  26548. if (ast_strlen_zero(configuration)) {
  26549. /* Nothing to add */
  26550. return;
  26551. }
  26552. ast_debug(1, "Auth config :: %s\n", configuration);
  26553. authcopy = ast_strdupa(configuration);
  26554. username = authcopy;
  26555. /* split user[:secret] and relm */
  26556. realm = strrchr(username, '@');
  26557. if (realm)
  26558. *realm++ = '\0';
  26559. if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
  26560. ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
  26561. return;
  26562. }
  26563. /* parse username at ':' for secret, or '#" for md5secret */
  26564. if ((secret = strchr(username, ':'))) {
  26565. *secret++ = '\0';
  26566. } else if ((md5secret = strchr(username, '#'))) {
  26567. *md5secret++ = '\0';
  26568. }
  26569. /* Create the continer if needed. */
  26570. if (!*credentials) {
  26571. *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
  26572. "Create realm auth container.");
  26573. if (!*credentials) {
  26574. /* Failed to create the credentials container. */
  26575. return;
  26576. }
  26577. }
  26578. /* Create the authentication credential entry. */
  26579. auth = ast_calloc(1, sizeof(*auth));
  26580. if (!auth) {
  26581. return;
  26582. }
  26583. ast_copy_string(auth->realm, realm, sizeof(auth->realm));
  26584. ast_copy_string(auth->username, username, sizeof(auth->username));
  26585. if (secret)
  26586. ast_copy_string(auth->secret, secret, sizeof(auth->secret));
  26587. if (md5secret)
  26588. ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
  26589. /* Add credential to container list. */
  26590. AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
  26591. ast_verb(3, "Added authentication for realm %s\n", realm);
  26592. }
  26593. /*!
  26594. * \internal
  26595. * \brief Find authentication for a specific realm.
  26596. *
  26597. * \param credentials Realm authentication container to search.
  26598. * \param realm Authentication realm to find.
  26599. *
  26600. * \return Found authentication credential or NULL.
  26601. */
  26602. static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
  26603. {
  26604. struct sip_auth *auth;
  26605. if (credentials) {
  26606. AST_LIST_TRAVERSE(&credentials->list, auth, node) {
  26607. if (!strcasecmp(auth->realm, realm)) {
  26608. break;
  26609. }
  26610. }
  26611. } else {
  26612. auth = NULL;
  26613. }
  26614. return auth;
  26615. }
  26616. /*! \brief
  26617. * implement the setvar config line
  26618. */
  26619. static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
  26620. {
  26621. struct ast_variable *tmpvar = NULL;
  26622. char *varname = ast_strdupa(buf), *varval = NULL;
  26623. if ((varval = strchr(varname, '='))) {
  26624. *varval++ = '\0';
  26625. if ((tmpvar = ast_variable_new(varname, varval, ""))) {
  26626. tmpvar->next = list;
  26627. list = tmpvar;
  26628. }
  26629. }
  26630. return list;
  26631. }
  26632. /*! \brief Set peer defaults before configuring specific configurations */
  26633. static void set_peer_defaults(struct sip_peer *peer)
  26634. {
  26635. if (peer->expire == 0) {
  26636. /* Don't reset expire or port time during reload
  26637. if we have an active registration
  26638. */
  26639. peer->expire = -1;
  26640. peer->pokeexpire = -1;
  26641. peer->keepalivesend = -1;
  26642. set_socket_transport(&peer->socket, AST_TRANSPORT_UDP);
  26643. }
  26644. peer->type = SIP_TYPE_PEER;
  26645. ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
  26646. ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  26647. ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  26648. ast_string_field_set(peer, context, sip_cfg.default_context);
  26649. ast_string_field_set(peer, record_on_feature, sip_cfg.default_record_on_feature);
  26650. ast_string_field_set(peer, record_off_feature, sip_cfg.default_record_off_feature);
  26651. ast_string_field_set(peer, messagecontext, sip_cfg.messagecontext);
  26652. ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
  26653. ast_string_field_set(peer, language, default_language);
  26654. ast_string_field_set(peer, mohinterpret, default_mohinterpret);
  26655. ast_string_field_set(peer, mohsuggest, default_mohsuggest);
  26656. ast_string_field_set(peer, engine, default_engine);
  26657. ast_sockaddr_setnull(&peer->addr);
  26658. ast_sockaddr_setnull(&peer->defaddr);
  26659. ast_format_cap_append_from_cap(peer->caps, sip_cfg.caps, AST_MEDIA_TYPE_UNKNOWN);
  26660. peer->maxcallbitrate = default_maxcallbitrate;
  26661. peer->rtptimeout = global_rtptimeout;
  26662. peer->rtpholdtimeout = global_rtpholdtimeout;
  26663. peer->rtpkeepalive = global_rtpkeepalive;
  26664. peer->allowtransfer = sip_cfg.allowtransfer;
  26665. peer->autoframing = global_autoframing;
  26666. peer->t38_maxdatagram = global_t38_maxdatagram;
  26667. peer->qualifyfreq = global_qualifyfreq;
  26668. if (global_callcounter)
  26669. peer->call_limit=INT_MAX;
  26670. ast_string_field_set(peer, vmexten, default_vmexten);
  26671. ast_string_field_set(peer, secret, "");
  26672. ast_string_field_set(peer, description, "");
  26673. ast_string_field_set(peer, remotesecret, "");
  26674. ast_string_field_set(peer, md5secret, "");
  26675. ast_string_field_set(peer, cid_num, "");
  26676. ast_string_field_set(peer, cid_name, "");
  26677. ast_string_field_set(peer, cid_tag, "");
  26678. ast_string_field_set(peer, fromdomain, "");
  26679. ast_string_field_set(peer, fromuser, "");
  26680. ast_string_field_set(peer, regexten, "");
  26681. peer->callgroup = 0;
  26682. peer->pickupgroup = 0;
  26683. peer->maxms = default_qualify;
  26684. peer->keepalive = default_keepalive;
  26685. ast_string_field_set(peer, zone, default_zone);
  26686. peer->stimer.st_mode_oper = global_st_mode; /* Session-Timers */
  26687. peer->stimer.st_ref = global_st_refresher;
  26688. peer->stimer.st_min_se = global_min_se;
  26689. peer->stimer.st_max_se = global_max_se;
  26690. peer->timer_t1 = global_t1;
  26691. peer->timer_b = global_timer_b;
  26692. clear_peer_mailboxes(peer);
  26693. peer->disallowed_methods = sip_cfg.disallowed_methods;
  26694. peer->transports = default_transports;
  26695. peer->default_outbound_transport = default_primary_transport;
  26696. if (peer->outboundproxy) {
  26697. ao2_ref(peer->outboundproxy, -1);
  26698. peer->outboundproxy = NULL;
  26699. }
  26700. }
  26701. /*! \brief Create temporary peer (used in autocreatepeer mode) */
  26702. static struct sip_peer *temp_peer(const char *name)
  26703. {
  26704. struct sip_peer *peer;
  26705. if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
  26706. return NULL;
  26707. if (ast_string_field_init(peer, 512)) {
  26708. ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
  26709. return NULL;
  26710. }
  26711. if (!(peer->cc_params = ast_cc_config_params_init())) {
  26712. ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
  26713. return NULL;
  26714. }
  26715. if (!(peer->caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  26716. ao2_t_ref(peer, -1, "failed to allocate format capabilities, drop peer");
  26717. return NULL;
  26718. }
  26719. ast_atomic_fetchadd_int(&apeerobjs, 1);
  26720. set_peer_defaults(peer);
  26721. ast_copy_string(peer->name, name, sizeof(peer->name));
  26722. peer->selfdestruct = TRUE;
  26723. peer->host_dynamic = TRUE;
  26724. reg_source_db(peer);
  26725. return peer;
  26726. }
  26727. /*! \todo document this function */
  26728. static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
  26729. {
  26730. char *next;
  26731. char *mbox;
  26732. next = ast_strdupa(value);
  26733. while ((mbox = strsep(&next, ","))) {
  26734. struct sip_mailbox *mailbox;
  26735. int duplicate = 0;
  26736. /* remove leading/trailing whitespace from mailbox string */
  26737. mbox = ast_strip(mbox);
  26738. if (ast_strlen_zero(mbox)) {
  26739. continue;
  26740. }
  26741. /* Check whether the mailbox is already in the list */
  26742. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  26743. if (!strcmp(mailbox->id, mbox)) {
  26744. duplicate = 1;
  26745. break;
  26746. }
  26747. }
  26748. if (duplicate) {
  26749. continue;
  26750. }
  26751. mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox));
  26752. if (!mailbox) {
  26753. continue;
  26754. }
  26755. strcpy(mailbox->id, mbox); /* SAFE */
  26756. AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
  26757. }
  26758. }
  26759. /*! \brief Build peer from configuration (file or realtime static/dynamic) */
  26760. static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
  26761. {
  26762. struct sip_peer *peer = NULL;
  26763. struct ast_acl_list *oldacl = NULL;
  26764. struct ast_acl_list *olddirectmediaacl = NULL;
  26765. int found = 0;
  26766. int firstpass = 1;
  26767. uint16_t port = 0;
  26768. int format = 0; /* Ama flags */
  26769. int timerb_set = 0, timert1_set = 0;
  26770. time_t regseconds = 0;
  26771. struct ast_flags peerflags[3] = {{(0)}};
  26772. struct ast_flags mask[3] = {{(0)}};
  26773. struct sip_peer tmp_peer;
  26774. const char *srvlookup = NULL;
  26775. static int deprecation_warning = 1;
  26776. int alt_fullcontact = alt ? 1 : 0, headercount = 0;
  26777. struct ast_str *fullcontact = ast_str_alloca(512);
  26778. int acl_change_subscription_needed = 0;
  26779. if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  26780. /* Note we do NOT use sip_find_peer here, to avoid realtime recursion */
  26781. /* We also use a case-sensitive comparison (unlike sip_find_peer) so
  26782. that case changes made to the peer name will be properly handled
  26783. during reload
  26784. */
  26785. ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
  26786. peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
  26787. }
  26788. if (peer) {
  26789. /* Already in the list, remove it and it will be added back (or FREE'd) */
  26790. found++;
  26791. /* we've unlinked the peer from the peers container but not unlinked from the peers_by_ip container yet
  26792. this leads to a wrong refcounter and the peer object is never destroyed */
  26793. if (!ast_sockaddr_isnull(&peer->addr)) {
  26794. ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
  26795. }
  26796. if (!(peer->the_mark))
  26797. firstpass = 0;
  26798. } else {
  26799. if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct"))) {
  26800. return NULL;
  26801. }
  26802. if (!(peer->endpoint = ast_endpoint_create("SIP", name))) {
  26803. return NULL;
  26804. }
  26805. if (!(peer->caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  26806. ao2_t_ref(peer, -1, "failed to allocate format capabilities, drop peer");
  26807. return NULL;
  26808. }
  26809. if (ast_string_field_init(peer, 512)) {
  26810. ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
  26811. return NULL;
  26812. }
  26813. if (!(peer->cc_params = ast_cc_config_params_init())) {
  26814. ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
  26815. return NULL;
  26816. }
  26817. if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  26818. ast_atomic_fetchadd_int(&rpeerobjs, 1);
  26819. ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
  26820. } else
  26821. ast_atomic_fetchadd_int(&speerobjs, 1);
  26822. }
  26823. /* Note that our peer HAS had its reference count increased */
  26824. if (firstpass) {
  26825. oldacl = peer->acl;
  26826. peer->acl = NULL;
  26827. olddirectmediaacl = peer->directmediaacl;
  26828. peer->directmediaacl = NULL;
  26829. set_peer_defaults(peer); /* Set peer defaults */
  26830. peer->type = 0;
  26831. }
  26832. /* in case the case of the peer name has changed, update the name */
  26833. ast_copy_string(peer->name, name, sizeof(peer->name));
  26834. /* If we have channel variables, remove them (reload) */
  26835. if (peer->chanvars) {
  26836. ast_variables_destroy(peer->chanvars);
  26837. peer->chanvars = NULL;
  26838. /* XXX should unregister ? */
  26839. }
  26840. if (found)
  26841. peer->portinuri = 0;
  26842. /* If we have realm authentication information, remove them (reload) */
  26843. ao2_lock(peer);
  26844. if (peer->auth) {
  26845. ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
  26846. peer->auth = NULL;
  26847. }
  26848. ao2_unlock(peer);
  26849. /* clear the transport information. We will detect if a default value is required after parsing the config */
  26850. peer->default_outbound_transport = 0;
  26851. peer->transports = 0;
  26852. if (!devstate_only) {
  26853. struct sip_mailbox *mailbox;
  26854. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  26855. mailbox->delme = 1;
  26856. }
  26857. }
  26858. /* clear named callgroup and named pickup group container */
  26859. peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
  26860. peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
  26861. for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
  26862. if (!devstate_only) {
  26863. if (handle_common_options(&peerflags[0], &mask[0], v)) {
  26864. continue;
  26865. }
  26866. if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
  26867. continue;
  26868. }
  26869. if (!strcasecmp(v->name, "transport")) {
  26870. char *val = ast_strdupa(v->value);
  26871. char *trans;
  26872. peer->transports = peer->default_outbound_transport = 0;
  26873. while ((trans = strsep(&val, ","))) {
  26874. trans = ast_skip_blanks(trans);
  26875. if (!strncasecmp(trans, "udp", 3)) {
  26876. peer->transports |= AST_TRANSPORT_UDP;
  26877. } else if (!strncasecmp(trans, "wss", 3)) {
  26878. peer->transports |= AST_TRANSPORT_WSS;
  26879. } else if (!strncasecmp(trans, "ws", 2)) {
  26880. peer->transports |= AST_TRANSPORT_WS;
  26881. } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
  26882. peer->transports |= AST_TRANSPORT_TCP;
  26883. } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
  26884. peer->transports |= AST_TRANSPORT_TLS;
  26885. } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
  26886. 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);
  26887. } else {
  26888. 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);
  26889. }
  26890. if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
  26891. peer->default_outbound_transport = peer->transports;
  26892. }
  26893. }
  26894. } else if (realtime && !strcasecmp(v->name, "regseconds")) {
  26895. ast_get_time_t(v->value, &regseconds, 0, NULL);
  26896. } else if (realtime && !strcasecmp(v->name, "name")) {
  26897. ast_copy_string(peer->name, v->value, sizeof(peer->name));
  26898. } else if (realtime && !strcasecmp(v->name, "useragent")) {
  26899. ast_string_field_set(peer, useragent, v->value);
  26900. } else if (!strcasecmp(v->name, "type")) {
  26901. if (!strcasecmp(v->value, "peer")) {
  26902. peer->type |= SIP_TYPE_PEER;
  26903. } else if (!strcasecmp(v->value, "user")) {
  26904. peer->type |= SIP_TYPE_USER;
  26905. } else if (!strcasecmp(v->value, "friend")) {
  26906. peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
  26907. }
  26908. } else if (!strcasecmp(v->name, "remotesecret")) {
  26909. ast_string_field_set(peer, remotesecret, v->value);
  26910. } else if (!strcasecmp(v->name, "secret")) {
  26911. ast_string_field_set(peer, secret, v->value);
  26912. } else if (!strcasecmp(v->name, "description")) {
  26913. ast_string_field_set(peer, description, v->value);
  26914. } else if (!strcasecmp(v->name, "md5secret")) {
  26915. ast_string_field_set(peer, md5secret, v->value);
  26916. } else if (!strcasecmp(v->name, "auth")) {
  26917. add_realm_authentication(&peer->auth, v->value, v->lineno);
  26918. } else if (!strcasecmp(v->name, "callerid")) {
  26919. char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
  26920. ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
  26921. ast_string_field_set(peer, cid_name, cid_name);
  26922. ast_string_field_set(peer, cid_num, cid_num);
  26923. } else if (!strcasecmp(v->name, "mwi_from")) {
  26924. ast_string_field_set(peer, mwi_from, v->value);
  26925. } else if (!strcasecmp(v->name, "fullname")) {
  26926. ast_string_field_set(peer, cid_name, v->value);
  26927. } else if (!strcasecmp(v->name, "trunkname")) {
  26928. /* This is actually for a trunk, so we don't want to override callerid */
  26929. ast_string_field_set(peer, cid_name, "");
  26930. } else if (!strcasecmp(v->name, "cid_number")) {
  26931. ast_string_field_set(peer, cid_num, v->value);
  26932. } else if (!strcasecmp(v->name, "cid_tag")) {
  26933. ast_string_field_set(peer, cid_tag, v->value);
  26934. } else if (!strcasecmp(v->name, "context")) {
  26935. ast_string_field_set(peer, context, v->value);
  26936. ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
  26937. } else if (!strcasecmp(v->name, "recordonfeature")) {
  26938. ast_string_field_set(peer, record_on_feature, v->value);
  26939. } else if (!strcasecmp(v->name, "recordofffeature")) {
  26940. ast_string_field_set(peer, record_off_feature, v->value);
  26941. } else if (!strcasecmp(v->name, "outofcall_message_context")) {
  26942. ast_string_field_set(peer, messagecontext, v->value);
  26943. } else if (!strcasecmp(v->name, "subscribecontext")) {
  26944. ast_string_field_set(peer, subscribecontext, v->value);
  26945. } else if (!strcasecmp(v->name, "fromdomain")) {
  26946. char *fromdomainport;
  26947. ast_string_field_set(peer, fromdomain, v->value);
  26948. if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
  26949. *fromdomainport++ = '\0';
  26950. if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
  26951. ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
  26952. }
  26953. } else {
  26954. peer->fromdomainport = STANDARD_SIP_PORT;
  26955. }
  26956. } else if (!strcasecmp(v->name, "usereqphone")) {
  26957. ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
  26958. } else if (!strcasecmp(v->name, "fromuser")) {
  26959. ast_string_field_set(peer, fromuser, v->value);
  26960. } else if (!strcasecmp(v->name, "outboundproxy")) {
  26961. struct sip_proxy *proxy;
  26962. if (ast_strlen_zero(v->value)) {
  26963. ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
  26964. continue;
  26965. }
  26966. proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
  26967. if (!proxy) {
  26968. ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
  26969. continue;
  26970. }
  26971. peer->outboundproxy = proxy;
  26972. } else if (!strcasecmp(v->name, "host")) {
  26973. if (!strcasecmp(v->value, "dynamic")) {
  26974. /* They'll register with us */
  26975. if ((!found && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) || !peer->host_dynamic) {
  26976. /* Initialize stuff if this is a new peer, or if it used to
  26977. * not be dynamic before the reload. */
  26978. ast_sockaddr_setnull(&peer->addr);
  26979. }
  26980. peer->host_dynamic = TRUE;
  26981. } else {
  26982. /* Non-dynamic. Make sure we become that way if we're not */
  26983. AST_SCHED_DEL_UNREF(sched, peer->expire,
  26984. sip_unref_peer(peer, "removing register expire ref"));
  26985. peer->host_dynamic = FALSE;
  26986. srvlookup = v->value;
  26987. }
  26988. } else if (!strcasecmp(v->name, "defaultip")) {
  26989. peer->defaddr.ss.ss_family = AST_AF_UNSPEC;
  26990. if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
  26991. sip_unref_peer(peer, "sip_unref_peer: from build_peer defaultip");
  26992. return NULL;
  26993. }
  26994. } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny") || !strcasecmp(v->name, "acl")) {
  26995. int ha_error = 0;
  26996. if (!ast_strlen_zero(v->value)) {
  26997. ast_append_acl(v->name, v->value, &peer->acl, &ha_error, &acl_change_subscription_needed);
  26998. }
  26999. if (ha_error) {
  27000. ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  27001. }
  27002. } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny") || !strcasecmp(v->name, "contactacl")) {
  27003. int ha_error = 0;
  27004. if (!ast_strlen_zero(v->value)) {
  27005. ast_append_acl(v->name + 7, v->value, &peer->contactacl, &ha_error, &acl_change_subscription_needed);
  27006. }
  27007. if (ha_error) {
  27008. ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  27009. }
  27010. } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny") || !strcasecmp(v->name, "directmediaacl")) {
  27011. int ha_error = 0;
  27012. ast_append_acl(v->name + 11, v->value, &peer->directmediaacl, &ha_error, &acl_change_subscription_needed);
  27013. if (ha_error) {
  27014. ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  27015. }
  27016. } else if (!strcasecmp(v->name, "port")) {
  27017. peer->portinuri = 1;
  27018. if (!(port = port_str2int(v->value, 0))) {
  27019. if (realtime) {
  27020. /* If stored as integer, could be 0 for some DBs (notably MySQL) */
  27021. peer->portinuri = 0;
  27022. } else {
  27023. ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
  27024. }
  27025. }
  27026. } else if (!strcasecmp(v->name, "callingpres")) {
  27027. peer->callingpres = ast_parse_caller_presentation(v->value);
  27028. if (peer->callingpres == -1) {
  27029. peer->callingpres = atoi(v->value);
  27030. }
  27031. } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) { /* "username" is deprecated */
  27032. ast_string_field_set(peer, username, v->value);
  27033. if (!strcasecmp(v->name, "username")) {
  27034. if (deprecation_warning) {
  27035. ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
  27036. deprecation_warning = 0;
  27037. }
  27038. peer->deprecated_username = 1;
  27039. }
  27040. } else if (!strcasecmp(v->name, "tonezone")) {
  27041. struct ast_tone_zone *new_zone;
  27042. if (!(new_zone = ast_get_indication_zone(v->value))) {
  27043. 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);
  27044. } else {
  27045. ast_tone_zone_unref(new_zone);
  27046. ast_string_field_set(peer, zone, v->value);
  27047. }
  27048. } else if (!strcasecmp(v->name, "language")) {
  27049. ast_string_field_set(peer, language, v->value);
  27050. } else if (!strcasecmp(v->name, "regexten")) {
  27051. ast_string_field_set(peer, regexten, v->value);
  27052. } else if (!strcasecmp(v->name, "callbackextension")) {
  27053. ast_string_field_set(peer, callback, v->value);
  27054. } else if (!strcasecmp(v->name, "amaflags")) {
  27055. format = ast_channel_string2amaflag(v->value);
  27056. if (format < 0) {
  27057. ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
  27058. } else {
  27059. peer->amaflags = format;
  27060. }
  27061. } else if (!strcasecmp(v->name, "maxforwards")) {
  27062. if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
  27063. || peer->maxforwards < 1 || 255 < peer->maxforwards) {
  27064. ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
  27065. peer->maxforwards = sip_cfg.default_max_forwards;
  27066. }
  27067. } else if (!strcasecmp(v->name, "accountcode")) {
  27068. ast_string_field_set(peer, accountcode, v->value);
  27069. } else if (!strcasecmp(v->name, "mohinterpret")) {
  27070. ast_string_field_set(peer, mohinterpret, v->value);
  27071. } else if (!strcasecmp(v->name, "mohsuggest")) {
  27072. ast_string_field_set(peer, mohsuggest, v->value);
  27073. } else if (!strcasecmp(v->name, "parkinglot")) {
  27074. ast_string_field_set(peer, parkinglot, v->value);
  27075. } else if (!strcasecmp(v->name, "rtp_engine")) {
  27076. ast_string_field_set(peer, engine, v->value);
  27077. } else if (!strcasecmp(v->name, "mailbox")) {
  27078. add_peer_mailboxes(peer, v->value);
  27079. } else if (!strcasecmp(v->name, "hasvoicemail")) {
  27080. /* People expect that if 'hasvoicemail' is set, that the mailbox will
  27081. * be also set, even if not explicitly specified. */
  27082. if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
  27083. /*
  27084. * hasvoicemail is a users.conf legacy voicemail enable method.
  27085. * hasvoicemail is only going to work for app_voicemail mailboxes.
  27086. */
  27087. if (strchr(name, '@')) {
  27088. add_peer_mailboxes(peer, name);
  27089. } else {
  27090. char mailbox[AST_MAX_MAILBOX_UNIQUEID];
  27091. snprintf(mailbox, sizeof(mailbox), "%s@default", name);
  27092. add_peer_mailboxes(peer, mailbox);
  27093. }
  27094. }
  27095. } else if (!strcasecmp(v->name, "subscribemwi")) {
  27096. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
  27097. } else if (!strcasecmp(v->name, "vmexten")) {
  27098. ast_string_field_set(peer, vmexten, v->value);
  27099. } else if (!strcasecmp(v->name, "callgroup")) {
  27100. peer->callgroup = ast_get_group(v->value);
  27101. } else if (!strcasecmp(v->name, "allowtransfer")) {
  27102. peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
  27103. } else if (!strcasecmp(v->name, "pickupgroup")) {
  27104. peer->pickupgroup = ast_get_group(v->value);
  27105. } else if (!strcasecmp(v->name, "namedcallgroup")) {
  27106. peer->named_callgroups = ast_get_namedgroups(v->value);
  27107. } else if (!strcasecmp(v->name, "namedpickupgroup")) {
  27108. peer->named_pickupgroups = ast_get_namedgroups(v->value);
  27109. } else if (!strcasecmp(v->name, "allow")) {
  27110. int error = ast_format_cap_update_by_allow_disallow(peer->caps, v->value, TRUE);
  27111. if (error) {
  27112. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  27113. }
  27114. } else if (!strcasecmp(v->name, "disallow")) {
  27115. int error = ast_format_cap_update_by_allow_disallow(peer->caps, v->value, FALSE);
  27116. if (error) {
  27117. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  27118. }
  27119. } else if (!strcasecmp(v->name, "preferred_codec_only")) {
  27120. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
  27121. } else if (!strcasecmp(v->name, "autoframing")) {
  27122. peer->autoframing = ast_true(v->value);
  27123. } else if (!strcasecmp(v->name, "rtptimeout")) {
  27124. if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
  27125. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  27126. peer->rtptimeout = global_rtptimeout;
  27127. }
  27128. } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
  27129. if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
  27130. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  27131. peer->rtpholdtimeout = global_rtpholdtimeout;
  27132. }
  27133. } else if (!strcasecmp(v->name, "rtpkeepalive")) {
  27134. if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
  27135. ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
  27136. peer->rtpkeepalive = global_rtpkeepalive;
  27137. }
  27138. } else if (!strcasecmp(v->name, "timert1")) {
  27139. if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
  27140. ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
  27141. peer->timer_t1 = global_t1min;
  27142. }
  27143. timert1_set = 1;
  27144. } else if (!strcasecmp(v->name, "timerb")) {
  27145. if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
  27146. ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
  27147. peer->timer_b = global_timer_b;
  27148. }
  27149. timerb_set = 1;
  27150. } else if (!strcasecmp(v->name, "setvar")) {
  27151. peer->chanvars = add_var(v->value, peer->chanvars);
  27152. } else if (!strcasecmp(v->name, "header")) {
  27153. char tmp[4096];
  27154. snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
  27155. peer->chanvars = add_var(tmp, peer->chanvars);
  27156. } else if (!strcasecmp(v->name, "qualifyfreq")) {
  27157. int i;
  27158. if (sscanf(v->value, "%30d", &i) == 1) {
  27159. peer->qualifyfreq = i * 1000;
  27160. } else {
  27161. ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
  27162. peer->qualifyfreq = global_qualifyfreq;
  27163. }
  27164. } else if (!strcasecmp(v->name, "maxcallbitrate")) {
  27165. peer->maxcallbitrate = atoi(v->value);
  27166. if (peer->maxcallbitrate < 0) {
  27167. peer->maxcallbitrate = default_maxcallbitrate;
  27168. }
  27169. } else if (!strcasecmp(v->name, "session-timers")) {
  27170. int i = (int) str2stmode(v->value);
  27171. if (i < 0) {
  27172. ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
  27173. peer->stimer.st_mode_oper = global_st_mode;
  27174. } else {
  27175. peer->stimer.st_mode_oper = i;
  27176. }
  27177. } else if (!strcasecmp(v->name, "session-expires")) {
  27178. if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
  27179. ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
  27180. peer->stimer.st_max_se = global_max_se;
  27181. }
  27182. } else if (!strcasecmp(v->name, "session-minse")) {
  27183. if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
  27184. ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
  27185. peer->stimer.st_min_se = global_min_se;
  27186. }
  27187. if (peer->stimer.st_min_se < DEFAULT_MIN_SE) {
  27188. 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);
  27189. peer->stimer.st_min_se = global_min_se;
  27190. }
  27191. } else if (!strcasecmp(v->name, "session-refresher")) {
  27192. int i = (int) str2strefresherparam(v->value);
  27193. if (i < 0) {
  27194. ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
  27195. peer->stimer.st_ref = global_st_refresher;
  27196. } else {
  27197. peer->stimer.st_ref = i;
  27198. }
  27199. } else if (!strcasecmp(v->name, "disallowed_methods")) {
  27200. char *disallow = ast_strdupa(v->value);
  27201. mark_parsed_methods(&peer->disallowed_methods, disallow);
  27202. } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
  27203. ast_string_field_set(peer, unsolicited_mailbox, v->value);
  27204. } else if (!strcasecmp(v->name, "use_q850_reason")) {
  27205. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
  27206. } else if (!strcasecmp(v->name, "encryption")) {
  27207. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
  27208. } else if (!strcasecmp(v->name, "encryption_taglen")) {
  27209. ast_set2_flag(&peer->flags[2], !strcasecmp(v->value, "32"), SIP_PAGE3_SRTP_TAG_32);
  27210. } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
  27211. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
  27212. } else if (!strcasecmp(v->name, "avpf")) {
  27213. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_USE_AVPF);
  27214. } else if (!strcasecmp(v->name, "icesupport")) {
  27215. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_ICE_SUPPORT);
  27216. } else if (!strcasecmp(v->name, "ignore_requested_pref")) {
  27217. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_IGNORE_PREFCAPS);
  27218. } else if (!strcasecmp(v->name, "discard_remote_hold_retrieval")) {
  27219. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_DISCARD_REMOTE_HOLD_RETRIEVAL);
  27220. } else if (!strcasecmp(v->name, "force_avp")) {
  27221. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_FORCE_AVP);
  27222. } else {
  27223. ast_rtp_dtls_cfg_parse(&peer->dtls_cfg, v->name, v->value);
  27224. }
  27225. }
  27226. /* Apply the encryption tag length to the DTLS configuration, in case DTLS is in use */
  27227. 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);
  27228. /* These apply to devstate lookups */
  27229. if (realtime && !strcasecmp(v->name, "lastms")) {
  27230. sscanf(v->value, "%30d", &peer->lastms);
  27231. } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
  27232. ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
  27233. } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
  27234. if (alt_fullcontact && !alt) {
  27235. /* Reset, because the alternate also has a fullcontact and we
  27236. * do NOT want the field value to be doubled. It might be
  27237. * tempting to skip this, but the first table might not have
  27238. * fullcontact and since we're here, we know that the alternate
  27239. * absolutely does. */
  27240. alt_fullcontact = 0;
  27241. ast_str_reset(fullcontact);
  27242. }
  27243. /* Reconstruct field, because realtime separates our value at the ';' */
  27244. if (ast_str_strlen(fullcontact) > 0) {
  27245. ast_str_append(&fullcontact, 0, ";%s", v->value);
  27246. } else {
  27247. ast_str_set(&fullcontact, 0, "%s", v->value);
  27248. }
  27249. } else if (!strcasecmp(v->name, "qualify")) {
  27250. if (!strcasecmp(v->value, "no")) {
  27251. peer->maxms = 0;
  27252. } else if (!strcasecmp(v->value, "yes")) {
  27253. peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
  27254. } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
  27255. 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);
  27256. peer->maxms = 0;
  27257. }
  27258. if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
  27259. /* This would otherwise cause a network storm, where the
  27260. * qualify response refreshes the peer from the database,
  27261. * which in turn causes another qualify to be sent, ad
  27262. * infinitum. */
  27263. 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);
  27264. peer->maxms = 0;
  27265. }
  27266. } else if (!strcasecmp(v->name, "keepalive")) {
  27267. if (!strcasecmp(v->value, "no")) {
  27268. peer->keepalive = 0;
  27269. } else if (!strcasecmp(v->value, "yes")) {
  27270. peer->keepalive = DEFAULT_KEEPALIVE_INTERVAL;
  27271. } else if (sscanf(v->value, "%30d", &peer->keepalive) != 1) {
  27272. 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);
  27273. peer->keepalive = 0;
  27274. }
  27275. } else if (!strcasecmp(v->name, "callcounter")) {
  27276. peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
  27277. } else if (!strcasecmp(v->name, "call-limit")) {
  27278. peer->call_limit = atoi(v->value);
  27279. if (peer->call_limit < 0) {
  27280. peer->call_limit = 0;
  27281. }
  27282. } else if (!strcasecmp(v->name, "busylevel")) {
  27283. peer->busy_level = atoi(v->value);
  27284. if (peer->busy_level < 0) {
  27285. peer->busy_level = 0;
  27286. }
  27287. } else if (ast_cc_is_config_param(v->name)) {
  27288. ast_cc_set_param(peer->cc_params, v->name, v->value);
  27289. }
  27290. }
  27291. if (!devstate_only) {
  27292. struct sip_mailbox *mailbox;
  27293. AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
  27294. if (mailbox->delme) {
  27295. AST_LIST_REMOVE_CURRENT(entry);
  27296. destroy_mailbox(mailbox);
  27297. }
  27298. }
  27299. AST_LIST_TRAVERSE_SAFE_END;
  27300. }
  27301. if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
  27302. 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);
  27303. ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
  27304. }
  27305. /* Note that Timer B is dependent upon T1 and MUST NOT be lower
  27306. * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
  27307. if (peer->timer_b < peer->timer_t1 * 64) {
  27308. if (timerb_set && timert1_set) {
  27309. 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);
  27310. } else if (timerb_set) {
  27311. if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
  27312. 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);
  27313. peer->timer_t1 = global_t1min;
  27314. peer->timer_b = peer->timer_t1 * 64;
  27315. }
  27316. peer->timer_t1 = peer->timer_b / 64;
  27317. } else {
  27318. peer->timer_b = peer->timer_t1 * 64;
  27319. }
  27320. }
  27321. if (!peer->default_outbound_transport) {
  27322. /* Set default set of transports */
  27323. peer->transports = default_transports;
  27324. /* Set default primary transport */
  27325. peer->default_outbound_transport = default_primary_transport;
  27326. }
  27327. /* The default transport type set during build_peer should only replace the socket.type when...
  27328. * 1. Registration is not present and the socket.type and default transport types are different.
  27329. * 2. The socket.type is not an acceptable transport type after rebuilding peer.
  27330. * 3. The socket.type is not set yet. */
  27331. if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
  27332. !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
  27333. set_socket_transport(&peer->socket, peer->default_outbound_transport);
  27334. }
  27335. ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
  27336. ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
  27337. ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
  27338. if (ast_str_strlen(fullcontact)) {
  27339. ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
  27340. peer->rt_fromcontact = TRUE;
  27341. /* We have a hostname in the fullcontact, but if we don't have an
  27342. * address listed on the entry (or if it's 'dynamic'), then we need to
  27343. * parse the entry to obtain the IP address, so a dynamic host can be
  27344. * contacted immediately after reload (as opposed to waiting for it to
  27345. * register once again). But if we have an address for this peer and NAT was
  27346. * specified, use that address instead. */
  27347. /* XXX May need to revisit the final argument; does the realtime DB store whether
  27348. * the original contact was over TLS or not? XXX */
  27349. if ((!ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT))
  27350. || ast_sockaddr_isnull(&peer->addr)) {
  27351. __set_address_from_contact(ast_str_buffer(fullcontact), &peer->addr, 0);
  27352. }
  27353. }
  27354. if (srvlookup && peer->dnsmgr == NULL) {
  27355. char transport[MAXHOSTNAMELEN];
  27356. char _srvlookup[MAXHOSTNAMELEN];
  27357. char *params;
  27358. ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
  27359. if ((params = strchr(_srvlookup, ';'))) {
  27360. *params++ = '\0';
  27361. }
  27362. snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
  27363. peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type); /* Filter address family */
  27364. if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
  27365. on_dns_update_peer, sip_ref_peer(peer, "Store peer on dnsmgr"))) {
  27366. ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
  27367. sip_unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
  27368. sip_unref_peer(peer, "getting rid of a peer pointer");
  27369. return NULL;
  27370. }
  27371. if (!peer->dnsmgr) {
  27372. /* dnsmgr refresh disabeld, release reference */
  27373. sip_unref_peer(peer, "dnsmgr disabled, unref peer");
  27374. }
  27375. ast_string_field_set(peer, tohost, srvlookup);
  27376. if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
  27377. int ha_error = 0;
  27378. ast_append_acl("deny", ast_sockaddr_stringify_addr(&peer->addr), &sip_cfg.contact_acl, &ha_error, NULL);
  27379. if (ha_error) {
  27380. ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
  27381. }
  27382. }
  27383. } else if (peer->dnsmgr && !peer->host_dynamic) {
  27384. /* force a refresh here on reload if dnsmgr already exists and host is set. */
  27385. ast_dnsmgr_refresh(peer->dnsmgr);
  27386. }
  27387. if (port && !realtime && peer->host_dynamic) {
  27388. ast_sockaddr_set_port(&peer->defaddr, port);
  27389. } else if (port) {
  27390. ast_sockaddr_set_port(&peer->addr, port);
  27391. }
  27392. if (ast_sockaddr_port(&peer->addr) == 0) {
  27393. ast_sockaddr_set_port(&peer->addr,
  27394. (peer->socket.type & AST_TRANSPORT_TLS) ?
  27395. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  27396. }
  27397. if (ast_sockaddr_port(&peer->defaddr) == 0) {
  27398. ast_sockaddr_set_port(&peer->defaddr,
  27399. (peer->socket.type & AST_TRANSPORT_TLS) ?
  27400. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  27401. }
  27402. if (!peer->socket.port) {
  27403. peer->socket.port = htons(((peer->socket.type & AST_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
  27404. }
  27405. if (realtime) {
  27406. int enablepoke = 1;
  27407. if (!sip_cfg.ignore_regexpire && peer->host_dynamic) {
  27408. time_t nowtime = time(NULL);
  27409. if ((nowtime - regseconds) > 0) {
  27410. destroy_association(peer);
  27411. memset(&peer->addr, 0, sizeof(peer->addr));
  27412. peer->lastms = -1;
  27413. enablepoke = 0;
  27414. ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
  27415. }
  27416. }
  27417. /* Startup regular pokes */
  27418. if (!devstate_only && enablepoke) {
  27419. sip_poke_peer(peer, 0);
  27420. }
  27421. }
  27422. if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
  27423. sip_cfg.allowsubscribe = TRUE; /* No global ban any more */
  27424. }
  27425. /* If read-only RT backend, then refresh from local DB cache */
  27426. if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
  27427. reg_source_db(peer);
  27428. }
  27429. /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
  27430. * subscribe to it now. */
  27431. if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
  27432. !AST_LIST_EMPTY(&peer->mailboxes)) {
  27433. add_peer_mwi_subs(peer);
  27434. /* Send MWI from the event cache only. This is so we can send initial
  27435. * MWI if app_voicemail got loaded before chan_sip. If it is the other
  27436. * way, then we will get events when app_voicemail gets loaded. */
  27437. sip_send_mwi_to_peer(peer, 1);
  27438. }
  27439. peer->the_mark = 0;
  27440. oldacl = ast_free_acl_list(oldacl);
  27441. olddirectmediaacl = ast_free_acl_list(olddirectmediaacl);
  27442. if (!ast_strlen_zero(peer->callback)) { /* build string from peer info */
  27443. char *reg_string;
  27444. 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) {
  27445. sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
  27446. ast_free(reg_string);
  27447. }
  27448. }
  27449. /* If an ACL change subscription is needed and doesn't exist, we need one. */
  27450. if (acl_change_subscription_needed) {
  27451. acl_change_stasis_subscribe();
  27452. }
  27453. return peer;
  27454. }
  27455. static int peer_markall_func(void *device, void *arg, int flags)
  27456. {
  27457. struct sip_peer *peer = device;
  27458. if (!peer->selfdestruct) {
  27459. peer->the_mark = 1;
  27460. }
  27461. return 0;
  27462. }
  27463. static int peer_markall_autopeers_func(void *device, void *arg, int flags)
  27464. {
  27465. struct sip_peer *peer = device;
  27466. if (peer->selfdestruct) {
  27467. peer->the_mark = 1;
  27468. }
  27469. return 0;
  27470. }
  27471. /*!
  27472. * \internal
  27473. * \brief If no default formats are set in config, these are used
  27474. */
  27475. static void sip_set_default_format_capabilities(struct ast_format_cap *cap)
  27476. {
  27477. ast_format_cap_remove_by_type(cap, AST_MEDIA_TYPE_UNKNOWN);
  27478. ast_format_cap_append(cap, ast_format_ulaw, 0);
  27479. ast_format_cap_append(cap, ast_format_alaw, 0);
  27480. ast_format_cap_append(cap, ast_format_gsm, 0);
  27481. ast_format_cap_append(cap, ast_format_h263, 0);
  27482. }
  27483. static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
  27484. int global_nat, specific_nat;
  27485. 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))) {
  27486. ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the global setting can make\n");
  27487. ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
  27488. ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
  27489. ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
  27490. 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));
  27491. }
  27492. }
  27493. static void cleanup_all_regs(void)
  27494. {
  27495. struct ao2_iterator iter;
  27496. struct sip_registry *iterator;
  27497. /* First, destroy all outstanding registry calls */
  27498. /* This is needed, since otherwise active registry entries will not be destroyed */
  27499. iter = ao2_iterator_init(registry_list, 0);
  27500. while ((iterator = ao2_t_iterator_next(&iter, "cleanup_all_regs iter"))) {
  27501. ao2_lock(iterator);
  27502. if (iterator->call) {
  27503. ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
  27504. /* This will also remove references to the registry */
  27505. dialog_unlink_all(iterator->call);
  27506. iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
  27507. }
  27508. if (iterator->expire > -1) {
  27509. AST_SCHED_DEL_UNREF(sched, iterator->expire, ao2_t_ref(iterator, -1, "reg ptr unref from reload config"));
  27510. }
  27511. if (iterator->timeout > -1) {
  27512. AST_SCHED_DEL_UNREF(sched, iterator->timeout, ao2_t_ref(iterator, -1, "reg ptr unref from reload config"));
  27513. }
  27514. if (iterator->dnsmgr) {
  27515. ast_dnsmgr_release(iterator->dnsmgr);
  27516. iterator->dnsmgr = NULL;
  27517. ao2_t_ref(iterator, -1, "reg ptr unref from dnsmgr");
  27518. }
  27519. ao2_unlock(iterator);
  27520. ao2_t_ref(iterator, -1, "cleanup_all_regs iter");
  27521. }
  27522. ao2_iterator_destroy(&iter);
  27523. }
  27524. /*! \brief Re-read SIP.conf config file
  27525. \note This function reloads all config data, except for
  27526. active peers (with registrations). They will only
  27527. change configuration data at restart, not at reload.
  27528. SIP debug and recordhistory state will not change
  27529. */
  27530. static int reload_config(enum channelreloadreason reason)
  27531. {
  27532. struct ast_config *cfg, *ucfg;
  27533. struct ast_variable *v;
  27534. struct sip_peer *peer;
  27535. char *cat, *stringp, *context, *oldregcontext;
  27536. char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
  27537. struct ast_flags mask[3] = {{0}};
  27538. struct ast_flags setflags[3] = {{0}};
  27539. 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 };
  27540. int auto_sip_domains = FALSE;
  27541. struct ast_sockaddr old_bindaddr = bindaddr;
  27542. int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
  27543. int subscribe_network_change = 1;
  27544. time_t run_start, run_end;
  27545. int bindport = 0;
  27546. int acl_change_subscription_needed = 0;
  27547. int min_subexpiry_set = 0, max_subexpiry_set = 0;
  27548. run_start = time(0);
  27549. ast_unload_realtime("sipregs");
  27550. ast_unload_realtime("sippeers");
  27551. cfg = ast_config_load(config, config_flags);
  27552. /* We *must* have a config file otherwise stop immediately */
  27553. if (!cfg) {
  27554. ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
  27555. return -1;
  27556. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  27557. ucfg = ast_config_load("users.conf", config_flags);
  27558. if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
  27559. return 1;
  27560. } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
  27561. ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
  27562. return 1;
  27563. }
  27564. /* Must reread both files, because one changed */
  27565. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  27566. if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
  27567. ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
  27568. ast_config_destroy(ucfg);
  27569. return 1;
  27570. }
  27571. if (!cfg) {
  27572. /* should have been able to reload here */
  27573. ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
  27574. return -1;
  27575. }
  27576. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  27577. ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
  27578. return 1;
  27579. } else {
  27580. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  27581. if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
  27582. ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
  27583. ast_config_destroy(cfg);
  27584. return 1;
  27585. }
  27586. }
  27587. sip_cfg.contact_acl = ast_free_acl_list(sip_cfg.contact_acl);
  27588. default_tls_cfg.enabled = FALSE; /* Default: Disable TLS */
  27589. if (reason != CHANNEL_MODULE_LOAD) {
  27590. ast_debug(4, "--------------- SIP reload started\n");
  27591. clear_sip_domains();
  27592. ast_mutex_lock(&authl_lock);
  27593. if (authl) {
  27594. ao2_t_ref(authl, -1, "Removing old global authentication");
  27595. authl = NULL;
  27596. }
  27597. ast_mutex_unlock(&authl_lock);
  27598. /* Then, actually destroy users and registry */
  27599. cleanup_all_regs();
  27600. ast_debug(4, "--------------- Done destroying registry list\n");
  27601. ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
  27602. }
  27603. /* Reset certificate handling for TLS sessions */
  27604. if (reason != CHANNEL_MODULE_LOAD) {
  27605. ast_free(default_tls_cfg.certfile);
  27606. ast_free(default_tls_cfg.pvtfile);
  27607. ast_free(default_tls_cfg.cipher);
  27608. ast_free(default_tls_cfg.cafile);
  27609. ast_free(default_tls_cfg.capath);
  27610. }
  27611. default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
  27612. default_tls_cfg.pvtfile = ast_strdup("");
  27613. default_tls_cfg.cipher = ast_strdup("");
  27614. default_tls_cfg.cafile = ast_strdup("");
  27615. default_tls_cfg.capath = ast_strdup("");
  27616. /* Initialize copy of current sip_cfg.regcontext for later use in removing stale contexts */
  27617. ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
  27618. oldregcontext = oldcontexts;
  27619. /* Clear all flags before setting default values */
  27620. /* Preserve debugging settings for console */
  27621. sipdebug &= sip_debug_console;
  27622. ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
  27623. ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
  27624. ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
  27625. /* Reset IP addresses */
  27626. ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
  27627. memset(&internip, 0, sizeof(internip));
  27628. /* Free memory for local network address mask */
  27629. ast_free_ha(localaddr);
  27630. memset(&localaddr, 0, sizeof(localaddr));
  27631. memset(&externaddr, 0, sizeof(externaddr));
  27632. memset(&media_address, 0, sizeof(media_address));
  27633. memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
  27634. sip_cfg.outboundproxy.force = FALSE; /*!< Don't force proxy usage, use route: headers */
  27635. default_transports = AST_TRANSPORT_UDP;
  27636. default_primary_transport = AST_TRANSPORT_UDP;
  27637. ourport_tcp = STANDARD_SIP_PORT;
  27638. ourport_tls = STANDARD_TLS_PORT;
  27639. externtcpport = STANDARD_SIP_PORT;
  27640. externtlsport = STANDARD_TLS_PORT;
  27641. sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
  27642. global_tos_sip = DEFAULT_TOS_SIP;
  27643. global_tos_audio = DEFAULT_TOS_AUDIO;
  27644. global_tos_video = DEFAULT_TOS_VIDEO;
  27645. global_tos_text = DEFAULT_TOS_TEXT;
  27646. global_cos_sip = DEFAULT_COS_SIP;
  27647. global_cos_audio = DEFAULT_COS_AUDIO;
  27648. global_cos_video = DEFAULT_COS_VIDEO;
  27649. global_cos_text = DEFAULT_COS_TEXT;
  27650. externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
  27651. externexpire = 0; /* Expiration for DNS re-issuing */
  27652. externrefresh = 10;
  27653. /* Reset channel settings to default before re-configuring */
  27654. sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
  27655. sip_cfg.regcontext[0] = '\0';
  27656. sip_set_default_format_capabilities(sip_cfg.caps);
  27657. sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
  27658. sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
  27659. sip_cfg.send_diversion = DEFAULT_SEND_DIVERSION;
  27660. sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
  27661. sip_cfg.notifycid = DEFAULT_NOTIFYCID;
  27662. sip_cfg.notifyhold = FALSE; /*!< Keep track of hold status for a peer */
  27663. sip_cfg.directrtpsetup = FALSE; /* Experimental feature, disabled by default */
  27664. sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
  27665. sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
  27666. sip_cfg.auth_message_requests = DEFAULT_AUTH_MESSAGE;
  27667. sip_cfg.messagecontext[0] = '\0';
  27668. sip_cfg.accept_outofcall_message = DEFAULT_ACCEPT_OUTOFCALL_MESSAGE;
  27669. sip_cfg.allowsubscribe = FALSE;
  27670. sip_cfg.disallowed_methods = SIP_UNKNOWN;
  27671. sip_cfg.contact_acl = NULL; /* Reset the contact ACL */
  27672. snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
  27673. snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
  27674. snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
  27675. global_prematuremediafilter = TRUE;
  27676. ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
  27677. ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
  27678. sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
  27679. ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
  27680. ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
  27681. sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
  27682. global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
  27683. global_regattempts_max = 0;
  27684. global_reg_retry_403 = 0;
  27685. sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
  27686. sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
  27687. global_autoframing = 0;
  27688. sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
  27689. global_callcounter = DEFAULT_CALLCOUNTER;
  27690. global_match_auth_username = FALSE; /*!< Match auth username if available instead of From: Default off. */
  27691. global_rtptimeout = 0;
  27692. global_rtpholdtimeout = 0;
  27693. global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
  27694. sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
  27695. sip_cfg.rtautoclear = 120;
  27696. ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for all devices: TRUE */
  27697. ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES); /* Default for all devices: Yes */
  27698. sip_cfg.peer_rtupdate = TRUE;
  27699. global_dynamic_exclude_static = 0; /* Exclude static peers */
  27700. sip_cfg.tcp_enabled = FALSE;
  27701. /* Session-Timers */
  27702. global_st_mode = SESSION_TIMER_MODE_ACCEPT;
  27703. global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
  27704. global_min_se = DEFAULT_MIN_SE;
  27705. global_max_se = DEFAULT_MAX_SE;
  27706. /* Peer poking settings */
  27707. global_qualify_gap = DEFAULT_QUALIFY_GAP;
  27708. global_qualify_peers = DEFAULT_QUALIFY_PEERS;
  27709. /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
  27710. ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
  27711. ast_copy_string(sip_cfg.default_record_on_feature, DEFAULT_RECORD_FEATURE, sizeof(sip_cfg.default_record_on_feature));
  27712. ast_copy_string(sip_cfg.default_record_off_feature, DEFAULT_RECORD_FEATURE, sizeof(sip_cfg.default_record_off_feature));
  27713. sip_cfg.default_subscribecontext[0] = '\0';
  27714. sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
  27715. default_language[0] = '\0';
  27716. default_fromdomain[0] = '\0';
  27717. default_fromdomainport = 0;
  27718. default_qualify = DEFAULT_QUALIFY;
  27719. default_keepalive = DEFAULT_KEEPALIVE;
  27720. default_zone[0] = '\0';
  27721. default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
  27722. ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
  27723. ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
  27724. ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
  27725. ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
  27726. ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA); /*!< Allow re-invites */
  27727. ast_set_flag(&global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT); /*!< Default to nat=auto_force_rport */
  27728. ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
  27729. ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
  27730. /* Debugging settings, always default to off */
  27731. dumphistory = FALSE;
  27732. recordhistory = FALSE;
  27733. sipdebug &= ~sip_debug_config;
  27734. /* Misc settings for the channel */
  27735. global_relaxdtmf = FALSE;
  27736. global_authfailureevents = FALSE;
  27737. global_t1 = DEFAULT_TIMER_T1;
  27738. global_timer_b = 64 * DEFAULT_TIMER_T1;
  27739. global_t1min = DEFAULT_T1MIN;
  27740. global_qualifyfreq = DEFAULT_QUALIFYFREQ;
  27741. global_t38_maxdatagram = -1;
  27742. global_shrinkcallerid = 1;
  27743. global_refer_addheaders = TRUE;
  27744. authlimit = DEFAULT_AUTHLIMIT;
  27745. authtimeout = DEFAULT_AUTHTIMEOUT;
  27746. global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
  27747. min_expiry = DEFAULT_MIN_EXPIRY;
  27748. max_expiry = DEFAULT_MAX_EXPIRY;
  27749. default_expiry = DEFAULT_DEFAULT_EXPIRY;
  27750. sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
  27751. /* Copy the default jb config over global_jbconf */
  27752. memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
  27753. ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
  27754. ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
  27755. ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
  27756. ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
  27757. /* Read the [general] config section of sip.conf (or from realtime config) */
  27758. for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
  27759. if (handle_common_options(&setflags[0], &mask[0], v)) {
  27760. continue;
  27761. }
  27762. if (handle_t38_options(&setflags[0], &mask[0], v, &global_t38_maxdatagram)) {
  27763. continue;
  27764. }
  27765. /* handle jb conf */
  27766. if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
  27767. continue;
  27768. }
  27769. /* handle tls conf, don't allow setting of tlsverifyclient as it isn't supported by chan_sip */
  27770. if (!strcasecmp(v->name, "tlsverifyclient")) {
  27771. ast_log(LOG_WARNING, "Ignoring unsupported option 'tlsverifyclient'\n");
  27772. continue;
  27773. } else if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
  27774. continue;
  27775. }
  27776. if (!strcasecmp(v->name, "context")) {
  27777. ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
  27778. } else if (!strcasecmp(v->name, "recordonfeature")) {
  27779. ast_copy_string(sip_cfg.default_record_on_feature, v->value, sizeof(sip_cfg.default_record_on_feature));
  27780. } else if (!strcasecmp(v->name, "recordofffeature")) {
  27781. ast_copy_string(sip_cfg.default_record_off_feature, v->value, sizeof(sip_cfg.default_record_off_feature));
  27782. } else if (!strcasecmp(v->name, "subscribecontext")) {
  27783. ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
  27784. } else if (!strcasecmp(v->name, "callcounter")) {
  27785. global_callcounter = ast_true(v->value) ? 1 : 0;
  27786. } else if (!strcasecmp(v->name, "allowguest")) {
  27787. sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
  27788. } else if (!strcasecmp(v->name, "realm")) {
  27789. ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
  27790. } else if (!strcasecmp(v->name, "domainsasrealm")) {
  27791. sip_cfg.domainsasrealm = ast_true(v->value);
  27792. } else if (!strcasecmp(v->name, "useragent")) {
  27793. ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
  27794. ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
  27795. } else if (!strcasecmp(v->name, "sdpsession")) {
  27796. ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
  27797. } else if (!strcasecmp(v->name, "sdpowner")) {
  27798. /* Field cannot contain spaces */
  27799. if (!strstr(v->value, " ")) {
  27800. ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
  27801. } else {
  27802. ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
  27803. }
  27804. } else if (!strcasecmp(v->name, "allowtransfer")) {
  27805. sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
  27806. } else if (!strcasecmp(v->name, "rtcachefriends")) {
  27807. ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
  27808. } else if (!strcasecmp(v->name, "rtsavesysname")) {
  27809. sip_cfg.rtsave_sysname = ast_true(v->value);
  27810. } else if (!strcasecmp(v->name, "rtsavepath")) {
  27811. sip_cfg.rtsave_path = ast_true(v->value);
  27812. } else if (!strcasecmp(v->name, "rtupdate")) {
  27813. sip_cfg.peer_rtupdate = ast_true(v->value);
  27814. } else if (!strcasecmp(v->name, "ignoreregexpire")) {
  27815. sip_cfg.ignore_regexpire = ast_true(v->value);
  27816. } else if (!strcasecmp(v->name, "timert1")) {
  27817. /* Defaults to 500ms, but RFC 3261 states that it is recommended
  27818. * for the value to be set higher, though a lower value is only
  27819. * allowed on private networks unconnected to the Internet. */
  27820. global_t1 = atoi(v->value);
  27821. } else if (!strcasecmp(v->name, "timerb")) {
  27822. int tmp = atoi(v->value);
  27823. if (tmp < 500) {
  27824. global_timer_b = global_t1 * 64;
  27825. ast_log(LOG_WARNING, "Invalid value for timerb ('%s'). Setting to default ('%d').\n", v->value, global_timer_b);
  27826. }
  27827. timerb_set = 1;
  27828. } else if (!strcasecmp(v->name, "t1min")) {
  27829. global_t1min = atoi(v->value);
  27830. } else if (!strcasecmp(v->name, "transport")) {
  27831. char *val = ast_strdupa(v->value);
  27832. char *trans;
  27833. default_transports = default_primary_transport = 0;
  27834. while ((trans = strsep(&val, ","))) {
  27835. trans = ast_skip_blanks(trans);
  27836. if (!strncasecmp(trans, "udp", 3)) {
  27837. default_transports |= AST_TRANSPORT_UDP;
  27838. } else if (!strncasecmp(trans, "tcp", 3)) {
  27839. default_transports |= AST_TRANSPORT_TCP;
  27840. } else if (!strncasecmp(trans, "tls", 3)) {
  27841. default_transports |= AST_TRANSPORT_TLS;
  27842. } else if (!strncasecmp(trans, "wss", 3)) {
  27843. default_transports |= AST_TRANSPORT_WSS;
  27844. } else if (!strncasecmp(trans, "ws", 2)) {
  27845. default_transports |= AST_TRANSPORT_WS;
  27846. } else {
  27847. ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
  27848. }
  27849. if (default_primary_transport == 0) {
  27850. default_primary_transport = default_transports;
  27851. }
  27852. }
  27853. } else if (!strcasecmp(v->name, "tcpenable")) {
  27854. if (!ast_false(v->value)) {
  27855. ast_debug(2, "Enabling TCP socket for listening\n");
  27856. sip_cfg.tcp_enabled = TRUE;
  27857. }
  27858. } else if (!strcasecmp(v->name, "tcpbindaddr")) {
  27859. if (ast_parse_arg(v->value, PARSE_ADDR,
  27860. &sip_tcp_desc.local_address)) {
  27861. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
  27862. v->name, v->value, v->lineno, config);
  27863. }
  27864. ast_debug(2, "Setting TCP socket address to %s\n",
  27865. ast_sockaddr_stringify(&sip_tcp_desc.local_address));
  27866. } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
  27867. global_dynamic_exclude_static = ast_true(v->value);
  27868. } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny") || !strcasecmp(v->name, "contactacl")) {
  27869. int ha_error = 0;
  27870. ast_append_acl(v->name + 7, v->value, &sip_cfg.contact_acl, &ha_error, &acl_change_subscription_needed);
  27871. if (ha_error) {
  27872. ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  27873. }
  27874. } else if (!strcasecmp(v->name, "rtautoclear")) {
  27875. int i = atoi(v->value);
  27876. if (i > 0) {
  27877. sip_cfg.rtautoclear = i;
  27878. } else {
  27879. i = 0;
  27880. }
  27881. ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
  27882. } else if (!strcasecmp(v->name, "usereqphone")) {
  27883. ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
  27884. } else if (!strcasecmp(v->name, "prematuremedia")) {
  27885. global_prematuremediafilter = ast_true(v->value);
  27886. } else if (!strcasecmp(v->name, "relaxdtmf")) {
  27887. global_relaxdtmf = ast_true(v->value);
  27888. } else if (!strcasecmp(v->name, "vmexten")) {
  27889. ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
  27890. } else if (!strcasecmp(v->name, "rtptimeout")) {
  27891. if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
  27892. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  27893. global_rtptimeout = 0;
  27894. }
  27895. } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
  27896. if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
  27897. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  27898. global_rtpholdtimeout = 0;
  27899. }
  27900. } else if (!strcasecmp(v->name, "rtpkeepalive")) {
  27901. if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
  27902. ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
  27903. global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
  27904. }
  27905. } else if (!strcasecmp(v->name, "compactheaders")) {
  27906. sip_cfg.compactheaders = ast_true(v->value);
  27907. } else if (!strcasecmp(v->name, "notifymimetype")) {
  27908. ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
  27909. } else if (!strcasecmp(v->name, "directrtpsetup")) {
  27910. sip_cfg.directrtpsetup = ast_true(v->value);
  27911. } else if (!strcasecmp(v->name, "notifyringing")) {
  27912. sip_cfg.notifyringing = ast_true(v->value);
  27913. } else if (!strcasecmp(v->name, "notifyhold")) {
  27914. sip_cfg.notifyhold = ast_true(v->value);
  27915. } else if (!strcasecmp(v->name, "notifycid")) {
  27916. if (!strcasecmp(v->value, "ignore-context")) {
  27917. sip_cfg.notifycid = IGNORE_CONTEXT;
  27918. } else {
  27919. sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
  27920. }
  27921. } else if (!strcasecmp(v->name, "alwaysauthreject")) {
  27922. sip_cfg.alwaysauthreject = ast_true(v->value);
  27923. } else if (!strcasecmp(v->name, "auth_options_requests")) {
  27924. if (ast_true(v->value)) {
  27925. sip_cfg.auth_options_requests = 1;
  27926. }
  27927. } else if (!strcasecmp(v->name, "auth_message_requests")) {
  27928. sip_cfg.auth_message_requests = ast_true(v->value) ? 1 : 0;
  27929. } else if (!strcasecmp(v->name, "accept_outofcall_message")) {
  27930. sip_cfg.accept_outofcall_message = ast_true(v->value) ? 1 : 0;
  27931. } else if (!strcasecmp(v->name, "outofcall_message_context")) {
  27932. ast_copy_string(sip_cfg.messagecontext, v->value, sizeof(sip_cfg.messagecontext));
  27933. } else if (!strcasecmp(v->name, "mohinterpret")) {
  27934. ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
  27935. } else if (!strcasecmp(v->name, "mohsuggest")) {
  27936. ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
  27937. } else if (!strcasecmp(v->name, "tonezone")) {
  27938. struct ast_tone_zone *new_zone;
  27939. if (!(new_zone = ast_get_indication_zone(v->value))) {
  27940. 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);
  27941. } else {
  27942. ast_tone_zone_unref(new_zone);
  27943. ast_copy_string(default_zone, v->value, sizeof(default_zone));
  27944. }
  27945. } else if (!strcasecmp(v->name, "language")) {
  27946. ast_copy_string(default_language, v->value, sizeof(default_language));
  27947. } else if (!strcasecmp(v->name, "regcontext")) {
  27948. ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
  27949. stringp = newcontexts;
  27950. /* Let's remove any contexts that are no longer defined in regcontext */
  27951. cleanup_stale_contexts(stringp, oldregcontext);
  27952. /* Create contexts if they don't exist already */
  27953. while ((context = strsep(&stringp, "&"))) {
  27954. ast_copy_string(used_context, context, sizeof(used_context));
  27955. ast_context_find_or_create(NULL, NULL, context, "SIP");
  27956. }
  27957. ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
  27958. } else if (!strcasecmp(v->name, "regextenonqualify")) {
  27959. sip_cfg.regextenonqualify = ast_true(v->value);
  27960. } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
  27961. sip_cfg.legacy_useroption_parsing = ast_true(v->value);
  27962. } else if (!strcasecmp(v->name, "send_diversion")) {
  27963. sip_cfg.send_diversion = ast_true(v->value);
  27964. } else if (!strcasecmp(v->name, "callerid")) {
  27965. ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
  27966. } else if (!strcasecmp(v->name, "mwi_from")) {
  27967. ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
  27968. } else if (!strcasecmp(v->name, "fromdomain")) {
  27969. char *fromdomainport;
  27970. ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
  27971. if ((fromdomainport = strchr(default_fromdomain, ':'))) {
  27972. *fromdomainport++ = '\0';
  27973. if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
  27974. ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
  27975. }
  27976. } else {
  27977. default_fromdomainport = STANDARD_SIP_PORT;
  27978. }
  27979. } else if (!strcasecmp(v->name, "outboundproxy")) {
  27980. struct sip_proxy *proxy;
  27981. if (ast_strlen_zero(v->value)) {
  27982. ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
  27983. continue;
  27984. }
  27985. proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
  27986. if (!proxy) {
  27987. ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
  27988. continue;
  27989. }
  27990. } else if (!strcasecmp(v->name, "autocreatepeer")) {
  27991. if (!strcasecmp(v->value, "persist")) {
  27992. sip_cfg.autocreatepeer = AUTOPEERS_PERSIST;
  27993. } else {
  27994. sip_cfg.autocreatepeer = ast_true(v->value) ? AUTOPEERS_VOLATILE : AUTOPEERS_DISABLED;
  27995. }
  27996. } else if (!strcasecmp(v->name, "match_auth_username")) {
  27997. global_match_auth_username = ast_true(v->value);
  27998. } else if (!strcasecmp(v->name, "srvlookup")) {
  27999. sip_cfg.srvlookup = ast_true(v->value);
  28000. } else if (!strcasecmp(v->name, "pedantic")) {
  28001. sip_cfg.pedanticsipchecking = ast_true(v->value);
  28002. } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
  28003. max_expiry = atoi(v->value);
  28004. if (max_expiry < 1) {
  28005. max_expiry = DEFAULT_MAX_EXPIRY;
  28006. }
  28007. } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
  28008. min_expiry = atoi(v->value);
  28009. if (min_expiry < 1) {
  28010. min_expiry = DEFAULT_MIN_EXPIRY;
  28011. }
  28012. } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
  28013. default_expiry = atoi(v->value);
  28014. if (default_expiry < 1) {
  28015. default_expiry = DEFAULT_DEFAULT_EXPIRY;
  28016. }
  28017. } else if (!strcasecmp(v->name, "submaxexpirey") || !strcasecmp(v->name, "submaxexpiry")) {
  28018. max_subexpiry = atoi(v->value);
  28019. if (max_subexpiry < 1) {
  28020. max_subexpiry = DEFAULT_MAX_EXPIRY;
  28021. }
  28022. max_subexpiry_set = 1;
  28023. } else if (!strcasecmp(v->name, "subminexpirey") || !strcasecmp(v->name, "subminexpiry")) {
  28024. min_subexpiry = atoi(v->value);
  28025. if (min_subexpiry < 1) {
  28026. min_subexpiry = DEFAULT_MIN_EXPIRY;
  28027. }
  28028. min_subexpiry_set = 1;
  28029. } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
  28030. mwi_expiry = atoi(v->value);
  28031. if (mwi_expiry < 1) {
  28032. mwi_expiry = DEFAULT_MWI_EXPIRY;
  28033. }
  28034. } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
  28035. if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
  28036. &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
  28037. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
  28038. v->name, v->value, v->lineno, config);
  28039. }
  28040. } else if (!strcasecmp(v->name, "tcpauthlimit")) {
  28041. if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
  28042. &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
  28043. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
  28044. v->name, v->value, v->lineno, config);
  28045. }
  28046. } else if (!strcasecmp(v->name, "sipdebug")) {
  28047. if (ast_true(v->value))
  28048. sipdebug |= sip_debug_config;
  28049. } else if (!strcasecmp(v->name, "dumphistory")) {
  28050. dumphistory = ast_true(v->value);
  28051. } else if (!strcasecmp(v->name, "recordhistory")) {
  28052. recordhistory = ast_true(v->value);
  28053. } else if (!strcasecmp(v->name, "registertimeout")) {
  28054. global_reg_timeout = atoi(v->value);
  28055. if (global_reg_timeout < 1) {
  28056. global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
  28057. }
  28058. } else if (!strcasecmp(v->name, "registerattempts")) {
  28059. global_regattempts_max = atoi(v->value);
  28060. } else if (!strcasecmp(v->name, "register_retry_403")) {
  28061. global_reg_retry_403 = ast_true(v->value);
  28062. } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
  28063. if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
  28064. ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
  28065. }
  28066. } else if (!strcasecmp(v->name, "localnet")) {
  28067. struct ast_ha *na;
  28068. int ha_error = 0;
  28069. if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
  28070. ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
  28071. } else {
  28072. localaddr = na;
  28073. }
  28074. if (ha_error) {
  28075. ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
  28076. }
  28077. } else if (!strcasecmp(v->name, "media_address")) {
  28078. if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
  28079. ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
  28080. } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
  28081. if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
  28082. ast_log(LOG_WARNING,
  28083. "Invalid address for externaddr keyword: %s\n",
  28084. v->value);
  28085. }
  28086. externexpire = 0;
  28087. } else if (!strcasecmp(v->name, "externhost")) {
  28088. ast_copy_string(externhost, v->value, sizeof(externhost));
  28089. if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
  28090. ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
  28091. }
  28092. externexpire = time(NULL);
  28093. } else if (!strcasecmp(v->name, "externrefresh")) {
  28094. if (sscanf(v->value, "%30d", &externrefresh) != 1) {
  28095. ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
  28096. externrefresh = 10;
  28097. }
  28098. } else if (!strcasecmp(v->name, "externtcpport")) {
  28099. if (!(externtcpport = port_str2int(v->value, 0))) {
  28100. ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
  28101. externtcpport = 0;
  28102. }
  28103. } else if (!strcasecmp(v->name, "externtlsport")) {
  28104. if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
  28105. ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
  28106. }
  28107. } else if (!strcasecmp(v->name, "allow")) {
  28108. int error = ast_format_cap_update_by_allow_disallow(sip_cfg.caps, v->value, TRUE);
  28109. if (error) {
  28110. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  28111. }
  28112. } else if (!strcasecmp(v->name, "disallow")) {
  28113. int error = ast_format_cap_update_by_allow_disallow(sip_cfg.caps, v->value, FALSE);
  28114. if (error) {
  28115. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  28116. }
  28117. } else if (!strcasecmp(v->name, "preferred_codec_only")) {
  28118. ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
  28119. } else if (!strcasecmp(v->name, "autoframing")) {
  28120. global_autoframing = ast_true(v->value);
  28121. } else if (!strcasecmp(v->name, "allowexternaldomains")) {
  28122. sip_cfg.allow_external_domains = ast_true(v->value);
  28123. } else if (!strcasecmp(v->name, "autodomain")) {
  28124. auto_sip_domains = ast_true(v->value);
  28125. } else if (!strcasecmp(v->name, "domain")) {
  28126. char *domain = ast_strdupa(v->value);
  28127. char *cntx = strchr(domain, ',');
  28128. if (cntx) {
  28129. *cntx++ = '\0';
  28130. }
  28131. if (ast_strlen_zero(cntx)) {
  28132. ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
  28133. }
  28134. if (ast_strlen_zero(domain)) {
  28135. ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
  28136. } else {
  28137. add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
  28138. }
  28139. } else if (!strcasecmp(v->name, "register")) {
  28140. if (sip_register(v->value, v->lineno) == 0) {
  28141. registry_count++;
  28142. }
  28143. } else if (!strcasecmp(v->name, "mwi")) {
  28144. sip_subscribe_mwi(v->value, v->lineno);
  28145. } else if (!strcasecmp(v->name, "tos_sip")) {
  28146. if (ast_str2tos(v->value, &global_tos_sip)) {
  28147. ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
  28148. }
  28149. } else if (!strcasecmp(v->name, "tos_audio")) {
  28150. if (ast_str2tos(v->value, &global_tos_audio)) {
  28151. ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
  28152. }
  28153. } else if (!strcasecmp(v->name, "tos_video")) {
  28154. if (ast_str2tos(v->value, &global_tos_video)) {
  28155. ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
  28156. }
  28157. } else if (!strcasecmp(v->name, "tos_text")) {
  28158. if (ast_str2tos(v->value, &global_tos_text)) {
  28159. ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
  28160. }
  28161. } else if (!strcasecmp(v->name, "cos_sip")) {
  28162. if (ast_str2cos(v->value, &global_cos_sip)) {
  28163. ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
  28164. }
  28165. } else if (!strcasecmp(v->name, "cos_audio")) {
  28166. if (ast_str2cos(v->value, &global_cos_audio)) {
  28167. ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
  28168. }
  28169. } else if (!strcasecmp(v->name, "cos_video")) {
  28170. if (ast_str2cos(v->value, &global_cos_video)) {
  28171. ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
  28172. }
  28173. } else if (!strcasecmp(v->name, "cos_text")) {
  28174. if (ast_str2cos(v->value, &global_cos_text)) {
  28175. ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
  28176. }
  28177. } else if (!strcasecmp(v->name, "bindport")) {
  28178. if (sscanf(v->value, "%5d", &bindport) != 1) {
  28179. ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
  28180. }
  28181. } else if (!strcasecmp(v->name, "qualify")) {
  28182. if (!strcasecmp(v->value, "no")) {
  28183. default_qualify = 0;
  28184. } else if (!strcasecmp(v->value, "yes")) {
  28185. default_qualify = DEFAULT_MAXMS;
  28186. } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
  28187. ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
  28188. default_qualify = 0;
  28189. }
  28190. } else if (!strcasecmp(v->name, "keepalive")) {
  28191. if (!strcasecmp(v->value, "no")) {
  28192. default_keepalive = 0;
  28193. } else if (!strcasecmp(v->value, "yes")) {
  28194. default_keepalive = DEFAULT_KEEPALIVE_INTERVAL;
  28195. } else if (sscanf(v->value, "%30d", &default_keepalive) != 1) {
  28196. 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);
  28197. default_keepalive = 0;
  28198. }
  28199. } else if (!strcasecmp(v->name, "qualifyfreq")) {
  28200. int i;
  28201. if (sscanf(v->value, "%30d", &i) == 1) {
  28202. global_qualifyfreq = i * 1000;
  28203. } else {
  28204. ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
  28205. global_qualifyfreq = DEFAULT_QUALIFYFREQ;
  28206. }
  28207. } else if (!strcasecmp(v->name, "authfailureevents")) {
  28208. global_authfailureevents = ast_true(v->value);
  28209. } else if (!strcasecmp(v->name, "maxcallbitrate")) {
  28210. default_maxcallbitrate = atoi(v->value);
  28211. if (default_maxcallbitrate < 0) {
  28212. default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
  28213. }
  28214. } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
  28215. sip_cfg.matchexternaddrlocally = ast_true(v->value);
  28216. } else if (!strcasecmp(v->name, "session-timers")) {
  28217. int i = (int) str2stmode(v->value);
  28218. if (i < 0) {
  28219. ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
  28220. global_st_mode = SESSION_TIMER_MODE_ACCEPT;
  28221. } else {
  28222. global_st_mode = i;
  28223. }
  28224. } else if (!strcasecmp(v->name, "session-expires")) {
  28225. if (sscanf(v->value, "%30d", &global_max_se) != 1) {
  28226. ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
  28227. global_max_se = DEFAULT_MAX_SE;
  28228. }
  28229. } else if (!strcasecmp(v->name, "session-minse")) {
  28230. if (sscanf(v->value, "%30d", &global_min_se) != 1) {
  28231. ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
  28232. global_min_se = DEFAULT_MIN_SE;
  28233. }
  28234. if (global_min_se < DEFAULT_MIN_SE) {
  28235. 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);
  28236. global_min_se = DEFAULT_MIN_SE;
  28237. }
  28238. } else if (!strcasecmp(v->name, "session-refresher")) {
  28239. int i = (int) str2strefresherparam(v->value);
  28240. if (i < 0) {
  28241. ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
  28242. global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
  28243. } else {
  28244. global_st_refresher = i;
  28245. }
  28246. } else if (!strcasecmp(v->name, "storesipcause")) {
  28247. global_store_sip_cause = ast_true(v->value);
  28248. if (global_store_sip_cause) {
  28249. ast_log(LOG_WARNING, "Usage of SIP_CAUSE is deprecated. Please use HANGUPCAUSE instead.\n");
  28250. }
  28251. } else if (!strcasecmp(v->name, "qualifygap")) {
  28252. if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
  28253. ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
  28254. global_qualify_gap = DEFAULT_QUALIFY_GAP;
  28255. }
  28256. } else if (!strcasecmp(v->name, "qualifypeers")) {
  28257. if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
  28258. ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
  28259. global_qualify_peers = DEFAULT_QUALIFY_PEERS;
  28260. }
  28261. } else if (!strcasecmp(v->name, "disallowed_methods")) {
  28262. char *disallow = ast_strdupa(v->value);
  28263. mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
  28264. } else if (!strcasecmp(v->name, "shrinkcallerid")) {
  28265. if (ast_true(v->value)) {
  28266. global_shrinkcallerid = 1;
  28267. } else if (ast_false(v->value)) {
  28268. global_shrinkcallerid = 0;
  28269. } else {
  28270. ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
  28271. }
  28272. } else if (!strcasecmp(v->name, "use_q850_reason")) {
  28273. ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
  28274. } else if (!strcasecmp(v->name, "maxforwards")) {
  28275. if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
  28276. || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
  28277. ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
  28278. sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
  28279. }
  28280. } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
  28281. if (ast_true(v->value)) {
  28282. subscribe_network_change = 1;
  28283. } else if (ast_false(v->value)) {
  28284. subscribe_network_change = 0;
  28285. } else {
  28286. ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
  28287. }
  28288. } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
  28289. ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
  28290. } else if (!strcasecmp(v->name, "icesupport")) {
  28291. ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_ICE_SUPPORT);
  28292. } else if (!strcasecmp(v->name, "discard_remote_hold_retrieval")) {
  28293. ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_DISCARD_REMOTE_HOLD_RETRIEVAL);
  28294. } else if (!strcasecmp(v->name, "parkinglot")) {
  28295. ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
  28296. } else if (!strcasecmp(v->name, "refer_addheaders")) {
  28297. global_refer_addheaders = ast_true(v->value);
  28298. } else if (!strcasecmp(v->name, "websocket_write_timeout")) {
  28299. if (sscanf(v->value, "%30d", &sip_cfg.websocket_write_timeout) != 1
  28300. || sip_cfg.websocket_write_timeout < 0) {
  28301. 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);
  28302. sip_cfg.websocket_write_timeout = AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT;
  28303. }
  28304. }
  28305. }
  28306. /* Override global defaults if setting found in general section */
  28307. ast_copy_flags(&global_flags[0], &setflags[0], mask[0].flags);
  28308. ast_copy_flags(&global_flags[1], &setflags[1], mask[1].flags);
  28309. ast_copy_flags(&global_flags[2], &setflags[2], mask[2].flags);
  28310. /* For backwards compatibility the corresponding registration timer value is used if subscription timer value isn't set by configuration */
  28311. if (!min_subexpiry_set) {
  28312. min_subexpiry = min_expiry;
  28313. }
  28314. if (!max_subexpiry_set) {
  28315. max_subexpiry = max_expiry;
  28316. }
  28317. if (reason != CHANNEL_MODULE_LOAD && sip_cfg.autocreatepeer != AUTOPEERS_PERSIST) {
  28318. ao2_t_callback(peers, OBJ_NODATA, peer_markall_autopeers_func, NULL, "callback to mark autopeers for destruction");
  28319. }
  28320. if (subscribe_network_change) {
  28321. network_change_stasis_subscribe();
  28322. } else {
  28323. network_change_stasis_unsubscribe();
  28324. }
  28325. if (global_t1 < global_t1min) {
  28326. ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d). Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
  28327. global_t1 = global_t1min;
  28328. }
  28329. if (global_timer_b < global_t1 * 64) {
  28330. if (timerb_set && timert1_set) {
  28331. 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);
  28332. } else if (timerb_set) {
  28333. if ((global_t1 = global_timer_b / 64) < global_t1min) {
  28334. 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);
  28335. global_t1 = global_t1min;
  28336. global_timer_b = global_t1 * 64;
  28337. }
  28338. } else {
  28339. global_timer_b = global_t1 * 64;
  28340. }
  28341. }
  28342. if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
  28343. ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
  28344. sip_cfg.allow_external_domains = 1;
  28345. }
  28346. /* If not or badly configured, set default transports */
  28347. if (!sip_cfg.tcp_enabled && (default_transports & AST_TRANSPORT_TCP)) {
  28348. ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
  28349. default_primary_transport &= ~AST_TRANSPORT_TCP;
  28350. default_transports &= ~AST_TRANSPORT_TCP;
  28351. }
  28352. if (!default_tls_cfg.enabled && (default_transports & AST_TRANSPORT_TLS)) {
  28353. ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
  28354. default_primary_transport &= ~AST_TRANSPORT_TLS;
  28355. default_transports &= ~AST_TRANSPORT_TLS;
  28356. }
  28357. if (!default_transports) {
  28358. ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
  28359. default_transports = default_primary_transport = AST_TRANSPORT_UDP;
  28360. } else if (!default_primary_transport) {
  28361. ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
  28362. default_primary_transport = AST_TRANSPORT_UDP;
  28363. }
  28364. /* Build list of authentication to various SIP realms, i.e. service providers */
  28365. for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
  28366. /* Format for authentication is auth = username:password@realm */
  28367. if (!strcasecmp(v->name, "auth")) {
  28368. add_realm_authentication(&authl, v->value, v->lineno);
  28369. }
  28370. }
  28371. if (bindport) {
  28372. if (ast_sockaddr_port(&bindaddr)) {
  28373. ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
  28374. "Using %d.\n", bindport);
  28375. }
  28376. ast_sockaddr_set_port(&bindaddr, bindport);
  28377. }
  28378. if (!ast_sockaddr_port(&bindaddr)) {
  28379. ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
  28380. }
  28381. /* Set UDP address and open socket */
  28382. ast_sockaddr_copy(&internip, &bindaddr);
  28383. if (ast_find_ourip(&internip, &bindaddr, 0)) {
  28384. ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
  28385. ast_config_destroy(cfg);
  28386. return 0;
  28387. }
  28388. ast_mutex_lock(&netlock);
  28389. if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
  28390. close(sipsock);
  28391. sipsock = -1;
  28392. }
  28393. if (sipsock < 0) {
  28394. sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
  28395. AF_INET6 : AF_INET, SOCK_DGRAM, 0);
  28396. if (sipsock < 0) {
  28397. ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
  28398. ast_config_destroy(cfg);
  28399. ast_mutex_unlock(&netlock);
  28400. return -1;
  28401. } else {
  28402. /* Allow SIP clients on the same host to access us: */
  28403. const int reuseFlag = 1;
  28404. setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
  28405. (const char*)&reuseFlag,
  28406. sizeof reuseFlag);
  28407. ast_enable_packet_fragmentation(sipsock);
  28408. if (ast_bind(sipsock, &bindaddr) < 0) {
  28409. ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
  28410. ast_sockaddr_stringify(&bindaddr), strerror(errno));
  28411. close(sipsock);
  28412. sipsock = -1;
  28413. } else {
  28414. ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
  28415. ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
  28416. }
  28417. }
  28418. } else {
  28419. ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
  28420. }
  28421. ast_mutex_unlock(&netlock);
  28422. /* Start TCP server */
  28423. if (sip_cfg.tcp_enabled) {
  28424. if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
  28425. ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
  28426. }
  28427. if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
  28428. ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
  28429. }
  28430. } else {
  28431. ast_sockaddr_setnull(&sip_tcp_desc.local_address);
  28432. }
  28433. ast_tcptls_server_start(&sip_tcp_desc);
  28434. if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
  28435. /* TCP server start failed. Tell the admin */
  28436. ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
  28437. } else {
  28438. ast_debug(2, "SIP TCP server started\n");
  28439. }
  28440. /* Start TLS server if needed */
  28441. memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
  28442. if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
  28443. if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
  28444. ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
  28445. ast_sockaddr_set_port(&sip_tls_desc.local_address,
  28446. STANDARD_TLS_PORT);
  28447. }
  28448. if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
  28449. ast_sockaddr_set_port(&sip_tls_desc.local_address,
  28450. STANDARD_TLS_PORT);
  28451. }
  28452. ast_tcptls_server_start(&sip_tls_desc);
  28453. if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
  28454. ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
  28455. sip_tls_desc.tls_cfg = NULL;
  28456. }
  28457. } else if (sip_tls_desc.tls_cfg->enabled) {
  28458. sip_tls_desc.tls_cfg = NULL;
  28459. ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
  28460. }
  28461. if (ucfg) {
  28462. struct ast_variable *gen;
  28463. int genhassip, genregistersip;
  28464. const char *hassip, *registersip;
  28465. genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
  28466. genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
  28467. gen = ast_variable_browse(ucfg, "general");
  28468. cat = ast_category_browse(ucfg, NULL);
  28469. while (cat) {
  28470. if (strcasecmp(cat, "general")) {
  28471. hassip = ast_variable_retrieve(ucfg, cat, "hassip");
  28472. registersip = ast_variable_retrieve(ucfg, cat, "registersip");
  28473. if (ast_true(hassip) || (!hassip && genhassip)) {
  28474. peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
  28475. if (peer) {
  28476. /* user.conf entries are always of type friend */
  28477. peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
  28478. ao2_t_link(peers, peer, "link peer into peer table");
  28479. if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
  28480. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  28481. }
  28482. sip_unref_peer(peer, "sip_unref_peer: from reload_config");
  28483. peer_count++;
  28484. }
  28485. }
  28486. if (ast_true(registersip) || (!registersip && genregistersip)) {
  28487. char tmp[256];
  28488. const char *host = ast_variable_retrieve(ucfg, cat, "host");
  28489. const char *username = ast_variable_retrieve(ucfg, cat, "username");
  28490. const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
  28491. const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
  28492. const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
  28493. if (!host) {
  28494. host = ast_variable_retrieve(ucfg, "general", "host");
  28495. }
  28496. if (!username) {
  28497. username = ast_variable_retrieve(ucfg, "general", "username");
  28498. }
  28499. if (!secret) {
  28500. secret = ast_variable_retrieve(ucfg, "general", "secret");
  28501. }
  28502. if (!contact) {
  28503. contact = "s";
  28504. }
  28505. if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
  28506. if (!ast_strlen_zero(secret)) {
  28507. if (!ast_strlen_zero(authuser)) {
  28508. snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
  28509. } else {
  28510. snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
  28511. }
  28512. } else if (!ast_strlen_zero(authuser)) {
  28513. snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
  28514. } else {
  28515. snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
  28516. }
  28517. if (sip_register(tmp, 0) == 0) {
  28518. registry_count++;
  28519. }
  28520. }
  28521. }
  28522. }
  28523. cat = ast_category_browse(ucfg, cat);
  28524. }
  28525. ast_config_destroy(ucfg);
  28526. }
  28527. /* Load peers, users and friends */
  28528. cat = NULL;
  28529. while ( (cat = ast_category_browse(cfg, cat)) ) {
  28530. const char *utype;
  28531. if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
  28532. continue;
  28533. utype = ast_variable_retrieve(cfg, cat, "type");
  28534. if (!utype) {
  28535. ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
  28536. continue;
  28537. } else {
  28538. if (!strcasecmp(utype, "user")) {
  28539. ;
  28540. } else if (!strcasecmp(utype, "friend")) {
  28541. ;
  28542. } else if (!strcasecmp(utype, "peer")) {
  28543. ;
  28544. } else {
  28545. ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
  28546. continue;
  28547. }
  28548. peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
  28549. if (peer) {
  28550. display_nat_warning(cat, reason, &peer->flags[0]);
  28551. ao2_t_link(peers, peer, "link peer into peers table");
  28552. if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
  28553. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  28554. }
  28555. sip_unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
  28556. peer_count++;
  28557. }
  28558. }
  28559. }
  28560. /* Add default domains - host name, IP address and IP:port
  28561. * Only do this if user added any sip domain with "localdomains"
  28562. * In order to *not* break backwards compatibility
  28563. * Some phones address us at IP only, some with additional port number
  28564. */
  28565. if (auto_sip_domains) {
  28566. char temp[MAXHOSTNAMELEN];
  28567. /* First our default IP address */
  28568. if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
  28569. add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
  28570. SIP_DOMAIN_AUTO, NULL);
  28571. } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
  28572. /* Our internal IP address, if configured */
  28573. add_sip_domain(ast_sockaddr_stringify_addr(&internip),
  28574. SIP_DOMAIN_AUTO, NULL);
  28575. } else {
  28576. ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
  28577. }
  28578. /* If TCP is running on a different IP than UDP, then add it too */
  28579. if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
  28580. !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
  28581. add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
  28582. SIP_DOMAIN_AUTO, NULL);
  28583. }
  28584. /* If TLS is running on a different IP than UDP and TCP, then add that too */
  28585. if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
  28586. !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
  28587. !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
  28588. &sip_tls_desc.local_address)) {
  28589. add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
  28590. SIP_DOMAIN_AUTO, NULL);
  28591. }
  28592. /* Our extern IP address, if configured */
  28593. if (!ast_sockaddr_isnull(&externaddr)) {
  28594. add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
  28595. SIP_DOMAIN_AUTO, NULL);
  28596. }
  28597. /* Extern host name (NAT traversal support) */
  28598. if (!ast_strlen_zero(externhost)) {
  28599. add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
  28600. }
  28601. /* Our host name */
  28602. if (!gethostname(temp, sizeof(temp))) {
  28603. add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
  28604. }
  28605. }
  28606. /* Release configuration from memory */
  28607. ast_config_destroy(cfg);
  28608. register_realtime_peers_with_callbackextens();
  28609. /* Load the list of manual NOTIFY types to support */
  28610. if (notify_types) {
  28611. ast_config_destroy(notify_types);
  28612. }
  28613. if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
  28614. ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
  28615. notify_types = NULL;
  28616. }
  28617. run_end = time(0);
  28618. ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
  28619. /* If an ACL change subscription is needed and doesn't exist, we need one. */
  28620. if (acl_change_subscription_needed) {
  28621. acl_change_stasis_subscribe();
  28622. }
  28623. return 0;
  28624. }
  28625. static int sip_allow_anyrtp_remote(struct ast_channel *chan1, struct ast_rtp_instance *instance, const char *rtptype)
  28626. {
  28627. struct sip_pvt *p;
  28628. struct ast_acl_list *acl = NULL;
  28629. int res = 1;
  28630. if (!(p = ast_channel_tech_pvt(chan1))) {
  28631. return 0;
  28632. }
  28633. sip_pvt_lock(p);
  28634. if (p->relatedpeer && p->relatedpeer->directmediaacl) {
  28635. acl = ast_duplicate_acl_list(p->relatedpeer->directmediaacl);
  28636. }
  28637. sip_pvt_unlock(p);
  28638. if (!acl) {
  28639. return res;
  28640. }
  28641. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  28642. struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
  28643. ast_rtp_instance_get_remote_address(instance, &them);
  28644. ast_rtp_instance_get_local_address(instance, &us);
  28645. if (ast_apply_acl(acl, &them, "SIP Direct Media ACL: ") == AST_SENSE_DENY) {
  28646. const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
  28647. const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
  28648. ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
  28649. rtptype, them_addr, us_addr);
  28650. res = 0;
  28651. }
  28652. }
  28653. ast_free_acl_list(acl);
  28654. return res;
  28655. }
  28656. static int sip_allow_rtp_remote(struct ast_channel *chan1, struct ast_rtp_instance *instance)
  28657. {
  28658. return sip_allow_anyrtp_remote(chan1, instance, "audio");
  28659. }
  28660. static int sip_allow_vrtp_remote(struct ast_channel *chan1, struct ast_rtp_instance *instance)
  28661. {
  28662. return sip_allow_anyrtp_remote(chan1, instance, "video");
  28663. }
  28664. static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
  28665. {
  28666. struct sip_pvt *p = NULL;
  28667. enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
  28668. if (!(p = ast_channel_tech_pvt(chan))) {
  28669. return AST_RTP_GLUE_RESULT_FORBID;
  28670. }
  28671. sip_pvt_lock(p);
  28672. if (!(p->rtp)) {
  28673. sip_pvt_unlock(p);
  28674. return AST_RTP_GLUE_RESULT_FORBID;
  28675. }
  28676. ao2_ref(p->rtp, +1);
  28677. *instance = p->rtp;
  28678. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  28679. res = AST_RTP_GLUE_RESULT_REMOTE;
  28680. } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
  28681. res = AST_RTP_GLUE_RESULT_REMOTE;
  28682. } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
  28683. res = AST_RTP_GLUE_RESULT_FORBID;
  28684. }
  28685. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
  28686. switch (p->t38.state) {
  28687. case T38_LOCAL_REINVITE:
  28688. case T38_PEER_REINVITE:
  28689. case T38_ENABLED:
  28690. res = AST_RTP_GLUE_RESULT_LOCAL;
  28691. break;
  28692. case T38_REJECTED:
  28693. default:
  28694. break;
  28695. }
  28696. }
  28697. if (p->srtp) {
  28698. res = AST_RTP_GLUE_RESULT_FORBID;
  28699. }
  28700. sip_pvt_unlock(p);
  28701. return res;
  28702. }
  28703. static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
  28704. {
  28705. struct sip_pvt *p = NULL;
  28706. enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
  28707. if (!(p = ast_channel_tech_pvt(chan))) {
  28708. return AST_RTP_GLUE_RESULT_FORBID;
  28709. }
  28710. sip_pvt_lock(p);
  28711. if (!(p->vrtp)) {
  28712. sip_pvt_unlock(p);
  28713. return AST_RTP_GLUE_RESULT_FORBID;
  28714. }
  28715. ao2_ref(p->vrtp, +1);
  28716. *instance = p->vrtp;
  28717. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  28718. res = AST_RTP_GLUE_RESULT_REMOTE;
  28719. }
  28720. sip_pvt_unlock(p);
  28721. return res;
  28722. }
  28723. static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
  28724. {
  28725. struct sip_pvt *p = NULL;
  28726. enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
  28727. if (!(p = ast_channel_tech_pvt(chan))) {
  28728. return AST_RTP_GLUE_RESULT_FORBID;
  28729. }
  28730. sip_pvt_lock(p);
  28731. if (!(p->trtp)) {
  28732. sip_pvt_unlock(p);
  28733. return AST_RTP_GLUE_RESULT_FORBID;
  28734. }
  28735. ao2_ref(p->trtp, +1);
  28736. *instance = p->trtp;
  28737. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  28738. res = AST_RTP_GLUE_RESULT_REMOTE;
  28739. }
  28740. sip_pvt_unlock(p);
  28741. return res;
  28742. }
  28743. 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)
  28744. {
  28745. struct sip_pvt *p;
  28746. int changed = 0;
  28747. p = ast_channel_tech_pvt(chan);
  28748. if (!p) {
  28749. return -1;
  28750. }
  28751. sip_pvt_lock(p);
  28752. if (p->owner != chan) {
  28753. /* I suppose it could be argued that if this happens it is a bug. */
  28754. ast_debug(1, "The private is not owned by channel %s anymore.\n", ast_channel_name(chan));
  28755. sip_pvt_unlock(p);
  28756. return 0;
  28757. }
  28758. /* Disable early RTP bridge */
  28759. if ((instance || vinstance || tinstance) &&
  28760. !ast_channel_is_bridged(chan) &&
  28761. !sip_cfg.directrtpsetup) {
  28762. sip_pvt_unlock(p);
  28763. return 0;
  28764. }
  28765. if (p->alreadygone) {
  28766. /* If we're destroyed, don't bother */
  28767. sip_pvt_unlock(p);
  28768. return 0;
  28769. }
  28770. /* if this peer cannot handle reinvites of the media stream to devices
  28771. that are known to be behind a NAT, then stop the process now
  28772. */
  28773. if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
  28774. sip_pvt_unlock(p);
  28775. return 0;
  28776. }
  28777. if (instance) {
  28778. changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
  28779. if (p->rtp) {
  28780. /* Prevent audio RTCP reads */
  28781. ast_channel_set_fd(chan, 1, -1);
  28782. /* Silence RTCP while audio RTP is inactive */
  28783. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
  28784. }
  28785. } else if (!ast_sockaddr_isnull(&p->redirip)) {
  28786. memset(&p->redirip, 0, sizeof(p->redirip));
  28787. changed = 1;
  28788. if (p->rtp) {
  28789. /* Enable RTCP since it will be inactive if we're coming back
  28790. * from a reinvite */
  28791. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
  28792. /* Enable audio RTCP reads */
  28793. ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
  28794. }
  28795. }
  28796. if (vinstance) {
  28797. changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
  28798. if (p->vrtp) {
  28799. /* Prevent video RTCP reads */
  28800. ast_channel_set_fd(chan, 3, -1);
  28801. /* Silence RTCP while video RTP is inactive */
  28802. ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
  28803. }
  28804. } else if (!ast_sockaddr_isnull(&p->vredirip)) {
  28805. memset(&p->vredirip, 0, sizeof(p->vredirip));
  28806. changed = 1;
  28807. if (p->vrtp) {
  28808. /* Enable RTCP since it will be inactive if we're coming back
  28809. * from a reinvite */
  28810. ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
  28811. /* Enable video RTCP reads */
  28812. ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
  28813. }
  28814. }
  28815. if (tinstance) {
  28816. changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
  28817. } else if (!ast_sockaddr_isnull(&p->tredirip)) {
  28818. memset(&p->tredirip, 0, sizeof(p->tredirip));
  28819. changed = 1;
  28820. }
  28821. if (cap && ast_format_cap_count(cap) && !ast_format_cap_identical(cap, p->redircaps)) {
  28822. ast_format_cap_remove_by_type(p->redircaps, AST_MEDIA_TYPE_UNKNOWN);
  28823. ast_format_cap_append_from_cap(p->redircaps, cap, AST_MEDIA_TYPE_UNKNOWN);
  28824. changed = 1;
  28825. }
  28826. if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
  28827. /* We only wish to withhold sending the initial direct media reinvite on the incoming dialog.
  28828. * Further direct media reinvites beyond the initial should be sent. In order to allow further
  28829. * direct media reinvites to be sent, we clear this flag.
  28830. */
  28831. ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
  28832. sip_pvt_unlock(p);
  28833. return 0;
  28834. }
  28835. if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
  28836. if (ast_channel_state(chan) != AST_STATE_UP) { /* We are in early state */
  28837. if (p->do_history)
  28838. append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
  28839. ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
  28840. } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
  28841. 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));
  28842. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  28843. } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  28844. 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));
  28845. /* We have a pending Invite. Send re-invite when we're done with the invite */
  28846. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  28847. }
  28848. }
  28849. /* Reset lastrtprx timer */
  28850. p->lastrtprx = p->lastrtptx = time(NULL);
  28851. sip_pvt_unlock(p);
  28852. return 0;
  28853. }
  28854. static void sip_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
  28855. {
  28856. struct sip_pvt *p = ast_channel_tech_pvt(chan);
  28857. ast_format_cap_append_from_cap(result, !ast_format_cap_count(p->peercaps) ? p->caps : p->peercaps, AST_MEDIA_TYPE_UNKNOWN);
  28858. }
  28859. static struct ast_rtp_glue sip_rtp_glue = {
  28860. .type = "SIP",
  28861. .get_rtp_info = sip_get_rtp_peer,
  28862. .allow_rtp_remote = sip_allow_rtp_remote,
  28863. .get_vrtp_info = sip_get_vrtp_peer,
  28864. .allow_vrtp_remote = sip_allow_vrtp_remote,
  28865. .get_trtp_info = sip_get_trtp_peer,
  28866. .update_peer = sip_set_rtp_peer,
  28867. .get_codec = sip_get_codec,
  28868. };
  28869. static char *app_dtmfmode = "SIPDtmfMode";
  28870. static char *app_sipaddheader = "SIPAddHeader";
  28871. static char *app_sipremoveheader = "SIPRemoveHeader";
  28872. #ifdef TEST_FRAMEWORK
  28873. static char *app_sipsendcustominfo = "SIPSendCustomINFO";
  28874. #endif
  28875. /*! \brief Set the DTMFmode for an outbound SIP call (application) */
  28876. static int sip_dtmfmode(struct ast_channel *chan, const char *data)
  28877. {
  28878. struct sip_pvt *p;
  28879. const char *mode = data;
  28880. if (!data) {
  28881. ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
  28882. return 0;
  28883. }
  28884. ast_channel_lock(chan);
  28885. if (!IS_SIP_TECH(ast_channel_tech(chan))) {
  28886. ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
  28887. ast_channel_unlock(chan);
  28888. return 0;
  28889. }
  28890. p = ast_channel_tech_pvt(chan);
  28891. if (!p) {
  28892. ast_channel_unlock(chan);
  28893. return 0;
  28894. }
  28895. sip_pvt_lock(p);
  28896. if (!strcasecmp(mode, "info")) {
  28897. ast_clear_flag(&p->flags[0], SIP_DTMF);
  28898. ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
  28899. p->jointnoncodeccapability &= ~AST_RTP_DTMF;
  28900. } else if (!strcasecmp(mode, "shortinfo")) {
  28901. ast_clear_flag(&p->flags[0], SIP_DTMF);
  28902. ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
  28903. p->jointnoncodeccapability &= ~AST_RTP_DTMF;
  28904. } else if (!strcasecmp(mode, "rfc2833")) {
  28905. ast_clear_flag(&p->flags[0], SIP_DTMF);
  28906. ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
  28907. p->jointnoncodeccapability |= AST_RTP_DTMF;
  28908. } else if (!strcasecmp(mode, "inband")) {
  28909. ast_clear_flag(&p->flags[0], SIP_DTMF);
  28910. ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
  28911. p->jointnoncodeccapability &= ~AST_RTP_DTMF;
  28912. } else {
  28913. ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
  28914. }
  28915. if (p->rtp)
  28916. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  28917. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  28918. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  28919. enable_dsp_detect(p);
  28920. } else {
  28921. disable_dsp_detect(p);
  28922. }
  28923. sip_pvt_unlock(p);
  28924. ast_channel_unlock(chan);
  28925. return 0;
  28926. }
  28927. /*! \brief Add a SIP header to an outbound INVITE */
  28928. static int sip_addheader(struct ast_channel *chan, const char *data)
  28929. {
  28930. int no = 0;
  28931. int ok = FALSE;
  28932. char varbuf[30];
  28933. const char *inbuf = data;
  28934. char *subbuf;
  28935. if (ast_strlen_zero(inbuf)) {
  28936. ast_log(LOG_WARNING, "This application requires the argument: Header\n");
  28937. return 0;
  28938. }
  28939. ast_channel_lock(chan);
  28940. /* Check for headers */
  28941. while (!ok && no <= 50) {
  28942. no++;
  28943. snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
  28944. /* Compare without the leading underscores */
  28945. if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
  28946. ok = TRUE;
  28947. }
  28948. }
  28949. if (ok) {
  28950. size_t len = strlen(inbuf);
  28951. subbuf = ast_alloca(len + 1);
  28952. ast_get_encoded_str(inbuf, subbuf, len + 1);
  28953. pbx_builtin_setvar_helper(chan, varbuf, subbuf);
  28954. if (sipdebug) {
  28955. ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
  28956. }
  28957. } else {
  28958. ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
  28959. }
  28960. ast_channel_unlock(chan);
  28961. return 0;
  28962. }
  28963. /*! \brief Remove SIP headers added previously with SipAddHeader application */
  28964. static int sip_removeheader(struct ast_channel *chan, const char *data)
  28965. {
  28966. struct ast_var_t *newvariable;
  28967. struct varshead *headp;
  28968. int removeall = 0;
  28969. char *inbuf = (char *) data;
  28970. if (ast_strlen_zero(inbuf)) {
  28971. removeall = 1;
  28972. }
  28973. ast_channel_lock(chan);
  28974. headp=ast_channel_varshead(chan);
  28975. AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
  28976. if (strncmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
  28977. if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
  28978. if (sipdebug) {
  28979. ast_debug(1,"removing SIP Header \"%s\" as %s\n",
  28980. ast_var_value(newvariable),
  28981. ast_var_name(newvariable));
  28982. }
  28983. AST_LIST_REMOVE_CURRENT(entries);
  28984. ast_var_delete(newvariable);
  28985. }
  28986. }
  28987. }
  28988. AST_LIST_TRAVERSE_SAFE_END;
  28989. ast_channel_unlock(chan);
  28990. return 0;
  28991. }
  28992. #ifdef TEST_FRAMEWORK
  28993. /*! \brief Send a custom INFO message via AST_CONTROL_CUSTOM indication */
  28994. static int sip_sendcustominfo(struct ast_channel *chan, const char *data)
  28995. {
  28996. char *info_data, *useragent;
  28997. if (ast_strlen_zero(data)) {
  28998. ast_log(LOG_WARNING, "You must provide data to be sent\n");
  28999. return 0;
  29000. }
  29001. useragent = ast_strdupa(data);
  29002. info_data = strsep(&useragent, ",");
  29003. if (ast_sipinfo_send(chan, NULL, "text/plain", info_data, useragent)) {
  29004. ast_log(LOG_WARNING, "Failed to create payload for custom SIP INFO\n");
  29005. return 0;
  29006. }
  29007. return 0;
  29008. }
  29009. #endif
  29010. /*! \brief Transfer call before connect with a 302 redirect
  29011. \note Called by the transfer() dialplan application through the sip_transfer()
  29012. pbx interface function if the call is in ringing state
  29013. \todo Fix this function so that we wait for reply to the REFER and
  29014. react to errors, denials or other issues the other end might have.
  29015. */
  29016. static int sip_sipredirect(struct sip_pvt *p, const char *dest)
  29017. {
  29018. char *cdest;
  29019. char *extension, *domain;
  29020. cdest = ast_strdupa(dest);
  29021. extension = strsep(&cdest, "@");
  29022. domain = cdest;
  29023. if (ast_strlen_zero(extension)) {
  29024. ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
  29025. return 0;
  29026. }
  29027. /* we'll issue the redirect message here */
  29028. if (!domain) {
  29029. char *local_to_header;
  29030. char to_header[256];
  29031. ast_copy_string(to_header, sip_get_header(&p->initreq, "To"), sizeof(to_header));
  29032. if (ast_strlen_zero(to_header)) {
  29033. ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
  29034. return 0;
  29035. }
  29036. if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
  29037. && (local_to_header = strchr(local_to_header, '@'))) {
  29038. char ldomain[256];
  29039. memset(ldomain, 0, sizeof(ldomain));
  29040. local_to_header++;
  29041. /* This is okey because lhost and lport are as big as tmp */
  29042. sscanf(local_to_header, "%256[^<>; ]", ldomain);
  29043. if (ast_strlen_zero(ldomain)) {
  29044. ast_log(LOG_ERROR, "Can't find the host address\n");
  29045. return 0;
  29046. }
  29047. domain = ast_strdupa(ldomain);
  29048. }
  29049. }
  29050. ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
  29051. transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
  29052. sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Make sure we stop send this reply. */
  29053. sip_alreadygone(p);
  29054. if (p->owner) {
  29055. enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
  29056. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  29057. }
  29058. /* hangup here */
  29059. return 0;
  29060. }
  29061. static int sip_is_xml_parsable(void)
  29062. {
  29063. #ifdef HAVE_LIBXML2
  29064. return TRUE;
  29065. #else
  29066. return FALSE;
  29067. #endif
  29068. }
  29069. /*! \brief Send a poke to all known peers */
  29070. static void sip_poke_all_peers(void)
  29071. {
  29072. int ms = 0, num = 0;
  29073. struct ao2_iterator i;
  29074. struct sip_peer *peer;
  29075. if (!speerobjs) { /* No peers, just give up */
  29076. return;
  29077. }
  29078. i = ao2_iterator_init(peers, 0);
  29079. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  29080. ao2_lock(peer);
  29081. /* Don't schedule poking on a peer without qualify */
  29082. if (peer->maxms) {
  29083. if (num == global_qualify_peers) {
  29084. ms += global_qualify_gap;
  29085. num = 0;
  29086. } else {
  29087. num++;
  29088. }
  29089. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
  29090. sip_unref_peer(_data, "removing poke peer ref"),
  29091. sip_unref_peer(peer, "removing poke peer ref"),
  29092. sip_ref_peer(peer, "adding poke peer ref"));
  29093. }
  29094. ao2_unlock(peer);
  29095. sip_unref_peer(peer, "toss iterator peer ptr");
  29096. }
  29097. ao2_iterator_destroy(&i);
  29098. }
  29099. /*! \brief Send a keepalive to all known peers */
  29100. static void sip_keepalive_all_peers(void)
  29101. {
  29102. struct ao2_iterator i;
  29103. struct sip_peer *peer;
  29104. if (!speerobjs) { /* No peers, just give up */
  29105. return;
  29106. }
  29107. i = ao2_iterator_init(peers, 0);
  29108. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  29109. ao2_lock(peer);
  29110. AST_SCHED_REPLACE_UNREF(peer->keepalivesend, sched, 0, sip_send_keepalive, peer,
  29111. sip_unref_peer(_data, "removing poke peer ref"),
  29112. sip_unref_peer(peer, "removing poke peer ref"),
  29113. sip_ref_peer(peer, "adding poke peer ref"));
  29114. ao2_unlock(peer);
  29115. sip_unref_peer(peer, "toss iterator peer ptr");
  29116. }
  29117. ao2_iterator_destroy(&i);
  29118. }
  29119. /*! \brief Send all known registrations */
  29120. static void sip_send_all_registers(void)
  29121. {
  29122. int ms;
  29123. int regspacing;
  29124. struct ao2_iterator iter;
  29125. struct sip_registry *iterator;
  29126. if (!ao2_container_count(registry_list)) {
  29127. return;
  29128. }
  29129. regspacing = default_expiry * 1000 / ao2_container_count(registry_list);
  29130. if (regspacing > 100) {
  29131. regspacing = 100;
  29132. }
  29133. ms = regspacing;
  29134. iter = ao2_iterator_init(registry_list, 0);
  29135. while ((iterator = ao2_t_iterator_next(&iter, "sip_send_all_registers iter"))) {
  29136. ao2_lock(iterator);
  29137. ms += regspacing;
  29138. AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
  29139. ao2_t_ref(_data, -1, "REPLACE sched del decs the refcount"),
  29140. ao2_t_ref(iterator, -1, "REPLACE sched add failure decs the refcount"),
  29141. ao2_t_ref(iterator, +1, "REPLACE sched add incs the refcount"));
  29142. ao2_unlock(iterator);
  29143. ao2_t_ref(iterator, -1, "sip_send_all_registers iter");
  29144. }
  29145. ao2_iterator_destroy(&iter);
  29146. }
  29147. /*! \brief Send all MWI subscriptions */
  29148. static void sip_send_all_mwi_subscriptions(void)
  29149. {
  29150. struct ao2_iterator iter;
  29151. struct sip_subscription_mwi *iterator;
  29152. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29153. while ((iterator = ao2_t_iterator_next(&iter, "sip_send_all_mwi_subscriptions iter"))) {
  29154. ao2_lock(iterator);
  29155. AST_SCHED_DEL(sched, iterator->resub);
  29156. ao2_t_ref(iterator, +1, "mwi added to schedule");
  29157. if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, iterator)) < 0) {
  29158. ao2_t_ref(iterator, -1, "mwi failed to schedule");
  29159. }
  29160. ao2_unlock(iterator);
  29161. ao2_t_ref(iterator, -1, "sip_send_all_mwi_subscriptions iter");
  29162. }
  29163. ao2_iterator_destroy(&iter);
  29164. }
  29165. static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp, const char *a)
  29166. {
  29167. struct ast_rtp_engine_dtls *dtls;
  29168. /* If no RTP instance exists for this media stream don't bother processing the crypto line */
  29169. if (!rtp) {
  29170. ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
  29171. return FALSE;
  29172. }
  29173. if (strncasecmp(a, "crypto:", 7)) {
  29174. return FALSE;
  29175. }
  29176. /* skip "crypto:" */
  29177. a += strlen("crypto:");
  29178. if (!*srtp) {
  29179. if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  29180. ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
  29181. return FALSE;
  29182. }
  29183. if (!(*srtp = ast_sdp_srtp_alloc())) {
  29184. return FALSE;
  29185. }
  29186. }
  29187. if (!(*srtp)->crypto && !((*srtp)->crypto = ast_sdp_crypto_alloc())) {
  29188. return FALSE;
  29189. }
  29190. if (ast_sdp_crypto_process(rtp, *srtp, a) < 0) {
  29191. return FALSE;
  29192. }
  29193. if ((dtls = ast_rtp_instance_get_dtls(rtp))) {
  29194. dtls->stop(rtp);
  29195. p->dtls_cfg.enabled = 0;
  29196. }
  29197. return TRUE;
  29198. }
  29199. /*! \brief Reload module */
  29200. static int sip_do_reload(enum channelreloadreason reason)
  29201. {
  29202. time_t start_poke, end_poke;
  29203. reload_config(reason);
  29204. ast_sched_dump(sched);
  29205. start_poke = time(0);
  29206. /* Prune peers who still are supposed to be deleted */
  29207. unlink_marked_peers_from_tables();
  29208. ast_debug(4, "--------------- Done destroying pruned peers\n");
  29209. /* Send qualify (OPTIONS) to all peers */
  29210. sip_poke_all_peers();
  29211. /* Send keepalive to all peers */
  29212. sip_keepalive_all_peers();
  29213. /* Register with all services */
  29214. sip_send_all_registers();
  29215. sip_send_all_mwi_subscriptions();
  29216. end_poke = time(0);
  29217. ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
  29218. ast_debug(4, "--------------- SIP reload done\n");
  29219. return 0;
  29220. }
  29221. /*! \brief Force reload of module from cli */
  29222. static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  29223. {
  29224. static struct sip_peer *tmp_peer, *new_peer;
  29225. switch (cmd) {
  29226. case CLI_INIT:
  29227. e->command = "sip reload";
  29228. e->usage =
  29229. "Usage: sip reload\n"
  29230. " Reloads SIP configuration from sip.conf\n";
  29231. return NULL;
  29232. case CLI_GENERATE:
  29233. return NULL;
  29234. }
  29235. ast_mutex_lock(&sip_reload_lock);
  29236. if (sip_reloading) {
  29237. ast_verbose("Previous SIP reload not yet done\n");
  29238. } else {
  29239. sip_reloading = TRUE;
  29240. sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
  29241. }
  29242. ast_mutex_unlock(&sip_reload_lock);
  29243. restart_monitor();
  29244. tmp_peer = bogus_peer;
  29245. /* Create new bogus peer possibly with new global settings. */
  29246. if ((new_peer = temp_peer("(bogus_peer)"))) {
  29247. ast_string_field_set(new_peer, md5secret, BOGUS_PEER_MD5SECRET);
  29248. ast_clear_flag(&new_peer->flags[0], SIP_INSECURE);
  29249. bogus_peer = new_peer;
  29250. ao2_t_ref(tmp_peer, -1, "unref the old bogus_peer during reload");
  29251. } else {
  29252. ast_log(LOG_ERROR, "Could not update the fake authentication peer.\n");
  29253. /* You probably have bigger (memory?) issues to worry about though.. */
  29254. }
  29255. return CLI_SUCCESS;
  29256. }
  29257. /*! \brief Part of Asterisk module interface */
  29258. static int reload(void)
  29259. {
  29260. if (sip_reload(0, 0, NULL)) {
  29261. return 0;
  29262. }
  29263. return 1;
  29264. }
  29265. /*! \brief Return the first entry from ast_sockaddr_resolve filtered by address family
  29266. *
  29267. * \warning Using this function probably means you have a faulty design.
  29268. */
  29269. static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
  29270. const char* name, int flag, int family)
  29271. {
  29272. struct ast_sockaddr *addrs;
  29273. int addrs_cnt;
  29274. addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
  29275. if (addrs_cnt <= 0) {
  29276. return 1;
  29277. }
  29278. if (addrs_cnt > 1) {
  29279. ast_debug(1, "Multiple addresses, using the first one only\n");
  29280. }
  29281. ast_sockaddr_copy(addr, &addrs[0]);
  29282. ast_free(addrs);
  29283. return 0;
  29284. }
  29285. /*! \brief Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
  29286. *
  29287. * \warning Using this function probably means you have a faulty design.
  29288. */
  29289. static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
  29290. const char* name, int flag)
  29291. {
  29292. return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(AST_TRANSPORT_UDP));
  29293. }
  29294. /*! \brief Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
  29295. *
  29296. * \warning Using this function probably means you have a faulty design.
  29297. */
  29298. static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
  29299. const char* name, int flag, unsigned int transport)
  29300. {
  29301. return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
  29302. }
  29303. /*! \brief
  29304. * \note The only member of the peer used here is the name field
  29305. */
  29306. static int peer_hash_cb(const void *obj, const int flags)
  29307. {
  29308. const struct sip_peer *peer = obj;
  29309. return ast_str_case_hash(peer->name);
  29310. }
  29311. /*!
  29312. * \note The only member of the peer used here is the name field
  29313. */
  29314. static int peer_cmp_cb(void *obj, void *arg, int flags)
  29315. {
  29316. struct sip_peer *peer = obj, *peer2 = arg;
  29317. return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
  29318. }
  29319. /*!
  29320. * Hash function based on the the peer's ip address. For IPv6, we use the end
  29321. * of the address.
  29322. * \todo Find a better hashing function
  29323. */
  29324. static int peer_iphash_cb(const void *obj, const int flags)
  29325. {
  29326. const struct sip_peer *peer = obj;
  29327. int ret = 0;
  29328. if (ast_sockaddr_isnull(&peer->addr)) {
  29329. ast_log(LOG_ERROR, "Empty address\n");
  29330. }
  29331. ret = ast_sockaddr_hash(&peer->addr);
  29332. if (ret < 0) {
  29333. ret = -ret;
  29334. }
  29335. return ret;
  29336. }
  29337. /*!
  29338. * Match Peers by IP and Port number.
  29339. *
  29340. * This function has two modes.
  29341. * - If the peer arg does not have INSECURE_PORT set, then we will only return
  29342. * a match for a peer that matches both the IP and port.
  29343. * - If the peer arg does have the INSECURE_PORT flag set, then we will only
  29344. * return a match for a peer that matches the IP and has insecure=port
  29345. * in its configuration.
  29346. *
  29347. * This callback will be used twice when doing peer matching. There is a first
  29348. * pass for full IP+port matching, and a second pass in case there is a match
  29349. * that meets the insecure=port criteria.
  29350. *
  29351. * \note Connections coming in over TCP or TLS should never be matched by port.
  29352. *
  29353. * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
  29354. */
  29355. static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags)
  29356. {
  29357. struct sip_peer *peer = obj, *peer2 = arg;
  29358. char *callback = data;
  29359. if (!ast_strlen_zero(callback) && strcasecmp(peer->callback, callback)) {
  29360. /* We require a callback extension match, but don't have one */
  29361. return 0;
  29362. }
  29363. /* At this point, we match the callback extension if we need to. Carry on. */
  29364. if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
  29365. /* IP doesn't match */
  29366. return 0;
  29367. }
  29368. /* We matched the IP, check to see if we need to match by port as well. */
  29369. if ((peer->transports & peer2->transports) & (AST_TRANSPORT_TLS | AST_TRANSPORT_TCP)) {
  29370. /* peer matching on port is not possible with TCP/TLS */
  29371. return CMP_MATCH | CMP_STOP;
  29372. } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
  29373. /* We are allowing match without port for peers configured that
  29374. * way in this pass through the peers. */
  29375. return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
  29376. (CMP_MATCH | CMP_STOP) : 0;
  29377. }
  29378. /* Now only return a match if the port matches, as well. */
  29379. return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
  29380. (CMP_MATCH | CMP_STOP) : 0;
  29381. }
  29382. static int peer_ipcmp_cb(void *obj, void *arg, int flags)
  29383. {
  29384. return peer_ipcmp_cb_full(obj, arg, NULL, flags);
  29385. }
  29386. static int threadt_hash_cb(const void *obj, const int flags)
  29387. {
  29388. const struct sip_threadinfo *th = obj;
  29389. return ast_sockaddr_hash(&th->tcptls_session->remote_address);
  29390. }
  29391. static int threadt_cmp_cb(void *obj, void *arg, int flags)
  29392. {
  29393. struct sip_threadinfo *th = obj, *th2 = arg;
  29394. return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
  29395. }
  29396. /*!
  29397. * \note The only member of the dialog used here callid string
  29398. */
  29399. static int dialog_hash_cb(const void *obj, const int flags)
  29400. {
  29401. const struct sip_pvt *pvt = obj;
  29402. return ast_str_case_hash(pvt->callid);
  29403. }
  29404. /*!
  29405. * \note Same as dialog_cmp_cb, except without the CMP_STOP on match
  29406. */
  29407. static int dialog_find_multiple(void *obj, void *arg, int flags)
  29408. {
  29409. struct sip_pvt *pvt = obj, *pvt2 = arg;
  29410. return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
  29411. }
  29412. /*!
  29413. * \note The only member of the dialog used here callid string
  29414. */
  29415. static int dialog_cmp_cb(void *obj, void *arg, int flags)
  29416. {
  29417. struct sip_pvt *pvt = obj, *pvt2 = arg;
  29418. return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
  29419. }
  29420. static int registry_hash_cb(const void *obj, const int flags)
  29421. {
  29422. const struct sip_registry *object;
  29423. const char *key;
  29424. switch (flags & OBJ_SEARCH_MASK) {
  29425. case OBJ_SEARCH_KEY:
  29426. key = obj;
  29427. break;
  29428. case OBJ_SEARCH_OBJECT:
  29429. object = obj;
  29430. key = object->configvalue;
  29431. break;
  29432. default:
  29433. /* Hash can only work on something with a full key. */
  29434. ast_assert(0);
  29435. return 0;
  29436. }
  29437. return ast_str_hash(key);
  29438. }
  29439. static int registry_cmp_cb(void *obj, void *arg, int flags)
  29440. {
  29441. const struct sip_registry *object_left = obj;
  29442. const struct sip_registry *object_right = arg;
  29443. const char *right_key = arg;
  29444. int cmp;
  29445. switch (flags & OBJ_SEARCH_MASK) {
  29446. case OBJ_SEARCH_OBJECT:
  29447. right_key = object_right->configvalue;
  29448. /* Fall through */
  29449. case OBJ_SEARCH_KEY:
  29450. cmp = strcmp(object_left->configvalue, right_key);
  29451. break;
  29452. default:
  29453. cmp = 0;
  29454. break;
  29455. }
  29456. if (cmp) {
  29457. return 0;
  29458. }
  29459. return CMP_MATCH;
  29460. }
  29461. /*! \brief SIP Cli commands definition */
  29462. static struct ast_cli_entry cli_sip[] = {
  29463. AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
  29464. AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
  29465. AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
  29466. AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
  29467. AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
  29468. AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
  29469. AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
  29470. AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
  29471. AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
  29472. AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
  29473. AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
  29474. AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
  29475. AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
  29476. AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
  29477. AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
  29478. AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
  29479. AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
  29480. AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
  29481. AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
  29482. AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
  29483. AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
  29484. AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
  29485. AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
  29486. };
  29487. /*! \brief SIP test registration */
  29488. static void sip_register_tests(void)
  29489. {
  29490. sip_config_parser_register_tests();
  29491. sip_request_parser_register_tests();
  29492. sip_dialplan_function_register_tests();
  29493. }
  29494. /*! \brief SIP test registration */
  29495. static void sip_unregister_tests(void)
  29496. {
  29497. sip_config_parser_unregister_tests();
  29498. sip_request_parser_unregister_tests();
  29499. sip_dialplan_function_unregister_tests();
  29500. }
  29501. #ifdef TEST_FRAMEWORK
  29502. AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
  29503. {
  29504. struct ao2_iterator iter;
  29505. struct sip_subscription_mwi *iterator;
  29506. int found = 0;
  29507. enum ast_test_result_state res = AST_TEST_PASS;
  29508. const char *mwi1 = "1234@mysipprovider.com/1234";
  29509. const char *mwi2 = "1234:password@mysipprovider.com/1234";
  29510. const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
  29511. const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
  29512. const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
  29513. const char *mwi6 = "1234:password";
  29514. switch (cmd) {
  29515. case TEST_INIT:
  29516. info->name = "sip_mwi_subscribe_parse_test";
  29517. info->category = "/channels/chan_sip/";
  29518. info->summary = "SIP MWI subscribe line parse unit test";
  29519. info->description =
  29520. "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
  29521. return AST_TEST_NOT_RUN;
  29522. case TEST_EXECUTE:
  29523. break;
  29524. }
  29525. if (sip_subscribe_mwi(mwi1, 1)) {
  29526. res = AST_TEST_FAIL;
  29527. } else {
  29528. found = 0;
  29529. res = AST_TEST_FAIL;
  29530. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29531. while ((iterator = ao2_t_iterator_next(&iter, "test_sip_mwi_subscribe_parse mwi1"))) {
  29532. ao2_lock(iterator);
  29533. if (
  29534. !strcmp(iterator->hostname, "mysipprovider.com") &&
  29535. !strcmp(iterator->username, "1234") &&
  29536. !strcmp(iterator->secret, "") &&
  29537. !strcmp(iterator->authuser, "") &&
  29538. !strcmp(iterator->mailbox, "1234") &&
  29539. iterator->portno == 0) {
  29540. found = 1;
  29541. res = AST_TEST_PASS;
  29542. }
  29543. ao2_unlock(iterator);
  29544. ao2_t_ref(iterator, -1, "test_sip_mwi_subscribe_parse mwi1");
  29545. }
  29546. ao2_iterator_destroy(&iter);
  29547. if (!found) {
  29548. ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
  29549. }
  29550. }
  29551. if (sip_subscribe_mwi(mwi2, 1)) {
  29552. res = AST_TEST_FAIL;
  29553. } else {
  29554. found = 0;
  29555. res = AST_TEST_FAIL;
  29556. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29557. while ((iterator = ao2_t_iterator_next(&iter, "test_sip_mwi_subscribe_parse mwi2"))) {
  29558. ao2_lock(iterator);
  29559. if (
  29560. !strcmp(iterator->hostname, "mysipprovider.com") &&
  29561. !strcmp(iterator->username, "1234") &&
  29562. !strcmp(iterator->secret, "password") &&
  29563. !strcmp(iterator->authuser, "") &&
  29564. !strcmp(iterator->mailbox, "1234") &&
  29565. iterator->portno == 0) {
  29566. found = 1;
  29567. res = AST_TEST_PASS;
  29568. }
  29569. ao2_unlock(iterator);
  29570. ao2_t_ref(iterator, -1, "test_sip_mwi_subscribe_parse mwi2");
  29571. }
  29572. ao2_iterator_destroy(&iter);
  29573. if (!found) {
  29574. ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
  29575. }
  29576. }
  29577. if (sip_subscribe_mwi(mwi3, 1)) {
  29578. res = AST_TEST_FAIL;
  29579. } else {
  29580. found = 0;
  29581. res = AST_TEST_FAIL;
  29582. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29583. while ((iterator = ao2_t_iterator_next(&iter, "test_sip_mwi_subscribe_parse mwi3"))) {
  29584. ao2_lock(iterator);
  29585. if (
  29586. !strcmp(iterator->hostname, "mysipprovider.com") &&
  29587. !strcmp(iterator->username, "1234") &&
  29588. !strcmp(iterator->secret, "password") &&
  29589. !strcmp(iterator->authuser, "") &&
  29590. !strcmp(iterator->mailbox, "1234") &&
  29591. iterator->portno == 5061) {
  29592. found = 1;
  29593. res = AST_TEST_PASS;
  29594. }
  29595. ao2_unlock(iterator);
  29596. ao2_t_ref(iterator, -1, "test_sip_mwi_subscribe_parse mwi3");
  29597. }
  29598. ao2_iterator_destroy(&iter);
  29599. if (!found) {
  29600. ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
  29601. }
  29602. }
  29603. if (sip_subscribe_mwi(mwi4, 1)) {
  29604. res = AST_TEST_FAIL;
  29605. } else {
  29606. found = 0;
  29607. res = AST_TEST_FAIL;
  29608. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29609. while ((iterator = ao2_t_iterator_next(&iter, "test_sip_mwi_subscribe_parse mwi4"))) {
  29610. ao2_lock(iterator);
  29611. if (
  29612. !strcmp(iterator->hostname, "mysipprovider.com") &&
  29613. !strcmp(iterator->username, "1234") &&
  29614. !strcmp(iterator->secret, "password") &&
  29615. !strcmp(iterator->authuser, "authuser") &&
  29616. !strcmp(iterator->mailbox, "1234") &&
  29617. iterator->portno == 0) {
  29618. found = 1;
  29619. res = AST_TEST_PASS;
  29620. }
  29621. ao2_unlock(iterator);
  29622. ao2_t_ref(iterator, -1, "test_sip_mwi_subscribe_parse mwi4");
  29623. }
  29624. ao2_iterator_destroy(&iter);
  29625. if (!found) {
  29626. ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
  29627. }
  29628. }
  29629. if (sip_subscribe_mwi(mwi5, 1)) {
  29630. res = AST_TEST_FAIL;
  29631. } else {
  29632. found = 0;
  29633. res = AST_TEST_FAIL;
  29634. iter = ao2_iterator_init(subscription_mwi_list, 0);
  29635. while ((iterator = ao2_t_iterator_next(&iter, "test_sip_mwi_subscribe_parse mwi4"))) {
  29636. ao2_lock(iterator);
  29637. if (
  29638. !strcmp(iterator->hostname, "mysipprovider.com") &&
  29639. !strcmp(iterator->username, "1234") &&
  29640. !strcmp(iterator->secret, "password") &&
  29641. !strcmp(iterator->authuser, "authuser") &&
  29642. !strcmp(iterator->mailbox, "1234") &&
  29643. iterator->portno == 5061) {
  29644. found = 1;
  29645. res = AST_TEST_PASS;
  29646. }
  29647. ao2_unlock(iterator);
  29648. ao2_t_ref(iterator, -1, "test_sip_mwi_subscribe_parse mwi4");
  29649. }
  29650. ao2_iterator_destroy(&iter);
  29651. if (!found) {
  29652. ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
  29653. }
  29654. }
  29655. if (sip_subscribe_mwi(mwi6, 1)) {
  29656. res = AST_TEST_PASS;
  29657. } else {
  29658. res = AST_TEST_FAIL;
  29659. }
  29660. return res;
  29661. }
  29662. AST_TEST_DEFINE(test_sip_peers_get)
  29663. {
  29664. struct sip_peer *peer;
  29665. struct ast_data *node;
  29666. struct ast_data_query query = {
  29667. .path = "/asterisk/channel/sip/peers",
  29668. .search = "peers/peer/name=test_peer_data_provider"
  29669. };
  29670. switch (cmd) {
  29671. case TEST_INIT:
  29672. info->name = "sip_peers_get_data_test";
  29673. info->category = "/main/data/sip/peers/";
  29674. info->summary = "SIP peers data providers unit test";
  29675. info->description =
  29676. "Tests whether the SIP peers data provider implementation works as expected.";
  29677. return AST_TEST_NOT_RUN;
  29678. case TEST_EXECUTE:
  29679. break;
  29680. }
  29681. /* Create the peer that we will retrieve. */
  29682. peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
  29683. if (!peer) {
  29684. return AST_TEST_FAIL;
  29685. }
  29686. peer->type = SIP_TYPE_USER;
  29687. peer->call_limit = 10;
  29688. ao2_link(peers, peer);
  29689. /* retrieve the chan_sip/peers tree and check the created peer. */
  29690. node = ast_data_get(&query);
  29691. if (!node) {
  29692. ao2_unlink(peers, peer);
  29693. ao2_ref(peer, -1);
  29694. return AST_TEST_FAIL;
  29695. }
  29696. /* compare item. */
  29697. if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
  29698. ao2_unlink(peers, peer);
  29699. ao2_ref(peer, -1);
  29700. ast_data_free(node);
  29701. return AST_TEST_FAIL;
  29702. }
  29703. if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
  29704. ao2_unlink(peers, peer);
  29705. ao2_ref(peer, -1);
  29706. ast_data_free(node);
  29707. return AST_TEST_FAIL;
  29708. }
  29709. if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
  29710. ao2_unlink(peers, peer);
  29711. ao2_ref(peer, -1);
  29712. ast_data_free(node);
  29713. return AST_TEST_FAIL;
  29714. }
  29715. /* release resources */
  29716. ast_data_free(node);
  29717. ao2_unlink(peers, peer);
  29718. ao2_ref(peer, -1);
  29719. return AST_TEST_PASS;
  29720. }
  29721. /*!
  29722. * \brief Imitation TCP reception loop
  29723. *
  29724. * This imitates the logic used by SIP's TCP code. Its purpose
  29725. * is to either
  29726. * 1) Combine fragments into a single message
  29727. * 2) Break up combined messages into single messages
  29728. *
  29729. * \param fragments The message fragments. This simulates the data received on a TCP socket.
  29730. * \param num_fragments This indicates the number of fragments to receive
  29731. * \param overflow This is a place to stash extra data if more than one message is received
  29732. * in a single fragment
  29733. * \param[out] messages The parsed messages are placed in this array
  29734. * \param[out] num_messages The number of messages that were parsed
  29735. * \param test Used for printing messages
  29736. * \retval 0 Success
  29737. * \retval -1 Failure
  29738. */
  29739. static int mock_tcp_loop(char *fragments[], size_t num_fragments,
  29740. struct ast_str **overflow, char **messages, int *num_messages, struct ast_test* test)
  29741. {
  29742. struct ast_str *req_data;
  29743. int i = 0;
  29744. int res = 0;
  29745. req_data = ast_str_create(128);
  29746. ast_str_reset(*overflow);
  29747. while (i < num_fragments || ast_str_strlen(*overflow) > 0) {
  29748. enum message_integrity message_integrity = MESSAGE_FRAGMENT;
  29749. ast_str_reset(req_data);
  29750. while (message_integrity == MESSAGE_FRAGMENT) {
  29751. if (ast_str_strlen(*overflow) > 0) {
  29752. ast_str_append(&req_data, 0, "%s", ast_str_buffer(*overflow));
  29753. ast_str_reset(*overflow);
  29754. } else {
  29755. ast_str_append(&req_data, 0, "%s", fragments[i++]);
  29756. }
  29757. message_integrity = check_message_integrity(&req_data, overflow);
  29758. }
  29759. if (strcmp(ast_str_buffer(req_data), messages[*num_messages])) {
  29760. ast_test_status_update(test, "Mismatch in SIP messages.\n");
  29761. ast_test_status_update(test, "Expected message:\n%s", messages[*num_messages]);
  29762. ast_test_status_update(test, "Parsed message:\n%s", ast_str_buffer(req_data));
  29763. res = -1;
  29764. goto end;
  29765. } else {
  29766. ast_test_status_update(test, "Successfully read message:\n%s", ast_str_buffer(req_data));
  29767. }
  29768. (*num_messages)++;
  29769. }
  29770. end:
  29771. ast_free(req_data);
  29772. return res;
  29773. };
  29774. AST_TEST_DEFINE(test_tcp_message_fragmentation)
  29775. {
  29776. /* Normal single message in one fragment */
  29777. char *normal[] = {
  29778. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29779. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29780. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29781. "To: <sip:bob@example.org:5060>\r\n"
  29782. "Call-ID: 12345\r\n"
  29783. "CSeq: 1 INVITE\r\n"
  29784. "Contact: sip:127.0.0.1:5061\r\n"
  29785. "Max-Forwards: 70\r\n"
  29786. "Content-Type: application/sdp\r\n"
  29787. "Content-Length: 130\r\n"
  29788. "\r\n"
  29789. "v=0\r\n"
  29790. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29791. "s=-\r\n"
  29792. "c=IN IP4 127.0.0.1\r\n"
  29793. "t=0 0\r\n"
  29794. "m=audio 10000 RTP/AVP 0\r\n"
  29795. "a=rtpmap:0 PCMU/8000\r\n"
  29796. };
  29797. /* Single message in two fragments.
  29798. * Fragments combine to make "normal"
  29799. */
  29800. char *fragmented[] = {
  29801. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29802. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29803. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29804. "To: <sip:bob@example.org:5060>\r\n"
  29805. "Call-ID: 12345\r\n"
  29806. "CSeq: 1 INVITE\r\n"
  29807. "Contact: sip:127.0.0.1:5061\r\n"
  29808. "Max-Forwards: ",
  29809. "70\r\n"
  29810. "Content-Type: application/sdp\r\n"
  29811. "Content-Length: 130\r\n"
  29812. "\r\n"
  29813. "v=0\r\n"
  29814. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29815. "s=-\r\n"
  29816. "c=IN IP4 127.0.0.1\r\n"
  29817. "t=0 0\r\n"
  29818. "m=audio 10000 RTP/AVP 0\r\n"
  29819. "a=rtpmap:0 PCMU/8000\r\n"
  29820. };
  29821. /* Single message in two fragments, divided precisely at the body
  29822. * Fragments combine to make "normal"
  29823. */
  29824. char *fragmented_body[] = {
  29825. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29826. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29827. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29828. "To: <sip:bob@example.org:5060>\r\n"
  29829. "Call-ID: 12345\r\n"
  29830. "CSeq: 1 INVITE\r\n"
  29831. "Contact: sip:127.0.0.1:5061\r\n"
  29832. "Max-Forwards: 70\r\n"
  29833. "Content-Type: application/sdp\r\n"
  29834. "Content-Length: 130\r\n"
  29835. "\r\n",
  29836. "v=0\r\n"
  29837. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29838. "s=-\r\n"
  29839. "c=IN IP4 127.0.0.1\r\n"
  29840. "t=0 0\r\n"
  29841. "m=audio 10000 RTP/AVP 0\r\n"
  29842. "a=rtpmap:0 PCMU/8000\r\n"
  29843. };
  29844. /* Single message in three fragments
  29845. * Fragments combine to make "normal"
  29846. */
  29847. char *multi_fragment[] = {
  29848. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29849. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29850. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29851. "To: <sip:bob@example.org:5060>\r\n"
  29852. "Call-ID: 12345\r\n"
  29853. "CSeq: 1 INVITE\r\n",
  29854. "Contact: sip:127.0.0.1:5061\r\n"
  29855. "Max-Forwards: 70\r\n"
  29856. "Content-Type: application/sdp\r\n"
  29857. "Content-Length: 130\r\n"
  29858. "\r\n"
  29859. "v=0\r\n"
  29860. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29861. "s=-\r\n"
  29862. "c=IN IP4",
  29863. " 127.0.0.1\r\n"
  29864. "t=0 0\r\n"
  29865. "m=audio 10000 RTP/AVP 0\r\n"
  29866. "a=rtpmap:0 PCMU/8000\r\n"
  29867. };
  29868. /* Two messages in a single fragment
  29869. * Fragments split into "multi_message_divided"
  29870. */
  29871. char *multi_message[] = {
  29872. "SIP/2.0 100 Trying\r\n"
  29873. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29874. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29875. "To: <sip:bob@example.org:5060>\r\n"
  29876. "Call-ID: 12345\r\n"
  29877. "CSeq: 1 INVITE\r\n"
  29878. "Contact: <sip:bob@example.org:5060>\r\n"
  29879. "Content-Length: 0\r\n"
  29880. "\r\n"
  29881. "SIP/2.0 180 Ringing\r\n"
  29882. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29883. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29884. "To: <sip:bob@example.org:5060>\r\n"
  29885. "Call-ID: 12345\r\n"
  29886. "CSeq: 1 INVITE\r\n"
  29887. "Contact: <sip:bob@example.org:5060>\r\n"
  29888. "Content-Length: 0\r\n"
  29889. "\r\n"
  29890. };
  29891. char *multi_message_divided[] = {
  29892. "SIP/2.0 100 Trying\r\n"
  29893. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29894. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29895. "To: <sip:bob@example.org:5060>\r\n"
  29896. "Call-ID: 12345\r\n"
  29897. "CSeq: 1 INVITE\r\n"
  29898. "Contact: <sip:bob@example.org:5060>\r\n"
  29899. "Content-Length: 0\r\n"
  29900. "\r\n",
  29901. "SIP/2.0 180 Ringing\r\n"
  29902. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29903. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29904. "To: <sip:bob@example.org:5060>\r\n"
  29905. "Call-ID: 12345\r\n"
  29906. "CSeq: 1 INVITE\r\n"
  29907. "Contact: <sip:bob@example.org:5060>\r\n"
  29908. "Content-Length: 0\r\n"
  29909. "\r\n"
  29910. };
  29911. /* Two messages with bodies combined into one fragment
  29912. * Fragments split into "multi_message_body_divided"
  29913. */
  29914. char *multi_message_body[] = {
  29915. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29916. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29917. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29918. "To: <sip:bob@example.org:5060>\r\n"
  29919. "Call-ID: 12345\r\n"
  29920. "CSeq: 1 INVITE\r\n"
  29921. "Contact: sip:127.0.0.1:5061\r\n"
  29922. "Max-Forwards: 70\r\n"
  29923. "Content-Type: application/sdp\r\n"
  29924. "Content-Length: 130\r\n"
  29925. "\r\n"
  29926. "v=0\r\n"
  29927. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29928. "s=-\r\n"
  29929. "c=IN IP4 127.0.0.1\r\n"
  29930. "t=0 0\r\n"
  29931. "m=audio 10000 RTP/AVP 0\r\n"
  29932. "a=rtpmap:0 PCMU/8000\r\n"
  29933. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29934. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29935. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29936. "To: <sip:bob@example.org:5060>\r\n"
  29937. "Call-ID: 12345\r\n"
  29938. "CSeq: 2 INVITE\r\n"
  29939. "Contact: sip:127.0.0.1:5061\r\n"
  29940. "Max-Forwards: 70\r\n"
  29941. "Content-Type: application/sdp\r\n"
  29942. "Content-Length: 130\r\n"
  29943. "\r\n"
  29944. "v=0\r\n"
  29945. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29946. "s=-\r\n"
  29947. "c=IN IP4 127.0.0.1\r\n"
  29948. "t=0 0\r\n"
  29949. "m=audio 10000 RTP/AVP 0\r\n"
  29950. "a=rtpmap:0 PCMU/8000\r\n"
  29951. };
  29952. char *multi_message_body_divided[] = {
  29953. "INVITE sip:bob@example.org SIP/2.0\r\n"
  29954. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29955. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29956. "To: <sip:bob@example.org:5060>\r\n"
  29957. "Call-ID: 12345\r\n"
  29958. "CSeq: 1 INVITE\r\n"
  29959. "Contact: sip:127.0.0.1:5061\r\n"
  29960. "Max-Forwards: 70\r\n"
  29961. "Content-Type: application/sdp\r\n"
  29962. "Content-Length: 130\r\n"
  29963. "\r\n"
  29964. "v=0\r\n"
  29965. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29966. "s=-\r\n"
  29967. "c=IN IP4 127.0.0.1\r\n"
  29968. "t=0 0\r\n"
  29969. "m=audio 10000 RTP/AVP 0\r\n"
  29970. "a=rtpmap:0 PCMU/8000\r\n",
  29971. "INVITE sip:bob@example.org SIP/2.0\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: 2 INVITE\r\n"
  29977. "Contact: sip:127.0.0.1:5061\r\n"
  29978. "Max-Forwards: 70\r\n"
  29979. "Content-Type: application/sdp\r\n"
  29980. "Content-Length: 130\r\n"
  29981. "\r\n"
  29982. "v=0\r\n"
  29983. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  29984. "s=-\r\n"
  29985. "c=IN IP4 127.0.0.1\r\n"
  29986. "t=0 0\r\n"
  29987. "m=audio 10000 RTP/AVP 0\r\n"
  29988. "a=rtpmap:0 PCMU/8000\r\n"
  29989. };
  29990. /* Two messages that appear in two fragments. Fragment
  29991. * boundaries do not align with message boundaries.
  29992. * Fragments combine to make "multi_message_divided"
  29993. */
  29994. char *multi_message_in_fragments[] = {
  29995. "SIP/2.0 100 Trying\r\n"
  29996. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  29997. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  29998. "To: <sip:bob@example.org:5060>\r\n"
  29999. "Call-ID: 12345\r\n"
  30000. "CSeq: 1 INVI",
  30001. "TE\r\n"
  30002. "Contact: <sip:bob@example.org:5060>\r\n"
  30003. "Content-Length: 0\r\n"
  30004. "\r\n"
  30005. "SIP/2.0 180 Ringing\r\n"
  30006. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30007. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30008. "To: <sip:bob@example.org:5060>\r\n"
  30009. "Call-ID: 12345\r\n"
  30010. "CSeq: 1 INVITE\r\n"
  30011. "Contact: <sip:bob@example.org:5060>\r\n"
  30012. "Content-Length: 0\r\n"
  30013. "\r\n"
  30014. };
  30015. /* Message with compact content-length header
  30016. * Same as "normal" but with compact content-length header
  30017. */
  30018. char *compact[] = {
  30019. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30020. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30021. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30022. "To: <sip:bob@example.org:5060>\r\n"
  30023. "Call-ID: 12345\r\n"
  30024. "CSeq: 1 INVITE\r\n"
  30025. "Contact: sip:127.0.0.1:5061\r\n"
  30026. "Max-Forwards: 70\r\n"
  30027. "Content-Type: application/sdp\r\n"
  30028. "l:130\r\n" /* intentionally no space */
  30029. "\r\n"
  30030. "v=0\r\n"
  30031. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30032. "s=-\r\n"
  30033. "c=IN IP4 127.0.0.1\r\n"
  30034. "t=0 0\r\n"
  30035. "m=audio 10000 RTP/AVP 0\r\n"
  30036. "a=rtpmap:0 PCMU/8000\r\n"
  30037. };
  30038. /* Message with faux content-length headers
  30039. * Same as "normal" but with extra fake content-length headers
  30040. */
  30041. char *faux[] = {
  30042. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30043. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30044. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30045. "To: <sip:bob@example.org:5060>\r\n"
  30046. "Call-ID: 12345\r\n"
  30047. "CSeq: 1 INVITE\r\n"
  30048. "Contact: sip:127.0.0.1:5061\r\n"
  30049. "Max-Forwards: 70\r\n"
  30050. "Content-Type: application/sdp\r\n"
  30051. "DisContent-Length: 0\r\n"
  30052. "MalContent-Length: 60\r\n"
  30053. "Content-Length:130\r\n" /* intentionally no space */
  30054. "\r\n"
  30055. "v=0\r\n"
  30056. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30057. "s=-\r\n"
  30058. "c=IN IP4 127.0.0.1\r\n"
  30059. "t=0 0\r\n"
  30060. "m=audio 10000 RTP/AVP 0\r\n"
  30061. "a=rtpmap:0 PCMU/8000\r\n"
  30062. };
  30063. /* Message with folded Content-Length header
  30064. * Message is "normal" with Content-Length spread across three lines
  30065. *
  30066. * This is the test that requires pedantic=yes in order to pass
  30067. */
  30068. char *folded[] = {
  30069. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30070. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30071. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30072. "To: <sip:bob@example.org:5060>\r\n"
  30073. "Call-ID: 12345\r\n"
  30074. "CSeq: 1 INVITE\r\n"
  30075. "Contact: sip:127.0.0.1:5061\r\n"
  30076. "Max-Forwards: 70\r\n"
  30077. "Content-Type: application/sdp\r\n"
  30078. "Content-Length: \t\r\n"
  30079. "\t \r\n"
  30080. " 130\t \r\n"
  30081. "\r\n"
  30082. "v=0\r\n"
  30083. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30084. "s=-\r\n"
  30085. "c=IN IP4 127.0.0.1\r\n"
  30086. "t=0 0\r\n"
  30087. "m=audio 10000 RTP/AVP 0\r\n"
  30088. "a=rtpmap:0 PCMU/8000\r\n"
  30089. };
  30090. /* Message with compact Content-length header in message and
  30091. * full Content-Length header in the body. Ensure that the header
  30092. * in the message is read and that the one in the body is ignored
  30093. */
  30094. char *cl_in_body[] = {
  30095. "INVITE sip:bob@example.org SIP/2.0\r\n"
  30096. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  30097. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  30098. "To: <sip:bob@example.org:5060>\r\n"
  30099. "Call-ID: 12345\r\n"
  30100. "CSeq: 1 INVITE\r\n"
  30101. "Contact: sip:127.0.0.1:5061\r\n"
  30102. "Max-Forwards: 70\r\n"
  30103. "Content-Type: application/sdp\r\n"
  30104. "l: 149\r\n"
  30105. "\r\n"
  30106. "v=0\r\n"
  30107. "Content-Length: 0\r\n"
  30108. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  30109. "s=-\r\n"
  30110. "c=IN IP4 127.0.0.1\r\n"
  30111. "t=0 0\r\n"
  30112. "m=audio 10000 RTP/AVP 0\r\n"
  30113. "a=rtpmap:0 PCMU/8000\r\n"
  30114. };
  30115. struct ast_str *overflow;
  30116. struct {
  30117. char **fragments;
  30118. char **expected;
  30119. int num_expected;
  30120. const char *description;
  30121. } tests[] = {
  30122. { normal, normal, 1, "normal" },
  30123. { fragmented, normal, 1, "fragmented" },
  30124. { fragmented_body, normal, 1, "fragmented_body" },
  30125. { multi_fragment, normal, 1, "multi_fragment" },
  30126. { multi_message, multi_message_divided, 2, "multi_message" },
  30127. { multi_message_body, multi_message_body_divided, 2, "multi_message_body" },
  30128. { multi_message_in_fragments, multi_message_divided, 2, "multi_message_in_fragments" },
  30129. { compact, compact, 1, "compact" },
  30130. { faux, faux, 1, "faux" },
  30131. { folded, folded, 1, "folded" },
  30132. { cl_in_body, cl_in_body, 1, "cl_in_body" },
  30133. };
  30134. int i;
  30135. enum ast_test_result_state res = AST_TEST_PASS;
  30136. switch (cmd) {
  30137. case TEST_INIT:
  30138. info->name = "sip_tcp_message_fragmentation";
  30139. info->category = "/main/sip/transport/";
  30140. info->summary = "SIP TCP message fragmentation test";
  30141. info->description =
  30142. "Tests reception of different TCP messages that have been fragmented or"
  30143. "run together. This test mimicks the code that TCP reception uses.";
  30144. return AST_TEST_NOT_RUN;
  30145. case TEST_EXECUTE:
  30146. break;
  30147. }
  30148. if (!sip_cfg.pedanticsipchecking) {
  30149. ast_log(LOG_WARNING, "Not running test. Pedantic SIP checking is not enabled, so it is guaranteed to fail\n");
  30150. return AST_TEST_NOT_RUN;
  30151. }
  30152. overflow = ast_str_create(128);
  30153. if (!overflow) {
  30154. return AST_TEST_FAIL;
  30155. }
  30156. for (i = 0; i < ARRAY_LEN(tests); ++i) {
  30157. int num_messages = 0;
  30158. if (mock_tcp_loop(tests[i].fragments, ARRAY_LEN(tests[i].fragments),
  30159. &overflow, tests[i].expected, &num_messages, test)) {
  30160. ast_test_status_update(test, "Failed to parse message '%s'\n", tests[i].description);
  30161. res = AST_TEST_FAIL;
  30162. break;
  30163. }
  30164. if (num_messages != tests[i].num_expected) {
  30165. ast_test_status_update(test, "Did not receive the expected number of messages. "
  30166. "Expected %d but received %d\n", tests[i].num_expected, num_messages);
  30167. res = AST_TEST_FAIL;
  30168. break;
  30169. }
  30170. }
  30171. ast_free(overflow);
  30172. return res;
  30173. }
  30174. AST_TEST_DEFINE(get_in_brackets_const_test)
  30175. {
  30176. const char *input;
  30177. const char *start = NULL;
  30178. int len = 0;
  30179. int res;
  30180. #define CHECK_RESULTS(in, expected_res, expected_start, expected_len) do { \
  30181. input = (in); \
  30182. res = get_in_brackets_const(input, &start, &len); \
  30183. if ((expected_res) != res) { \
  30184. ast_test_status_update(test, "Unexpected result: %d != %d\n", expected_res, res); \
  30185. return AST_TEST_FAIL; \
  30186. } \
  30187. if ((expected_start) != start) { \
  30188. const char *e = expected_start ? expected_start : "(null)"; \
  30189. const char *a = start ? start : "(null)"; \
  30190. ast_test_status_update(test, "Unexpected start: %s != %s\n", e, a); \
  30191. return AST_TEST_FAIL; \
  30192. } \
  30193. if ((expected_len) != len) { \
  30194. ast_test_status_update(test, "Unexpected len: %d != %d\n", expected_len, len); \
  30195. return AST_TEST_FAIL; \
  30196. } \
  30197. } while(0)
  30198. switch (cmd) {
  30199. case TEST_INIT:
  30200. info->name = __func__;
  30201. info->category = "/channels/chan_sip/";
  30202. info->summary = "get_in_brackets_const test";
  30203. info->description =
  30204. "Tests the get_in_brackets_const function";
  30205. return AST_TEST_NOT_RUN;
  30206. case TEST_EXECUTE:
  30207. break;
  30208. }
  30209. CHECK_RESULTS("", 1, NULL, -1);
  30210. CHECK_RESULTS("normal <test>", 0, input + 8, 4);
  30211. CHECK_RESULTS("\"normal\" <test>", 0, input + 10, 4);
  30212. CHECK_RESULTS("not normal <test", -1, NULL, -1);
  30213. CHECK_RESULTS("\"yes < really\" <test>", 0, input + 16, 4);
  30214. CHECK_RESULTS("\"even > this\" <test>", 0, input + 15, 4);
  30215. CHECK_RESULTS("<sip:id1@10.10.10.10;lr>", 0, input + 1, 22);
  30216. CHECK_RESULTS("<sip:id1@10.10.10.10;lr>, <sip:id1@10.10.10.20;lr>", 0, input + 1, 22);
  30217. CHECK_RESULTS("<sip:id1,id2@10.10.10.10;lr>", 0, input + 1, 26);
  30218. CHECK_RESULTS("<sip:id1@10., <sip:id2@10.10.10.10;lr>", 0, input + 1, 36);
  30219. CHECK_RESULTS("\"quoted text\" <sip:dlg1@10.10.10.10;lr>", 0, input + 15, 23);
  30220. return AST_TEST_PASS;
  30221. }
  30222. #endif
  30223. #define DATA_EXPORT_SIP_PEER(MEMBER) \
  30224. MEMBER(sip_peer, name, AST_DATA_STRING) \
  30225. MEMBER(sip_peer, secret, AST_DATA_PASSWORD) \
  30226. MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD) \
  30227. MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD) \
  30228. MEMBER(sip_peer, context, AST_DATA_STRING) \
  30229. MEMBER(sip_peer, subscribecontext, AST_DATA_STRING) \
  30230. MEMBER(sip_peer, username, AST_DATA_STRING) \
  30231. MEMBER(sip_peer, accountcode, AST_DATA_STRING) \
  30232. MEMBER(sip_peer, tohost, AST_DATA_STRING) \
  30233. MEMBER(sip_peer, regexten, AST_DATA_STRING) \
  30234. MEMBER(sip_peer, fromuser, AST_DATA_STRING) \
  30235. MEMBER(sip_peer, fromdomain, AST_DATA_STRING) \
  30236. MEMBER(sip_peer, fullcontact, AST_DATA_STRING) \
  30237. MEMBER(sip_peer, cid_num, AST_DATA_STRING) \
  30238. MEMBER(sip_peer, cid_name, AST_DATA_STRING) \
  30239. MEMBER(sip_peer, vmexten, AST_DATA_STRING) \
  30240. MEMBER(sip_peer, language, AST_DATA_STRING) \
  30241. MEMBER(sip_peer, mohinterpret, AST_DATA_STRING) \
  30242. MEMBER(sip_peer, mohsuggest, AST_DATA_STRING) \
  30243. MEMBER(sip_peer, parkinglot, AST_DATA_STRING) \
  30244. MEMBER(sip_peer, useragent, AST_DATA_STRING) \
  30245. MEMBER(sip_peer, mwi_from, AST_DATA_STRING) \
  30246. MEMBER(sip_peer, engine, AST_DATA_STRING) \
  30247. MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING) \
  30248. MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN) \
  30249. MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN) \
  30250. MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN) \
  30251. MEMBER(sip_peer, inuse, AST_DATA_INTEGER) \
  30252. MEMBER(sip_peer, ringing, AST_DATA_INTEGER) \
  30253. MEMBER(sip_peer, onhold, AST_DATA_INTEGER) \
  30254. MEMBER(sip_peer, call_limit, AST_DATA_INTEGER) \
  30255. MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER) \
  30256. MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
  30257. MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS) \
  30258. MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
  30259. MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS) \
  30260. MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS) \
  30261. MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS) \
  30262. MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS) \
  30263. MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS) \
  30264. MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS) \
  30265. MEMBER(sip_peer, description, AST_DATA_STRING)
  30266. AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
  30267. static int peers_data_provider_get(const struct ast_data_search *search,
  30268. struct ast_data *data_root)
  30269. {
  30270. struct sip_peer *peer;
  30271. struct ao2_iterator i;
  30272. struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
  30273. struct ast_data *data_sip_options;
  30274. int total_mailboxes, x;
  30275. struct sip_mailbox *mailbox;
  30276. i = ao2_iterator_init(peers, 0);
  30277. while ((peer = ao2_iterator_next(&i))) {
  30278. ao2_lock(peer);
  30279. data_peer = ast_data_add_node(data_root, "peer");
  30280. if (!data_peer) {
  30281. ao2_unlock(peer);
  30282. ao2_ref(peer, -1);
  30283. continue;
  30284. }
  30285. ast_data_add_structure(sip_peer, data_peer, peer);
  30286. /* transfer mode */
  30287. enum_node = ast_data_add_node(data_peer, "allowtransfer");
  30288. if (!enum_node) {
  30289. ao2_unlock(peer);
  30290. ao2_ref(peer, -1);
  30291. continue;
  30292. }
  30293. ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
  30294. ast_data_add_int(enum_node, "value", peer->allowtransfer);
  30295. /* transports */
  30296. ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
  30297. /* peer type */
  30298. if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
  30299. ast_data_add_str(data_peer, "type", "friend");
  30300. } else if (peer->type & SIP_TYPE_PEER) {
  30301. ast_data_add_str(data_peer, "type", "peer");
  30302. } else if (peer->type & SIP_TYPE_USER) {
  30303. ast_data_add_str(data_peer, "type", "user");
  30304. }
  30305. /* mailboxes */
  30306. total_mailboxes = 0;
  30307. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  30308. if (!total_mailboxes) {
  30309. data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
  30310. if (!data_peer_mailboxes) {
  30311. break;
  30312. }
  30313. total_mailboxes++;
  30314. }
  30315. data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
  30316. if (!data_peer_mailbox) {
  30317. continue;
  30318. }
  30319. ast_data_add_str(data_peer_mailbox, "id", mailbox->id);
  30320. }
  30321. /* amaflags */
  30322. enum_node = ast_data_add_node(data_peer, "amaflags");
  30323. if (!enum_node) {
  30324. ao2_unlock(peer);
  30325. ao2_ref(peer, -1);
  30326. continue;
  30327. }
  30328. ast_data_add_int(enum_node, "value", peer->amaflags);
  30329. ast_data_add_str(enum_node, "text", ast_channel_amaflags2string(peer->amaflags));
  30330. /* sip options */
  30331. data_sip_options = ast_data_add_node(data_peer, "sipoptions");
  30332. if (!data_sip_options) {
  30333. ao2_unlock(peer);
  30334. ao2_ref(peer, -1);
  30335. continue;
  30336. }
  30337. for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
  30338. ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
  30339. }
  30340. /* callingpres */
  30341. enum_node = ast_data_add_node(data_peer, "callingpres");
  30342. if (!enum_node) {
  30343. ao2_unlock(peer);
  30344. ao2_ref(peer, -1);
  30345. continue;
  30346. }
  30347. ast_data_add_int(enum_node, "value", peer->callingpres);
  30348. ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
  30349. /* codecs */
  30350. ast_data_add_codecs(data_peer, "codecs", peer->caps);
  30351. if (!ast_data_search_match(search, data_peer)) {
  30352. ast_data_remove_node(data_root, data_peer);
  30353. }
  30354. ao2_unlock(peer);
  30355. ao2_ref(peer, -1);
  30356. }
  30357. ao2_iterator_destroy(&i);
  30358. return 0;
  30359. }
  30360. static const struct ast_data_handler peers_data_provider = {
  30361. .version = AST_DATA_HANDLER_VERSION,
  30362. .get = peers_data_provider_get
  30363. };
  30364. static const struct ast_data_entry sip_data_providers[] = {
  30365. AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
  30366. };
  30367. static const struct ast_sip_api_tech chan_sip_api_provider = {
  30368. .version = AST_SIP_API_VERSION,
  30369. .name = "chan_sip",
  30370. .sipinfo_send = sipinfo_send,
  30371. };
  30372. static int unload_module(void);
  30373. /*!
  30374. * \brief Load the module
  30375. *
  30376. * Module loading including tests for configuration or dependencies.
  30377. * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
  30378. * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
  30379. * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
  30380. * configuration file or other non-critical problem return
  30381. * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
  30382. */
  30383. static int load_module(void)
  30384. {
  30385. ast_verbose("SIP channel loading...\n");
  30386. if (STASIS_MESSAGE_TYPE_INIT(session_timeout_type)) {
  30387. unload_module();
  30388. return AST_MODULE_LOAD_FAILURE;
  30389. }
  30390. if (!(sip_tech.capabilities = ast_format_cap_alloc(0))) {
  30391. unload_module();
  30392. return AST_MODULE_LOAD_FAILURE;
  30393. }
  30394. if (ast_sip_api_provider_register(&chan_sip_api_provider)) {
  30395. unload_module();
  30396. return AST_MODULE_LOAD_FAILURE;
  30397. }
  30398. /* the fact that ao2_containers can't resize automatically is a major worry! */
  30399. /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
  30400. peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
  30401. peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
  30402. dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
  30403. dialogs_needdestroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_needdestroy");
  30404. dialogs_rtpcheck = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs for rtpchecks");
  30405. threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
  30406. if (!peers || !peers_by_ip || !dialogs || !dialogs_needdestroy || !dialogs_rtpcheck
  30407. || !threadt) {
  30408. ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
  30409. unload_module();
  30410. return AST_MODULE_LOAD_FAILURE;
  30411. }
  30412. if (!(sip_cfg.caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  30413. unload_module();
  30414. return AST_MODULE_LOAD_FAILURE;
  30415. }
  30416. ast_format_cap_append_by_type(sip_tech.capabilities, AST_MEDIA_TYPE_AUDIO);
  30417. registry_list = ao2_t_container_alloc(HASH_REGISTRY_SIZE, registry_hash_cb, registry_cmp_cb, "allocate registry_list");
  30418. subscription_mwi_list = ao2_t_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX,
  30419. AO2_CONTAINER_ALLOC_OPT_INSERT_BEGIN, NULL, NULL, "allocate subscription_mwi_list");
  30420. if (!(sched = ast_sched_context_create())) {
  30421. ast_log(LOG_ERROR, "Unable to create scheduler context\n");
  30422. unload_module();
  30423. return AST_MODULE_LOAD_FAILURE;
  30424. }
  30425. if (!(io = io_context_create())) {
  30426. ast_log(LOG_ERROR, "Unable to create I/O context\n");
  30427. unload_module();
  30428. return AST_MODULE_LOAD_FAILURE;
  30429. }
  30430. sip_reloadreason = CHANNEL_MODULE_LOAD;
  30431. can_parse_xml = sip_is_xml_parsable();
  30432. if (reload_config(sip_reloadreason)) { /* Load the configuration from sip.conf */
  30433. unload_module();
  30434. return AST_MODULE_LOAD_DECLINE;
  30435. }
  30436. /* Initialize bogus peer. Can be done first after reload_config() */
  30437. if (!(bogus_peer = temp_peer("(bogus_peer)"))) {
  30438. ast_log(LOG_ERROR, "Unable to create bogus_peer for authentication\n");
  30439. unload_module();
  30440. return AST_MODULE_LOAD_FAILURE;
  30441. }
  30442. /* Make sure the auth will always fail. */
  30443. ast_string_field_set(bogus_peer, md5secret, BOGUS_PEER_MD5SECRET);
  30444. ast_clear_flag(&bogus_peer->flags[0], SIP_INSECURE);
  30445. /* Prepare the version that does not require DTMF BEGIN frames.
  30446. * We need to use tricks such as memcpy and casts because the variable
  30447. * has const fields.
  30448. */
  30449. memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
  30450. memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
  30451. if (ast_msg_tech_register(&sip_msg_tech)) {
  30452. unload_module();
  30453. return AST_MODULE_LOAD_FAILURE;
  30454. }
  30455. /* Make sure we can register our sip channel type */
  30456. if (ast_channel_register(&sip_tech)) {
  30457. ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
  30458. unload_module();
  30459. return AST_MODULE_LOAD_FAILURE;
  30460. }
  30461. #ifdef TEST_FRAMEWORK
  30462. AST_TEST_REGISTER(test_sip_peers_get);
  30463. AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
  30464. AST_TEST_REGISTER(test_tcp_message_fragmentation);
  30465. AST_TEST_REGISTER(get_in_brackets_const_test);
  30466. #endif
  30467. /* Register AstData providers */
  30468. ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
  30469. /* Register all CLI functions for SIP */
  30470. ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
  30471. /* Tell the RTP engine about our RTP glue */
  30472. ast_rtp_glue_register(&sip_rtp_glue);
  30473. /* Register dialplan applications */
  30474. ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
  30475. ast_register_application_xml(app_sipaddheader, sip_addheader);
  30476. ast_register_application_xml(app_sipremoveheader, sip_removeheader);
  30477. #ifdef TEST_FRAMEWORK
  30478. ast_register_application_xml(app_sipsendcustominfo, sip_sendcustominfo);
  30479. #endif
  30480. /* Register dialplan functions */
  30481. ast_custom_function_register(&sip_header_function);
  30482. ast_custom_function_register(&sippeer_function);
  30483. ast_custom_function_register(&checksipdomain_function);
  30484. /* Register manager commands */
  30485. ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
  30486. ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
  30487. ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
  30488. ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
  30489. ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
  30490. ast_manager_register_xml("SIPpeerstatus", EVENT_FLAG_SYSTEM, manager_sip_peer_status);
  30491. sip_poke_all_peers();
  30492. sip_keepalive_all_peers();
  30493. sip_send_all_registers();
  30494. sip_send_all_mwi_subscriptions();
  30495. initialize_escs();
  30496. if (sip_epa_register(&cc_epa_static_data)) {
  30497. unload_module();
  30498. return AST_MODULE_LOAD_DECLINE;
  30499. }
  30500. if (sip_reqresp_parser_init() == -1) {
  30501. ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
  30502. unload_module();
  30503. return AST_MODULE_LOAD_DECLINE;
  30504. }
  30505. if (can_parse_xml) {
  30506. /* SIP CC agents require the ability to parse XML PIDF bodies
  30507. * in incoming PUBLISH requests
  30508. */
  30509. if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
  30510. unload_module();
  30511. return AST_MODULE_LOAD_DECLINE;
  30512. }
  30513. }
  30514. if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
  30515. unload_module();
  30516. return AST_MODULE_LOAD_DECLINE;
  30517. }
  30518. if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
  30519. unload_module();
  30520. return AST_MODULE_LOAD_DECLINE;
  30521. }
  30522. /* And start the monitor for the first time */
  30523. restart_monitor();
  30524. ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
  30525. "name", RQ_CHAR, 10,
  30526. "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
  30527. "port", RQ_UINTEGER2, 5,
  30528. "regseconds", RQ_INTEGER4, 11,
  30529. "defaultuser", RQ_CHAR, 10,
  30530. "fullcontact", RQ_CHAR, 35,
  30531. "regserver", RQ_CHAR, 20,
  30532. "useragent", RQ_CHAR, 20,
  30533. "lastms", RQ_INTEGER4, 11,
  30534. SENTINEL);
  30535. sip_register_tests();
  30536. network_change_stasis_subscribe();
  30537. ast_websocket_add_protocol("sip", sip_websocket_callback);
  30538. return AST_MODULE_LOAD_SUCCESS;
  30539. }
  30540. /*! \brief PBX unload module API */
  30541. static int unload_module(void)
  30542. {
  30543. struct sip_pvt *p;
  30544. struct sip_threadinfo *th;
  30545. struct ast_context *con;
  30546. struct ao2_iterator i;
  30547. int wait_count;
  30548. ast_sip_api_provider_unregister();
  30549. ast_websocket_remove_protocol("sip", sip_websocket_callback);
  30550. network_change_stasis_unsubscribe();
  30551. acl_change_event_stasis_unsubscribe();
  30552. ast_sched_dump(sched);
  30553. /* First, take us out of the channel type list */
  30554. ast_channel_unregister(&sip_tech);
  30555. ast_msg_tech_unregister(&sip_msg_tech);
  30556. /* Unregister dial plan functions */
  30557. ast_custom_function_unregister(&sippeer_function);
  30558. ast_custom_function_unregister(&sip_header_function);
  30559. ast_custom_function_unregister(&checksipdomain_function);
  30560. /* Unregister dial plan applications */
  30561. ast_unregister_application(app_dtmfmode);
  30562. ast_unregister_application(app_sipaddheader);
  30563. ast_unregister_application(app_sipremoveheader);
  30564. #ifdef TEST_FRAMEWORK
  30565. ast_unregister_application(app_sipsendcustominfo);
  30566. AST_TEST_UNREGISTER(test_sip_peers_get);
  30567. AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
  30568. AST_TEST_UNREGISTER(test_tcp_message_fragmentation);
  30569. AST_TEST_UNREGISTER(get_in_brackets_const_test);
  30570. #endif
  30571. /* Unregister all the AstData providers */
  30572. ast_data_unregister(NULL);
  30573. /* Unregister CLI commands */
  30574. ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
  30575. /* Disconnect from RTP engine */
  30576. ast_rtp_glue_unregister(&sip_rtp_glue);
  30577. /* Unregister AMI actions */
  30578. ast_manager_unregister("SIPpeers");
  30579. ast_manager_unregister("SIPshowpeer");
  30580. ast_manager_unregister("SIPqualifypeer");
  30581. ast_manager_unregister("SIPshowregistry");
  30582. ast_manager_unregister("SIPnotify");
  30583. ast_manager_unregister("SIPpeerstatus");
  30584. /* Kill TCP/TLS server threads */
  30585. if (sip_tcp_desc.master) {
  30586. ast_tcptls_server_stop(&sip_tcp_desc);
  30587. }
  30588. if (sip_tls_desc.master) {
  30589. ast_tcptls_server_stop(&sip_tls_desc);
  30590. }
  30591. ast_ssl_teardown(sip_tls_desc.tls_cfg);
  30592. /* Kill all existing TCP/TLS threads */
  30593. i = ao2_iterator_init(threadt, 0);
  30594. while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
  30595. pthread_t thread = th->threadid;
  30596. th->stop = 1;
  30597. pthread_kill(thread, SIGURG);
  30598. ao2_t_ref(th, -1, "decrement ref from iterator");
  30599. }
  30600. ao2_iterator_destroy(&i);
  30601. /* Hangup all dialogs if they have an owner */
  30602. i = ao2_iterator_init(dialogs, 0);
  30603. while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  30604. if (p->owner)
  30605. ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
  30606. ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
  30607. }
  30608. ao2_iterator_destroy(&i);
  30609. unlink_all_peers_from_tables();
  30610. ast_mutex_lock(&monlock);
  30611. if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
  30612. pthread_t th = monitor_thread;
  30613. monitor_thread = AST_PTHREADT_STOP;
  30614. pthread_cancel(th);
  30615. pthread_kill(th, SIGURG);
  30616. ast_mutex_unlock(&monlock);
  30617. pthread_join(th, NULL);
  30618. } else {
  30619. monitor_thread = AST_PTHREADT_STOP;
  30620. ast_mutex_unlock(&monlock);
  30621. }
  30622. /* Destroy all the dialogs and free their memory */
  30623. i = ao2_iterator_init(dialogs, 0);
  30624. while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  30625. dialog_unlink_all(p);
  30626. ao2_t_ref(p, -1, "throw away iterator result");
  30627. }
  30628. ao2_iterator_destroy(&i);
  30629. /* Free memory for local network address mask */
  30630. ast_free_ha(localaddr);
  30631. ast_mutex_lock(&authl_lock);
  30632. if (authl) {
  30633. ao2_t_cleanup(authl, "Removing global authentication");
  30634. authl = NULL;
  30635. }
  30636. ast_mutex_unlock(&authl_lock);
  30637. sip_epa_unregister_all();
  30638. destroy_escs();
  30639. ast_free(default_tls_cfg.certfile);
  30640. ast_free(default_tls_cfg.pvtfile);
  30641. ast_free(default_tls_cfg.cipher);
  30642. ast_free(default_tls_cfg.cafile);
  30643. ast_free(default_tls_cfg.capath);
  30644. cleanup_all_regs();
  30645. ao2_cleanup(registry_list);
  30646. {
  30647. struct ao2_iterator iter;
  30648. struct sip_subscription_mwi *iterator;
  30649. iter = ao2_iterator_init(subscription_mwi_list, 0);
  30650. while ((iterator = ao2_t_iterator_next(&iter, "unload_module iter"))) {
  30651. ao2_lock(iterator);
  30652. if (iterator->dnsmgr) {
  30653. ast_dnsmgr_release(iterator->dnsmgr);
  30654. iterator->dnsmgr = NULL;
  30655. ao2_t_ref(iterator, -1, "dnsmgr release");
  30656. }
  30657. ao2_unlock(iterator);
  30658. ao2_t_ref(iterator, -1, "unload_module iter");
  30659. }
  30660. ao2_iterator_destroy(&iter);
  30661. }
  30662. ao2_cleanup(subscription_mwi_list);
  30663. /*
  30664. * Wait awhile for the TCP/TLS thread container to become empty.
  30665. *
  30666. * XXX This is a hack, but the worker threads cannot be created
  30667. * joinable. They can die on their own and remove themselves
  30668. * from the container thus resulting in a huge memory leak.
  30669. */
  30670. wait_count = 1000;
  30671. while (ao2_container_count(threadt) && --wait_count) {
  30672. sched_yield();
  30673. }
  30674. if (!wait_count) {
  30675. ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
  30676. }
  30677. ao2_t_cleanup(bogus_peer, "unref the bogus_peer");
  30678. ao2_t_cleanup(peers, "unref the peers table");
  30679. ao2_t_cleanup(peers_by_ip, "unref the peers_by_ip table");
  30680. ao2_t_cleanup(dialogs, "unref the dialogs table");
  30681. ao2_t_cleanup(dialogs_needdestroy, "unref dialogs_needdestroy");
  30682. ao2_t_cleanup(dialogs_rtpcheck, "unref dialogs_rtpcheck");
  30683. ao2_t_cleanup(threadt, "unref the thread table");
  30684. ao2_t_cleanup(sip_monitor_instances, "unref the sip_monitor_instances table");
  30685. clear_sip_domains();
  30686. sip_cfg.contact_acl = ast_free_acl_list(sip_cfg.contact_acl);
  30687. if (sipsock_read_id) {
  30688. ast_io_remove(io, sipsock_read_id);
  30689. sipsock_read_id = NULL;
  30690. }
  30691. close(sipsock);
  30692. io_context_destroy(io);
  30693. ast_sched_context_destroy(sched);
  30694. con = ast_context_find(used_context);
  30695. if (con) {
  30696. ast_context_destroy(con, "SIP");
  30697. }
  30698. ast_unload_realtime("sipregs");
  30699. ast_unload_realtime("sippeers");
  30700. ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
  30701. ast_cc_agent_unregister(&sip_cc_agent_callbacks);
  30702. sip_reqresp_parser_exit();
  30703. sip_unregister_tests();
  30704. if (notify_types) {
  30705. ast_config_destroy(notify_types);
  30706. notify_types = NULL;
  30707. }
  30708. ao2_cleanup(sip_tech.capabilities);
  30709. sip_tech.capabilities = NULL;
  30710. ao2_cleanup(sip_cfg.caps);
  30711. sip_cfg.caps = NULL;
  30712. STASIS_MESSAGE_TYPE_CLEANUP(session_timeout_type);
  30713. return 0;
  30714. }
  30715. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
  30716. .support_level = AST_MODULE_SUPPORT_CORE,
  30717. .load = load_module,
  30718. .unload = unload_module,
  30719. .reload = reload,
  30720. .load_pri = AST_MODPRI_CHANNEL_DRIVER,
  30721. .nonoptreq = "res_crypto,res_http_websocket",
  30722. );