chan_sip.c 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163
  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. /*!
  94. * \page sip_tcp_tls SIP TCP and TLS support
  95. *
  96. * \par tcpfixes TCP implementation changes needed
  97. * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
  98. * \todo Save TCP/TLS sessions in registry
  99. * If someone registers a SIPS uri, this forces us to set up a TLS connection back.
  100. * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
  101. * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
  102. * The tcpbindaddr config option should only be used to open ADDITIONAL ports
  103. * So we should propably go back to
  104. * bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
  105. * if tlsenable=yes, open TLS port (provided we also have cert)
  106. * tcpbindaddr = extra address for additional TCP connections
  107. * tlsbindaddr = extra address for additional TCP/TLS connections
  108. * udpbindaddr = extra address for additional UDP connections
  109. * These three options should take multiple IP/port pairs
  110. * Note: Since opening additional listen sockets is a *new* feature we do not have today
  111. * the XXXbindaddr options needs to be disabled until we have support for it
  112. *
  113. * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
  114. * thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
  115. * even if udp is the configured first transport.
  116. *
  117. * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
  118. * specially to communication with other peers (proxies).
  119. * \todo We need to test TCP sessions with SIP proxies and in regards
  120. * to the SIP outbound specs.
  121. * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
  122. *
  123. * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
  124. * message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
  125. * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
  126. * multiple domains in our TLS implementation, meaning one socket and one cert per domain
  127. * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
  128. * also considering outbound proxy options.
  129. * First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port: DNS naptr, srv, AAA)
  130. * Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
  131. * DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
  132. * Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
  133. * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
  134. * devices directly from the dialplan. UDP is only a fallback if no other method works,
  135. * in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
  136. * MTU (like INIVTE with video, audio and RTT) TCP should be preferred.
  137. *
  138. * When dialling unconfigured peers (with no port number) or devices in external domains
  139. * NAPTR records MUST be consulted to find configured transport. If they are not found,
  140. * SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
  141. * If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
  142. * \note this only applies if there's no outbound proxy configured for the session. If an outbound
  143. * proxy is configured, these procedures might apply for locating the proxy and determining
  144. * the transport to use for communication with the proxy.
  145. * \par Other bugs to fix ----
  146. * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
  147. * - sets TLS port as default for all TCP connections, unless other port is given in contact.
  148. * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
  149. * - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
  150. * a bad guess.
  151. * - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
  152. * get_destination(struct sip_pvt *p, struct sip_request *oreq)
  153. * - Doesn't store the information that we got an incoming SIPS request in the channel, so that
  154. * we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
  155. * fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
  156. * channel variable in the dialplan.
  157. * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
  158. * - As above, if we have a SIPS: uri in the refer-to header
  159. * - Does not check transport in refer_to uri.
  160. */
  161. /*** MODULEINFO
  162. <use>res_crypto</use>
  163. <depend>chan_local</depend>
  164. <support_level>core</support_level>
  165. ***/
  166. /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
  167. The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
  168. refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
  169. request at a negotiated interval. If a session refresh fails then all the entities that support Session-
  170. Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
  171. the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
  172. that do not support Session-Timers).
  173. The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
  174. per-peer settings override the global settings. The following new parameters have been
  175. added to the sip.conf file.
  176. session-timers=["accept", "originate", "refuse"]
  177. session-expires=[integer]
  178. session-minse=[integer]
  179. session-refresher=["uas", "uac"]
  180. The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
  181. Asterisk. The Asterisk can be configured in one of the following three modes:
  182. 1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
  183. made by remote end-points. A remote end-point can request Asterisk to engage
  184. session-timers by either sending it an INVITE request with a "Supported: timer"
  185. header in it or by responding to Asterisk's INVITE with a 200 OK that contains
  186. Session-Expires: header in it. In this mode, the Asterisk server does not
  187. request session-timers from remote end-points. This is the default mode.
  188. 2. Originate :: In the "originate" mode, the Asterisk server requests the remote
  189. end-points to activate session-timers in addition to honoring such requests
  190. made by the remote end-pints. In order to get as much protection as possible
  191. against hanging SIP channels due to network or end-point failures, Asterisk
  192. resends periodic re-INVITEs even if a remote end-point does not support
  193. the session-timers feature.
  194. 3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
  195. timers for inbound or outbound requests. If a remote end-point requests
  196. session-timers in a dialog, then Asterisk ignores that request unless it's
  197. noted as a requirement (Require: header), in which case the INVITE is
  198. rejected with a 420 Bad Extension response.
  199. */
  200. #include "asterisk.h"
  201. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  202. #include <signal.h>
  203. #include <sys/signal.h>
  204. #include <regex.h>
  205. #include <inttypes.h>
  206. #include "asterisk/network.h"
  207. #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
  208. #include "asterisk/lock.h"
  209. #include "asterisk/config.h"
  210. #include "asterisk/module.h"
  211. #include "asterisk/pbx.h"
  212. #include "asterisk/sched.h"
  213. #include "asterisk/io.h"
  214. #include "asterisk/rtp_engine.h"
  215. #include "asterisk/udptl.h"
  216. #include "asterisk/acl.h"
  217. #include "asterisk/manager.h"
  218. #include "asterisk/callerid.h"
  219. #include "asterisk/cli.h"
  220. #include "asterisk/musiconhold.h"
  221. #include "asterisk/dsp.h"
  222. #include "asterisk/features.h"
  223. #include "asterisk/srv.h"
  224. #include "asterisk/astdb.h"
  225. #include "asterisk/causes.h"
  226. #include "asterisk/utils.h"
  227. #include "asterisk/file.h"
  228. #include "asterisk/astobj2.h"
  229. #include "asterisk/dnsmgr.h"
  230. #include "asterisk/devicestate.h"
  231. #include "asterisk/monitor.h"
  232. #include "asterisk/netsock2.h"
  233. #include "asterisk/localtime.h"
  234. #include "asterisk/abstract_jb.h"
  235. #include "asterisk/threadstorage.h"
  236. #include "asterisk/translate.h"
  237. #include "asterisk/ast_version.h"
  238. #include "asterisk/event.h"
  239. #include "asterisk/cel.h"
  240. #include "asterisk/data.h"
  241. #include "asterisk/aoc.h"
  242. #include "sip/include/sip.h"
  243. #include "sip/include/globals.h"
  244. #include "sip/include/config_parser.h"
  245. #include "sip/include/reqresp_parser.h"
  246. #include "sip/include/sip_utils.h"
  247. #include "sip/include/srtp.h"
  248. #include "sip/include/sdp_crypto.h"
  249. #include "asterisk/ccss.h"
  250. #include "asterisk/xml.h"
  251. #include "sip/include/dialog.h"
  252. #include "sip/include/dialplan_functions.h"
  253. /*** DOCUMENTATION
  254. <application name="SIPDtmfMode" language="en_US">
  255. <synopsis>
  256. Change the dtmfmode for a SIP call.
  257. </synopsis>
  258. <syntax>
  259. <parameter name="mode" required="true">
  260. <enumlist>
  261. <enum name="inband" />
  262. <enum name="info" />
  263. <enum name="rfc2833" />
  264. </enumlist>
  265. </parameter>
  266. </syntax>
  267. <description>
  268. <para>Changes the dtmfmode for a SIP call.</para>
  269. </description>
  270. </application>
  271. <application name="SIPAddHeader" language="en_US">
  272. <synopsis>
  273. Add a SIP header to the outbound call.
  274. </synopsis>
  275. <syntax argsep=":">
  276. <parameter name="Header" required="true" />
  277. <parameter name="Content" required="true" />
  278. </syntax>
  279. <description>
  280. <para>Adds a header to a SIP call placed with DIAL.</para>
  281. <para>Remember to use the X-header if you are adding non-standard SIP
  282. headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
  283. Adding the wrong headers may jeopardize the SIP dialog.</para>
  284. <para>Always returns <literal>0</literal>.</para>
  285. </description>
  286. </application>
  287. <application name="SIPRemoveHeader" language="en_US">
  288. <synopsis>
  289. Remove SIP headers previously added with SIPAddHeader
  290. </synopsis>
  291. <syntax>
  292. <parameter name="Header" required="false" />
  293. </syntax>
  294. <description>
  295. <para>SIPRemoveHeader() allows you to remove headers which were previously
  296. added with SIPAddHeader(). If no parameter is supplied, all previously added
  297. headers will be removed. If a parameter is supplied, only the matching headers
  298. will be removed.</para>
  299. <para>For example you have added these 2 headers:</para>
  300. <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
  301. <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
  302. <para></para>
  303. <para>// remove all headers</para>
  304. <para>SIPRemoveHeader();</para>
  305. <para>// remove all P- headers</para>
  306. <para>SIPRemoveHeader(P-);</para>
  307. <para>// remove only the PAI header (note the : at the end)</para>
  308. <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
  309. <para></para>
  310. <para>Always returns <literal>0</literal>.</para>
  311. </description>
  312. </application>
  313. <function name="SIP_HEADER" language="en_US">
  314. <synopsis>
  315. Gets the specified SIP header from an incoming INVITE message.
  316. </synopsis>
  317. <syntax>
  318. <parameter name="name" required="true" />
  319. <parameter name="number">
  320. <para>If not specified, defaults to <literal>1</literal>.</para>
  321. </parameter>
  322. </syntax>
  323. <description>
  324. <para>Since there are several headers (such as Via) which can occur multiple
  325. times, SIP_HEADER takes an optional second argument to specify which header with
  326. that name to retrieve. Headers start at offset <literal>1</literal>.</para>
  327. </description>
  328. </function>
  329. <function name="SIPPEER" language="en_US">
  330. <synopsis>
  331. Gets SIP peer information.
  332. </synopsis>
  333. <syntax>
  334. <parameter name="peername" required="true" />
  335. <parameter name="item">
  336. <enumlist>
  337. <enum name="ip">
  338. <para>(default) The ip address.</para>
  339. </enum>
  340. <enum name="port">
  341. <para>The port number.</para>
  342. </enum>
  343. <enum name="mailbox">
  344. <para>The configured mailbox.</para>
  345. </enum>
  346. <enum name="context">
  347. <para>The configured context.</para>
  348. </enum>
  349. <enum name="expire">
  350. <para>The epoch time of the next expire.</para>
  351. </enum>
  352. <enum name="dynamic">
  353. <para>Is it dynamic? (yes/no).</para>
  354. </enum>
  355. <enum name="callerid_name">
  356. <para>The configured Caller ID name.</para>
  357. </enum>
  358. <enum name="callerid_num">
  359. <para>The configured Caller ID number.</para>
  360. </enum>
  361. <enum name="callgroup">
  362. <para>The configured Callgroup.</para>
  363. </enum>
  364. <enum name="pickupgroup">
  365. <para>The configured Pickupgroup.</para>
  366. </enum>
  367. <enum name="codecs">
  368. <para>The configured codecs.</para>
  369. </enum>
  370. <enum name="status">
  371. <para>Status (if qualify=yes).</para>
  372. </enum>
  373. <enum name="regexten">
  374. <para>Registration extension.</para>
  375. </enum>
  376. <enum name="limit">
  377. <para>Call limit (call-limit).</para>
  378. </enum>
  379. <enum name="busylevel">
  380. <para>Configured call level for signalling busy.</para>
  381. </enum>
  382. <enum name="curcalls">
  383. <para>Current amount of calls. Only available if call-limit is set.</para>
  384. </enum>
  385. <enum name="language">
  386. <para>Default language for peer.</para>
  387. </enum>
  388. <enum name="accountcode">
  389. <para>Account code for this peer.</para>
  390. </enum>
  391. <enum name="useragent">
  392. <para>Current user agent id for peer.</para>
  393. </enum>
  394. <enum name="maxforwards">
  395. <para>The value used for SIP loop prevention in outbound requests</para>
  396. </enum>
  397. <enum name="chanvar[name]">
  398. <para>A channel variable configured with setvar for this peer.</para>
  399. </enum>
  400. <enum name="codec[x]">
  401. <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
  402. </enum>
  403. </enumlist>
  404. </parameter>
  405. </syntax>
  406. <description></description>
  407. </function>
  408. <function name="SIPCHANINFO" language="en_US">
  409. <synopsis>
  410. Gets the specified SIP parameter from the current channel.
  411. </synopsis>
  412. <syntax>
  413. <parameter name="item" required="true">
  414. <enumlist>
  415. <enum name="peerip">
  416. <para>The IP address of the peer.</para>
  417. </enum>
  418. <enum name="recvip">
  419. <para>The source IP address of the peer.</para>
  420. </enum>
  421. <enum name="from">
  422. <para>The URI from the <literal>From:</literal> header.</para>
  423. </enum>
  424. <enum name="uri">
  425. <para>The URI from the <literal>Contact:</literal> header.</para>
  426. </enum>
  427. <enum name="useragent">
  428. <para>The useragent.</para>
  429. </enum>
  430. <enum name="peername">
  431. <para>The name of the peer.</para>
  432. </enum>
  433. <enum name="t38passthrough">
  434. <para><literal>1</literal> if T38 is offered or enabled in this channel,
  435. otherwise <literal>0</literal>.</para>
  436. </enum>
  437. </enumlist>
  438. </parameter>
  439. </syntax>
  440. <description></description>
  441. </function>
  442. <function name="CHECKSIPDOMAIN" language="en_US">
  443. <synopsis>
  444. Checks if domain is a local domain.
  445. </synopsis>
  446. <syntax>
  447. <parameter name="domain" required="true" />
  448. </syntax>
  449. <description>
  450. <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
  451. as a local SIP domain that this Asterisk server is configured to handle.
  452. Returns the domain name if it is locally handled, otherwise an empty string.
  453. Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
  454. </description>
  455. </function>
  456. <manager name="SIPpeers" language="en_US">
  457. <synopsis>
  458. List SIP peers (text format).
  459. </synopsis>
  460. <syntax>
  461. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  462. </syntax>
  463. <description>
  464. <para>Lists SIP peers in text format with details on current status.
  465. Peerlist will follow as separate events, followed by a final event called
  466. PeerlistComplete.</para>
  467. </description>
  468. </manager>
  469. <manager name="SIPshowpeer" language="en_US">
  470. <synopsis>
  471. show SIP peer (text format).
  472. </synopsis>
  473. <syntax>
  474. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  475. <parameter name="Peer" required="true">
  476. <para>The peer name you want to check.</para>
  477. </parameter>
  478. </syntax>
  479. <description>
  480. <para>Show one SIP peer with details on current status.</para>
  481. </description>
  482. </manager>
  483. <manager name="SIPqualifypeer" language="en_US">
  484. <synopsis>
  485. Qualify SIP peers.
  486. </synopsis>
  487. <syntax>
  488. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  489. <parameter name="Peer" required="true">
  490. <para>The peer name you want to qualify.</para>
  491. </parameter>
  492. </syntax>
  493. <description>
  494. <para>Qualify a SIP peer.</para>
  495. </description>
  496. </manager>
  497. <manager name="SIPshowregistry" language="en_US">
  498. <synopsis>
  499. Show SIP registrations (text format).
  500. </synopsis>
  501. <syntax>
  502. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  503. </syntax>
  504. <description>
  505. <para>Lists all registration requests and status. Registrations will follow as separate
  506. events. followed by a final event called RegistrationsComplete.</para>
  507. </description>
  508. </manager>
  509. <manager name="SIPnotify" language="en_US">
  510. <synopsis>
  511. Send a SIP notify.
  512. </synopsis>
  513. <syntax>
  514. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  515. <parameter name="Channel" required="true">
  516. <para>Peer to receive the notify.</para>
  517. </parameter>
  518. <parameter name="Variable" required="true">
  519. <para>At least one variable pair must be specified.
  520. <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
  521. </parameter>
  522. </syntax>
  523. <description>
  524. <para>Sends a SIP Notify event.</para>
  525. <para>All parameters for this event must be specified in the body of this request
  526. via multiple Variable: name=value sequences.</para>
  527. </description>
  528. </manager>
  529. ***/
  530. static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
  531. static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
  532. static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
  533. static int mwi_expiry = DEFAULT_MWI_EXPIRY;
  534. static int unauth_sessions = 0;
  535. static int authlimit = DEFAULT_AUTHLIMIT;
  536. static int authtimeout = DEFAULT_AUTHTIMEOUT;
  537. /*! \brief Global jitterbuffer configuration - by default, jb is disabled
  538. * \note Values shown here match the defaults shown in sip.conf.sample */
  539. static struct ast_jb_conf default_jbconf =
  540. {
  541. .flags = 0,
  542. .max_size = 200,
  543. .resync_threshold = 1000,
  544. .impl = "fixed",
  545. .target_extra = 40,
  546. };
  547. static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
  548. static const char config[] = "sip.conf"; /*!< Main configuration file */
  549. static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
  550. /*! \brief Readable descriptions of device states.
  551. * \note Should be aligned to above table as index */
  552. static const struct invstate2stringtable {
  553. const enum invitestates state;
  554. const char *desc;
  555. } invitestate2string[] = {
  556. {INV_NONE, "None" },
  557. {INV_CALLING, "Calling (Trying)"},
  558. {INV_PROCEEDING, "Proceeding "},
  559. {INV_EARLY_MEDIA, "Early media"},
  560. {INV_COMPLETED, "Completed (done)"},
  561. {INV_CONFIRMED, "Confirmed (up)"},
  562. {INV_TERMINATED, "Done"},
  563. {INV_CANCELLED, "Cancelled"}
  564. };
  565. /*! \brief Subscription types that we support. We support
  566. * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
  567. * - SIMPLE presence used for device status
  568. * - Voicemail notification subscriptions
  569. */
  570. static const struct cfsubscription_types {
  571. enum subscriptiontype type;
  572. const char * const event;
  573. const char * const mediatype;
  574. const char * const text;
  575. } subscription_types[] = {
  576. { NONE, "-", "unknown", "unknown" },
  577. /* RFC 4235: SIP Dialog event package */
  578. { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
  579. { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
  580. { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
  581. { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
  582. { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
  583. };
  584. /*! \brief The core structure to setup dialogs. We parse incoming messages by using
  585. * structure and then route the messages according to the type.
  586. *
  587. * \note Note that sip_methods[i].id == i must hold or the code breaks
  588. */
  589. static const struct cfsip_methods {
  590. enum sipmethod id;
  591. int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
  592. char * const text;
  593. enum can_create_dialog can_create;
  594. } sip_methods[] = {
  595. { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
  596. { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
  597. { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
  598. { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
  599. { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
  600. { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
  601. { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
  602. { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
  603. { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
  604. { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
  605. { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
  606. { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
  607. { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
  608. { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
  609. { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
  610. { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
  611. { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
  612. };
  613. /*! \brief Diversion header reasons
  614. *
  615. * The core defines a bunch of constants used to define
  616. * redirecting reasons. This provides a translation table
  617. * between those and the strings which may be present in
  618. * a SIP Diversion header
  619. */
  620. static const struct sip_reasons {
  621. enum AST_REDIRECTING_REASON code;
  622. char * const text;
  623. } sip_reason_table[] = {
  624. { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
  625. { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
  626. { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
  627. { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
  628. { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
  629. { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
  630. { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
  631. { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
  632. { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
  633. { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
  634. { AST_REDIRECTING_REASON_AWAY, "away" },
  635. { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
  636. };
  637. /*! \name DefaultSettings
  638. Default setttings are used as a channel setting and as a default when
  639. configuring devices
  640. */
  641. /*@{*/
  642. static char default_language[MAX_LANGUAGE]; /*!< Default language setting for new channels */
  643. static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
  644. static char default_mwi_from[80]; /*!< Default caller ID for MWI updates */
  645. static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
  646. static int default_fromdomainport; /*!< Default domain port on outbound messages */
  647. static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
  648. static char default_vmexten[AST_MAX_EXTENSION]; /*!< Default From Username on MWI updates */
  649. static int default_qualify; /*!< Default Qualify= setting */
  650. static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
  651. static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
  652. * a bridged channel on hold */
  653. static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
  654. static char default_engine[256]; /*!< Default RTP engine */
  655. static int default_maxcallbitrate; /*!< Maximum bitrate for call */
  656. static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
  657. static unsigned int default_transports; /*!< Default Transports (enum sip_transport) that are acceptable */
  658. static unsigned int default_primary_transport; /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
  659. /*@}*/
  660. static struct sip_settings sip_cfg; /*!< SIP configuration data.
  661. \note in the future we could have multiple of these (per domain, per device group etc) */
  662. /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
  663. #define SIP_PEDANTIC_DECODE(str) \
  664. if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
  665. ast_uri_decode(str); \
  666. } \
  667. static unsigned int chan_idx; /*!< used in naming sip channel */
  668. static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
  669. static int global_relaxdtmf; /*!< Relax DTMF */
  670. static int global_prematuremediafilter; /*!< Enable/disable premature frames in a call (causing 183 early media) */
  671. static int global_rtptimeout; /*!< Time out call if no RTP */
  672. static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
  673. static int global_rtpkeepalive; /*!< Send RTP keepalives */
  674. static int global_reg_timeout; /*!< Global time between attempts for outbound registrations */
  675. static int global_regattempts_max; /*!< Registration attempts before giving up */
  676. static int global_reg_retry_403; /*!< Treat 403 responses to registrations as 401 responses */
  677. static int global_shrinkcallerid; /*!< enable or disable shrinking of caller id */
  678. static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
  679. * call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
  680. * with just a boolean flag in the device structure */
  681. static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
  682. static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
  683. static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
  684. static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
  685. static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
  686. static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
  687. static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
  688. static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
  689. static unsigned int recordhistory; /*!< Record SIP history. Off by default */
  690. static unsigned int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
  691. static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
  692. static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
  693. static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
  694. static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
  695. static int global_t1; /*!< T1 time */
  696. static int global_t1min; /*!< T1 roundtrip time minimum */
  697. static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
  698. static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
  699. static int global_qualifyfreq; /*!< Qualify frequency */
  700. static int global_qualify_gap; /*!< Time between our group of peer pokes */
  701. static int global_qualify_peers; /*!< Number of peers to poke at a given time */
  702. static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
  703. static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher */
  704. static int global_min_se; /*!< Lowest threshold for session refresh interval */
  705. static int global_max_se; /*!< Highest threshold for session refresh interval */
  706. static int global_store_sip_cause; /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
  707. static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
  708. /*@}*/
  709. /*!
  710. * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
  711. * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
  712. * event package. This variable is set at module load time and may be checked at runtime to determine
  713. * if XML parsing support was found.
  714. */
  715. static int can_parse_xml;
  716. /*! \name Object counters @{
  717. * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
  718. * should be used to modify these values. */
  719. static int speerobjs = 0; /*!< Static peers */
  720. static int rpeerobjs = 0; /*!< Realtime peers */
  721. static int apeerobjs = 0; /*!< Autocreated peer objects */
  722. static int regobjs = 0; /*!< Registry objects */
  723. /* }@ */
  724. static struct ast_flags global_flags[3] = {{0}}; /*!< global SIP_ flags */
  725. static unsigned int global_t38_maxdatagram; /*!< global T.38 FaxMaxDatagram override */
  726. static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
  727. static int network_change_event_sched_id = -1;
  728. static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
  729. AST_MUTEX_DEFINE_STATIC(netlock);
  730. /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
  731. when it's doing something critical. */
  732. AST_MUTEX_DEFINE_STATIC(monlock);
  733. AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
  734. /*! \brief This is the thread for the monitor which checks for input on the channels
  735. which are not currently in use. */
  736. static pthread_t monitor_thread = AST_PTHREADT_NULL;
  737. static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
  738. static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
  739. struct sched_context *sched; /*!< The scheduling context */
  740. static struct io_context *io; /*!< The IO context */
  741. static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
  742. struct sip_pkt;
  743. static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
  744. AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
  745. static enum sip_debug_e sipdebug;
  746. /*! \brief extra debugging for 'text' related events.
  747. * At the moment this is set together with sip_debug_console.
  748. * \note It should either go away or be implemented properly.
  749. */
  750. static int sipdebug_text;
  751. static const struct _map_x_s referstatusstrings[] = {
  752. { REFER_IDLE, "<none>" },
  753. { REFER_SENT, "Request sent" },
  754. { REFER_RECEIVED, "Request received" },
  755. { REFER_CONFIRMED, "Confirmed" },
  756. { REFER_ACCEPTED, "Accepted" },
  757. { REFER_RINGING, "Target ringing" },
  758. { REFER_200OK, "Done" },
  759. { REFER_FAILED, "Failed" },
  760. { REFER_NOAUTH, "Failed - auth failure" },
  761. { -1, NULL} /* terminator */
  762. };
  763. /* --- Hash tables of various objects --------*/
  764. #ifdef LOW_MEMORY
  765. static const int HASH_PEER_SIZE = 17;
  766. static const int HASH_DIALOG_SIZE = 17;
  767. #else
  768. static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
  769. static const int HASH_DIALOG_SIZE = 563;
  770. #endif
  771. static const struct {
  772. enum ast_cc_service_type service;
  773. const char *service_string;
  774. } sip_cc_service_map [] = {
  775. [AST_CC_NONE] = { AST_CC_NONE, "" },
  776. [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
  777. [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
  778. [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
  779. };
  780. static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
  781. {
  782. enum ast_cc_service_type service;
  783. for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
  784. if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
  785. return service;
  786. }
  787. }
  788. return AST_CC_NONE;
  789. }
  790. static const struct {
  791. enum sip_cc_notify_state state;
  792. const char *state_string;
  793. } sip_cc_notify_state_map [] = {
  794. [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
  795. [CC_READY] = {CC_READY, "cc-state: ready"},
  796. };
  797. AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
  798. static int sip_epa_register(const struct epa_static_data *static_data)
  799. {
  800. struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
  801. if (!backend) {
  802. return -1;
  803. }
  804. backend->static_data = static_data;
  805. AST_LIST_LOCK(&epa_static_data_list);
  806. AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
  807. AST_LIST_UNLOCK(&epa_static_data_list);
  808. return 0;
  809. }
  810. static void sip_epa_unregister_all(void)
  811. {
  812. struct epa_backend *backend;
  813. AST_LIST_LOCK(&epa_static_data_list);
  814. while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
  815. ast_free(backend);
  816. }
  817. AST_LIST_UNLOCK(&epa_static_data_list);
  818. }
  819. static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
  820. static void cc_epa_destructor(void *data)
  821. {
  822. struct sip_epa_entry *epa_entry = data;
  823. struct cc_epa_entry *cc_entry = epa_entry->instance_data;
  824. ast_free(cc_entry);
  825. }
  826. static const struct epa_static_data cc_epa_static_data = {
  827. .event = CALL_COMPLETION,
  828. .name = "call-completion",
  829. .handle_error = cc_handle_publish_error,
  830. .destructor = cc_epa_destructor,
  831. };
  832. static const struct epa_static_data *find_static_data(const char * const event_package)
  833. {
  834. const struct epa_backend *backend = NULL;
  835. AST_LIST_LOCK(&epa_static_data_list);
  836. AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
  837. if (!strcmp(backend->static_data->name, event_package)) {
  838. break;
  839. }
  840. }
  841. AST_LIST_UNLOCK(&epa_static_data_list);
  842. return backend ? backend->static_data : NULL;
  843. }
  844. static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
  845. {
  846. struct sip_epa_entry *epa_entry;
  847. const struct epa_static_data *static_data;
  848. if (!(static_data = find_static_data(event_package))) {
  849. return NULL;
  850. }
  851. if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
  852. return NULL;
  853. }
  854. epa_entry->static_data = static_data;
  855. ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
  856. return epa_entry;
  857. }
  858. /*!
  859. * Used to create new entity IDs by ESCs.
  860. */
  861. static int esc_etag_counter;
  862. static const int DEFAULT_PUBLISH_EXPIRES = 3600;
  863. #ifdef HAVE_LIBXML2
  864. 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);
  865. static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
  866. .initial_handler = cc_esc_publish_handler,
  867. .modify_handler = cc_esc_publish_handler,
  868. };
  869. #endif
  870. /*!
  871. * \brief The Event State Compositors
  872. *
  873. * An Event State Compositor is an entity which
  874. * accepts PUBLISH requests and acts appropriately
  875. * based on these requests.
  876. *
  877. * The actual event_state_compositor structure is simply
  878. * an ao2_container of sip_esc_entrys. When an incoming
  879. * PUBLISH is received, we can match the appropriate sip_esc_entry
  880. * using the entity ID of the incoming PUBLISH.
  881. */
  882. static struct event_state_compositor {
  883. enum subscriptiontype event;
  884. const char * name;
  885. const struct sip_esc_publish_callbacks *callbacks;
  886. struct ao2_container *compositor;
  887. } event_state_compositors [] = {
  888. #ifdef HAVE_LIBXML2
  889. {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
  890. #endif
  891. };
  892. static const int ESC_MAX_BUCKETS = 37;
  893. static void esc_entry_destructor(void *obj)
  894. {
  895. struct sip_esc_entry *esc_entry = obj;
  896. if (esc_entry->sched_id > -1) {
  897. AST_SCHED_DEL(sched, esc_entry->sched_id);
  898. }
  899. }
  900. static int esc_hash_fn(const void *obj, const int flags)
  901. {
  902. const struct sip_esc_entry *entry = obj;
  903. return ast_str_hash(entry->entity_tag);
  904. }
  905. static int esc_cmp_fn(void *obj, void *arg, int flags)
  906. {
  907. struct sip_esc_entry *entry1 = obj;
  908. struct sip_esc_entry *entry2 = arg;
  909. return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
  910. }
  911. static struct event_state_compositor *get_esc(const char * const event_package) {
  912. int i;
  913. for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
  914. if (!strcasecmp(event_package, event_state_compositors[i].name)) {
  915. return &event_state_compositors[i];
  916. }
  917. }
  918. return NULL;
  919. }
  920. static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
  921. struct sip_esc_entry *entry;
  922. struct sip_esc_entry finder;
  923. ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
  924. entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
  925. return entry;
  926. }
  927. static int publish_expire(const void *data)
  928. {
  929. struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
  930. struct event_state_compositor *esc = get_esc(esc_entry->event);
  931. ast_assert(esc != NULL);
  932. ao2_unlink(esc->compositor, esc_entry);
  933. ao2_ref(esc_entry, -1);
  934. return 0;
  935. }
  936. static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
  937. {
  938. int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
  939. struct event_state_compositor *esc = get_esc(esc_entry->event);
  940. ast_assert(esc != NULL);
  941. if (is_linked) {
  942. ao2_unlink(esc->compositor, esc_entry);
  943. }
  944. snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
  945. ao2_link(esc->compositor, esc_entry);
  946. }
  947. static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
  948. {
  949. struct sip_esc_entry *esc_entry;
  950. int expires_ms;
  951. if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
  952. return NULL;
  953. }
  954. esc_entry->event = esc->name;
  955. expires_ms = expires * 1000;
  956. /* Bump refcount for scheduler */
  957. ao2_ref(esc_entry, +1);
  958. esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
  959. /* Note: This links the esc_entry into the ESC properly */
  960. create_new_sip_etag(esc_entry, 0);
  961. return esc_entry;
  962. }
  963. static int initialize_escs(void)
  964. {
  965. int i, res = 0;
  966. for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
  967. if (!((event_state_compositors[i].compositor) =
  968. ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
  969. res = -1;
  970. }
  971. }
  972. return res;
  973. }
  974. static void destroy_escs(void)
  975. {
  976. int i;
  977. for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
  978. ao2_ref(event_state_compositors[i].compositor, -1);
  979. }
  980. }
  981. /*!
  982. * \details
  983. * This container holds the dialogs that will be destroyed immediately.
  984. */
  985. struct ao2_container *dialogs_to_destroy;
  986. /*! \brief
  987. * Here we implement the container for dialogs (sip_pvt), defining
  988. * generic wrapper functions to ease the transition from the current
  989. * implementation (a single linked list) to a different container.
  990. * In addition to a reference to the container, we need functions to lock/unlock
  991. * the container and individual items, and functions to add/remove
  992. * references to the individual items.
  993. */
  994. static struct ao2_container *dialogs;
  995. #define sip_pvt_lock(x) ao2_lock(x)
  996. #define sip_pvt_trylock(x) ao2_trylock(x)
  997. #define sip_pvt_unlock(x) ao2_unlock(x)
  998. /*! \brief The table of TCP threads */
  999. static struct ao2_container *threadt;
  1000. /*! \brief The peer list: Users, Peers and Friends */
  1001. static struct ao2_container *peers;
  1002. static struct ao2_container *peers_by_ip;
  1003. /*! \brief A bogus peer, to be used when authentication should fail */
  1004. static struct sip_peer *bogus_peer;
  1005. /*! \brief We can recognise the bogus peer by this invalid MD5 hash */
  1006. #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
  1007. /*! \brief The register list: Other SIP proxies we register with and receive calls from */
  1008. static struct ast_register_list {
  1009. ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
  1010. int recheck;
  1011. } regl;
  1012. /*! \brief The MWI subscription list */
  1013. static struct ast_subscription_mwi_list {
  1014. ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
  1015. } submwil;
  1016. static int temp_pvt_init(void *);
  1017. static void temp_pvt_cleanup(void *);
  1018. /*! \brief A per-thread temporary pvt structure */
  1019. AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
  1020. /*! \brief Authentication container for realm authentication */
  1021. static struct sip_auth_container *authl = NULL;
  1022. /*! \brief Global authentication container protection while adjusting the references. */
  1023. AST_MUTEX_DEFINE_STATIC(authl_lock);
  1024. /* --- Sockets and networking --------------*/
  1025. /*! \brief Main socket for UDP SIP communication.
  1026. *
  1027. * sipsock is shared between the SIP manager thread (which handles reload
  1028. * requests), the udp io handler (sipsock_read()) and the user routines that
  1029. * issue udp writes (using __sip_xmit()).
  1030. * The socket is -1 only when opening fails (this is a permanent condition),
  1031. * or when we are handling a reload() that changes its address (this is
  1032. * a transient situation during which we might have a harmless race, see
  1033. * below). Because the conditions for the race to be possible are extremely
  1034. * rare, we don't want to pay the cost of locking on every I/O.
  1035. * Rather, we remember that when the race may occur, communication is
  1036. * bound to fail anyways, so we just live with this event and let
  1037. * the protocol handle this above us.
  1038. */
  1039. static int sipsock = -1;
  1040. struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
  1041. /*! \brief our (internal) default address/port to put in SIP/SDP messages
  1042. * internip is initialized picking a suitable address from one of the
  1043. * interfaces, and the same port number we bind to. It is used as the
  1044. * default address/port in SIP messages, and as the default address
  1045. * (but not port) in SDP messages.
  1046. */
  1047. static struct ast_sockaddr internip;
  1048. /*! \brief our external IP address/port for SIP sessions.
  1049. * externaddr.sin_addr is only set when we know we might be behind
  1050. * a NAT, and this is done using a variety of (mutually exclusive)
  1051. * ways from the config file:
  1052. *
  1053. * + with "externaddr = host[:port]" we specify the address/port explicitly.
  1054. * The address is looked up only once when (re)loading the config file;
  1055. *
  1056. * + with "externhost = host[:port]" we do a similar thing, but the
  1057. * hostname is stored in externhost, and the hostname->IP mapping
  1058. * is refreshed every 'externrefresh' seconds;
  1059. *
  1060. * Other variables (externhost, externexpire, externrefresh) are used
  1061. * to support the above functions.
  1062. */
  1063. static struct ast_sockaddr externaddr; /*!< External IP address if we are behind NAT */
  1064. static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
  1065. static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
  1066. static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
  1067. static int externrefresh = 10; /*!< Refresh timer for DNS-based external address (dyndns) */
  1068. static uint16_t externtcpport; /*!< external tcp port */
  1069. static uint16_t externtlsport; /*!< external tls port */
  1070. /*! \brief List of local networks
  1071. * We store "localnet" addresses from the config file into an access list,
  1072. * marked as 'DENY', so the call to ast_apply_ha() will return
  1073. * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
  1074. * (i.e. presumably public) addresses.
  1075. */
  1076. static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
  1077. static int ourport_tcp; /*!< The port used for TCP connections */
  1078. static int ourport_tls; /*!< The port used for TCP/TLS connections */
  1079. static struct ast_sockaddr debugaddr;
  1080. static struct ast_config *notify_types = NULL; /*!< The list of manual NOTIFY types we know how to send */
  1081. /*! some list management macros. */
  1082. #define UNLINK(element, head, prev) do { \
  1083. if (prev) \
  1084. (prev)->next = (element)->next; \
  1085. else \
  1086. (head) = (element)->next; \
  1087. } while (0)
  1088. struct show_peers_context;
  1089. /*---------------------------- Forward declarations of functions in chan_sip.c */
  1090. /* Note: This is added to help splitting up chan_sip.c into several files
  1091. in coming releases. */
  1092. /*--- PBX interface functions */
  1093. static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
  1094. static int sip_devicestate(void *data);
  1095. static int sip_sendtext(struct ast_channel *ast, const char *text);
  1096. static int sip_call(struct ast_channel *ast, char *dest, int timeout);
  1097. static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
  1098. static int sip_hangup(struct ast_channel *ast);
  1099. static int sip_answer(struct ast_channel *ast);
  1100. static struct ast_frame *sip_read(struct ast_channel *ast);
  1101. static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
  1102. static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
  1103. static int sip_transfer(struct ast_channel *ast, const char *dest);
  1104. static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
  1105. static int sip_senddigit_begin(struct ast_channel *ast, char digit);
  1106. static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
  1107. static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
  1108. static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
  1109. static const char *sip_get_callid(struct ast_channel *chan);
  1110. static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
  1111. static int sip_standard_port(enum sip_transport type, int port);
  1112. static int sip_prepare_socket(struct sip_pvt *p);
  1113. static int get_address_family_filter(unsigned int transport);
  1114. /*--- Transmitting responses and requests */
  1115. static int sipsock_read(int *id, int fd, short events, void *ignore);
  1116. static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
  1117. static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
  1118. static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
  1119. static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
  1120. static int retrans_pkt(const void *data);
  1121. 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);
  1122. static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1123. static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1124. static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1125. 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);
  1126. static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
  1127. 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);
  1128. static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
  1129. static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
  1130. static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
  1131. static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
  1132. static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
  1133. static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
  1134. static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
  1135. static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
  1136. static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
  1137. static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
  1138. static int transmit_info_with_vidupdate(struct sip_pvt *p);
  1139. static int transmit_message_with_text(struct sip_pvt *p, const char *text);
  1140. static int transmit_refer(struct sip_pvt *p, const char *dest);
  1141. static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
  1142. static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
  1143. static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
  1144. static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
  1145. static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
  1146. static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
  1147. static void copy_request(struct sip_request *dst, const struct sip_request *src);
  1148. static void receive_message(struct sip_pvt *p, struct sip_request *req);
  1149. static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
  1150. static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
  1151. /* Misc dialog routines */
  1152. static int __sip_autodestruct(const void *data);
  1153. static void *registry_unref(struct sip_registry *reg, char *tag);
  1154. static int update_call_counter(struct sip_pvt *fup, int event);
  1155. static int auto_congest(const void *arg);
  1156. static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
  1157. static void free_old_route(struct sip_route *route);
  1158. static void list_route(struct sip_route *route);
  1159. static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
  1160. static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
  1161. struct sip_request *req, const char *uri);
  1162. static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
  1163. static void check_pendings(struct sip_pvt *p);
  1164. static void *sip_park_thread(void *stuff);
  1165. static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context);
  1166. static void *sip_pickup_thread(void *stuff);
  1167. static int sip_pickup(struct ast_channel *chan);
  1168. static int sip_sipredirect(struct sip_pvt *p, const char *dest);
  1169. static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
  1170. /*--- Codec handling / SDP */
  1171. static void try_suggested_sip_codec(struct sip_pvt *p);
  1172. static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
  1173. static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
  1174. static int find_sdp(struct sip_request *req);
  1175. static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
  1176. static int process_sdp_o(const char *o, struct sip_pvt *p);
  1177. static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
  1178. static int process_sdp_a_sendonly(const char *a, int *sendonly);
  1179. static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
  1180. static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
  1181. 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);
  1182. static int process_sdp_a_image(const char *a, struct sip_pvt *p);
  1183. static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
  1184. struct ast_str **m_buf, struct ast_str **a_buf,
  1185. int debug, int *min_packet_size);
  1186. static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
  1187. struct ast_str **m_buf, struct ast_str **a_buf,
  1188. int debug);
  1189. static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
  1190. static void do_setnat(struct sip_pvt *p);
  1191. static void stop_media_flows(struct sip_pvt *p);
  1192. /*--- Authentication stuff */
  1193. static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
  1194. static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
  1195. static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
  1196. const char *secret, const char *md5secret, int sipmethod,
  1197. const char *uri, enum xmittype reliable, int ignore);
  1198. static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
  1199. int sipmethod, const char *uri, enum xmittype reliable,
  1200. struct ast_sockaddr *addr, struct sip_peer **authpeer);
  1201. static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
  1202. /*--- Domain handling */
  1203. static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
  1204. static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
  1205. static void clear_sip_domains(void);
  1206. /*--- SIP realm authentication */
  1207. static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
  1208. static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
  1209. /*--- Misc functions */
  1210. static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
  1211. static int reload_config(enum channelreloadreason reason);
  1212. static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
  1213. static int expire_register(const void *data);
  1214. static void *do_monitor(void *data);
  1215. static int restart_monitor(void);
  1216. static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
  1217. static struct ast_variable *copy_vars(struct ast_variable *src);
  1218. static int dialog_find_multiple(void *obj, void *arg, int flags);
  1219. static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
  1220. /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
  1221. static int sip_refer_allocate(struct sip_pvt *p);
  1222. static int sip_notify_allocate(struct sip_pvt *p);
  1223. static void ast_quiet_chan(struct ast_channel *chan);
  1224. static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
  1225. static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
  1226. /*--- Device monitoring and Device/extension state/event handling */
  1227. static int cb_extensionstate(char *context, char* exten, int state, void *data);
  1228. static int sip_devicestate(void *data);
  1229. static int sip_poke_noanswer(const void *data);
  1230. static int sip_poke_peer(struct sip_peer *peer, int force);
  1231. static void sip_poke_all_peers(void);
  1232. static void sip_peer_hold(struct sip_pvt *p, int hold);
  1233. static void mwi_event_cb(const struct ast_event *, void *);
  1234. static void network_change_event_cb(const struct ast_event *, void *);
  1235. /*--- Applications, functions, CLI and manager command helpers */
  1236. static const char *sip_nat_mode(const struct sip_pvt *p);
  1237. static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1238. static char *transfermode2str(enum transfermodes mode) attribute_const;
  1239. static int peer_status(struct sip_peer *peer, char *status, int statuslen);
  1240. static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1241. static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
  1242. static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
  1243. static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1244. static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1245. static void print_group(int fd, ast_group_t group, int crlf);
  1246. static const char *dtmfmode2str(int mode) attribute_const;
  1247. static int str2dtmfmode(const char *str) attribute_unused;
  1248. static const char *insecure2str(int mode) attribute_const;
  1249. static const char *allowoverlap2str(int mode) attribute_const;
  1250. static void cleanup_stale_contexts(char *new, char *old);
  1251. static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
  1252. static const char *domain_mode_to_text(const enum domain_mode mode);
  1253. static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1254. static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
  1255. static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1256. static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
  1257. static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1258. static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1259. static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1260. static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1261. static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1262. static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
  1263. static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
  1264. static char *complete_sip_peer(const char *word, int state, int flags2);
  1265. static char *complete_sip_registered_peer(const char *word, int state, int flags2);
  1266. static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
  1267. static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
  1268. static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
  1269. static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
  1270. static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1271. static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1272. static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1273. static char *sip_do_debug_ip(int fd, const char *arg);
  1274. static char *sip_do_debug_peer(int fd, const char *arg);
  1275. static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1276. static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1277. static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1278. static int sip_dtmfmode(struct ast_channel *chan, const char *data);
  1279. static int sip_addheader(struct ast_channel *chan, const char *data);
  1280. static int sip_do_reload(enum channelreloadreason reason);
  1281. static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1282. static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
  1283. const char *name, int flag, int family);
  1284. static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
  1285. const char *name, int flag);
  1286. static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
  1287. const char *name, int flag, unsigned int transport);
  1288. /*--- Debugging
  1289. Functions for enabling debug per IP or fully, or enabling history logging for
  1290. a SIP dialog
  1291. */
  1292. static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
  1293. static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
  1294. static inline int sip_debug_test_pvt(struct sip_pvt *p);
  1295. static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
  1296. static void sip_dump_history(struct sip_pvt *dialog);
  1297. /*--- Device object handling */
  1298. static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
  1299. static int update_call_counter(struct sip_pvt *fup, int event);
  1300. static void sip_destroy_peer(struct sip_peer *peer);
  1301. static void sip_destroy_peer_fn(void *peer);
  1302. static void set_peer_defaults(struct sip_peer *peer);
  1303. static struct sip_peer *temp_peer(const char *name);
  1304. static void register_peer_exten(struct sip_peer *peer, int onoff);
  1305. static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
  1306. static int sip_poke_peer_s(const void *data);
  1307. static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
  1308. static void reg_source_db(struct sip_peer *peer);
  1309. static void destroy_association(struct sip_peer *peer);
  1310. static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
  1311. static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
  1312. static void set_socket_transport(struct sip_socket *socket, int transport);
  1313. /* Realtime device support */
  1314. 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);
  1315. static void update_peer(struct sip_peer *p, int expire);
  1316. static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
  1317. static const char *get_name_from_variable(const struct ast_variable *var);
  1318. static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
  1319. static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1320. /*--- Internal UA client handling (outbound registrations) */
  1321. static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
  1322. static void sip_registry_destroy(struct sip_registry *reg);
  1323. static int sip_register(const char *value, int lineno);
  1324. static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
  1325. static int sip_reregister(const void *data);
  1326. static int __sip_do_register(struct sip_registry *r);
  1327. static int sip_reg_timeout(const void *data);
  1328. static void sip_send_all_registers(void);
  1329. static int sip_reinvite_retry(const void *data);
  1330. /*--- Parsing SIP requests and responses */
  1331. static void append_date(struct sip_request *req); /* Append date to SIP packet */
  1332. static int determine_firstline_parts(struct sip_request *req);
  1333. static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
  1334. static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
  1335. static int find_sip_method(const char *msg);
  1336. static unsigned int parse_allowed_methods(struct sip_request *req);
  1337. static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
  1338. static int parse_request(struct sip_request *req);
  1339. static const char *get_header(const struct sip_request *req, const char *name);
  1340. static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
  1341. static int method_match(enum sipmethod id, const char *name);
  1342. static void parse_copy(struct sip_request *dst, const struct sip_request *src);
  1343. static const char *find_alias(const char *name, const char *_default);
  1344. static const char *__get_header(const struct sip_request *req, const char *name, int *start);
  1345. static void lws2sws(struct ast_str *msgbuf);
  1346. static void extract_uri(struct sip_pvt *p, struct sip_request *req);
  1347. static char *remove_uri_parameters(char *uri);
  1348. static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
  1349. static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
  1350. static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
  1351. static int set_address_from_contact(struct sip_pvt *pvt);
  1352. static void check_via(struct sip_pvt *p, const struct sip_request *req);
  1353. static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
  1354. static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
  1355. static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
  1356. static int get_msg_text(char *buf, int len, struct sip_request *req);
  1357. static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
  1358. static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
  1359. static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
  1360. static int get_domain(const char *str, char *domain, int len);
  1361. static void get_realm(struct sip_pvt *p, const struct sip_request *req);
  1362. /*-- TCP connection handling ---*/
  1363. static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
  1364. static void *sip_tcp_worker_fn(void *);
  1365. /*--- Constructing requests and responses */
  1366. static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
  1367. static int init_req(struct sip_request *req, int sipmethod, const char *recip);
  1368. static void deinit_req(struct sip_request *req);
  1369. static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
  1370. static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
  1371. static int init_resp(struct sip_request *resp, const char *msg);
  1372. static inline int resp_needs_contact(const char *msg, enum sipmethod method);
  1373. static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
  1374. static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
  1375. static void build_via(struct sip_pvt *p);
  1376. static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
  1377. static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
  1378. static char *generate_random_string(char *buf, size_t size);
  1379. static void build_callid_pvt(struct sip_pvt *pvt);
  1380. static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
  1381. static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
  1382. static void build_localtag_registry(struct sip_registry *reg);
  1383. static void make_our_tag(struct sip_pvt *pvt);
  1384. static int add_header(struct sip_request *req, const char *var, const char *value);
  1385. static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
  1386. static int add_content(struct sip_request *req, const char *line);
  1387. static int finalize_content(struct sip_request *req);
  1388. static int add_text(struct sip_request *req, const char *text);
  1389. static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
  1390. static int add_rpid(struct sip_request *req, struct sip_pvt *p);
  1391. static int add_vidupdate(struct sip_request *req);
  1392. static void add_route(struct sip_request *req, struct sip_route *route);
  1393. static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
  1394. static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
  1395. static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
  1396. static void set_destination(struct sip_pvt *p, char *uri);
  1397. static void append_date(struct sip_request *req);
  1398. static void build_contact(struct sip_pvt *p);
  1399. /*------Request handling functions */
  1400. static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
  1401. static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
  1402. static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
  1403. static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
  1404. static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
  1405. static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
  1406. static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
  1407. static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
  1408. static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
  1409. static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
  1410. static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
  1411. static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
  1412. static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
  1413. static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
  1414. /*------Response handling functions */
  1415. static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1416. static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1417. static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1418. static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1419. static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1420. static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1421. static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
  1422. /*------ SRTP Support -------- */
  1423. static int setup_srtp(struct sip_srtp **srtp);
  1424. static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
  1425. /*------ T38 Support --------- */
  1426. static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
  1427. static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
  1428. static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
  1429. static void change_t38_state(struct sip_pvt *p, int state);
  1430. /*------ Session-Timers functions --------- */
  1431. static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
  1432. static int proc_session_timer(const void *vp);
  1433. static void stop_session_timer(struct sip_pvt *p);
  1434. static void start_session_timer(struct sip_pvt *p);
  1435. static void restart_session_timer(struct sip_pvt *p);
  1436. static const char *strefresherparam2str(enum st_refresher r);
  1437. static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
  1438. static int parse_minse(const char *p_hdrval, int *const p_interval);
  1439. static int st_get_se(struct sip_pvt *, int max);
  1440. static enum st_refresher st_get_refresher(struct sip_pvt *);
  1441. static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
  1442. static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
  1443. /*------- RTP Glue functions -------- */
  1444. 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, format_t codecs, int nat_active);
  1445. /*!--- SIP MWI Subscription support */
  1446. static int sip_subscribe_mwi(const char *value, int lineno);
  1447. static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
  1448. static void sip_send_all_mwi_subscriptions(void);
  1449. static int sip_subscribe_mwi_do(const void *data);
  1450. static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
  1451. /*! \brief Definition of this channel for PBX channel registration */
  1452. const struct ast_channel_tech sip_tech = {
  1453. .type = "SIP",
  1454. .description = "Session Initiation Protocol (SIP)",
  1455. .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
  1456. .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
  1457. .requester = sip_request_call, /* called with chan unlocked */
  1458. .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
  1459. .call = sip_call, /* called with chan locked */
  1460. .send_html = sip_sendhtml,
  1461. .hangup = sip_hangup, /* called with chan locked */
  1462. .answer = sip_answer, /* called with chan locked */
  1463. .read = sip_read, /* called with chan locked */
  1464. .write = sip_write, /* called with chan locked */
  1465. .write_video = sip_write, /* called with chan locked */
  1466. .write_text = sip_write,
  1467. .indicate = sip_indicate, /* called with chan locked */
  1468. .transfer = sip_transfer, /* called with chan locked */
  1469. .fixup = sip_fixup, /* called with chan locked */
  1470. .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
  1471. .send_digit_end = sip_senddigit_end,
  1472. .bridge = ast_rtp_instance_bridge, /* XXX chan unlocked ? */
  1473. .early_bridge = ast_rtp_instance_early_bridge,
  1474. .send_text = sip_sendtext, /* called with chan locked */
  1475. .func_channel_read = sip_acf_channel_read,
  1476. .setoption = sip_setoption,
  1477. .queryoption = sip_queryoption,
  1478. .get_pvt_uniqueid = sip_get_callid,
  1479. };
  1480. /*! \brief This version of the sip channel tech has no send_digit_begin
  1481. * callback so that the core knows that the channel does not want
  1482. * DTMF BEGIN frames.
  1483. * The struct is initialized just before registering the channel driver,
  1484. * and is for use with channels using SIP INFO DTMF.
  1485. */
  1486. struct ast_channel_tech sip_tech_info;
  1487. static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
  1488. static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
  1489. static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
  1490. static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
  1491. static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
  1492. static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
  1493. static int sip_cc_agent_recall(struct ast_cc_agent *agent);
  1494. static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
  1495. static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
  1496. .type = "SIP",
  1497. .init = sip_cc_agent_init,
  1498. .start_offer_timer = sip_cc_agent_start_offer_timer,
  1499. .stop_offer_timer = sip_cc_agent_stop_offer_timer,
  1500. .respond = sip_cc_agent_respond,
  1501. .status_request = sip_cc_agent_status_request,
  1502. .start_monitoring = sip_cc_agent_start_monitoring,
  1503. .callee_available = sip_cc_agent_recall,
  1504. .destructor = sip_cc_agent_destructor,
  1505. };
  1506. static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
  1507. {
  1508. struct ast_cc_agent *agent = obj;
  1509. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1510. const char *uri = arg;
  1511. return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
  1512. }
  1513. static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
  1514. {
  1515. struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
  1516. return agent;
  1517. }
  1518. static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
  1519. {
  1520. struct ast_cc_agent *agent = obj;
  1521. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1522. const char *uri = arg;
  1523. return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
  1524. }
  1525. static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
  1526. {
  1527. struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
  1528. return agent;
  1529. }
  1530. static int find_by_callid_helper(void *obj, void *arg, int flags)
  1531. {
  1532. struct ast_cc_agent *agent = obj;
  1533. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1534. struct sip_pvt *call_pvt = arg;
  1535. return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
  1536. }
  1537. static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
  1538. {
  1539. struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
  1540. return agent;
  1541. }
  1542. static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
  1543. {
  1544. struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
  1545. struct sip_pvt *call_pvt = chan->tech_pvt;
  1546. if (!agent_pvt) {
  1547. return -1;
  1548. }
  1549. ast_assert(!strcmp(chan->tech->type, "SIP"));
  1550. ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
  1551. ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
  1552. agent_pvt->offer_timer_id = -1;
  1553. agent->private_data = agent_pvt;
  1554. sip_pvt_lock(call_pvt);
  1555. ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
  1556. sip_pvt_unlock(call_pvt);
  1557. return 0;
  1558. }
  1559. static int sip_offer_timer_expire(const void *data)
  1560. {
  1561. struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
  1562. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1563. agent_pvt->offer_timer_id = -1;
  1564. return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
  1565. }
  1566. static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
  1567. {
  1568. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1569. int when;
  1570. when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
  1571. agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
  1572. return 0;
  1573. }
  1574. static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
  1575. {
  1576. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1577. AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
  1578. return 0;
  1579. }
  1580. static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
  1581. {
  1582. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1583. sip_pvt_lock(agent_pvt->subscribe_pvt);
  1584. ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  1585. if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
  1586. /* The second half of this if statement may be a bit hard to grasp,
  1587. * so here's an explanation. When a subscription comes into
  1588. * chan_sip, as long as it is not malformed, it will be passed
  1589. * to the CC core. If the core senses an out-of-order state transition,
  1590. * then the core will call this callback with the "reason" set to a
  1591. * failure condition.
  1592. * However, an out-of-order state transition will occur during a resubscription
  1593. * for CC. In such a case, we can see that we have already generated a notify_uri
  1594. * and so we can detect that this isn't a *real* failure. Rather, it is just
  1595. * something the core doesn't recognize as a legitimate SIP state transition.
  1596. * Thus we respond with happiness and flowers.
  1597. */
  1598. transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
  1599. transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
  1600. } else {
  1601. transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
  1602. }
  1603. sip_pvt_unlock(agent_pvt->subscribe_pvt);
  1604. agent_pvt->is_available = TRUE;
  1605. }
  1606. static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
  1607. {
  1608. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1609. enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
  1610. return ast_cc_agent_status_response(agent->core_id, state);
  1611. }
  1612. static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
  1613. {
  1614. /* To start monitoring just means to wait for an incoming PUBLISH
  1615. * to tell us that the caller has become available again. No special
  1616. * action is needed
  1617. */
  1618. return 0;
  1619. }
  1620. static int sip_cc_agent_recall(struct ast_cc_agent *agent)
  1621. {
  1622. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1623. /* If we have received a PUBLISH beforehand stating that the caller in question
  1624. * is not available, we can save ourself a bit of effort here and just report
  1625. * the caller as busy
  1626. */
  1627. if (!agent_pvt->is_available) {
  1628. return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
  1629. agent->device_name);
  1630. }
  1631. /* Otherwise, we transmit a NOTIFY to the caller and await either
  1632. * a PUBLISH or an INVITE
  1633. */
  1634. sip_pvt_lock(agent_pvt->subscribe_pvt);
  1635. transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
  1636. sip_pvt_unlock(agent_pvt->subscribe_pvt);
  1637. return 0;
  1638. }
  1639. static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
  1640. {
  1641. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  1642. if (!agent_pvt) {
  1643. /* The agent constructor probably failed. */
  1644. return;
  1645. }
  1646. sip_cc_agent_stop_offer_timer(agent);
  1647. if (agent_pvt->subscribe_pvt) {
  1648. sip_pvt_lock(agent_pvt->subscribe_pvt);
  1649. if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  1650. /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
  1651. * the subscriber know something went wrong
  1652. */
  1653. transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
  1654. }
  1655. sip_pvt_unlock(agent_pvt->subscribe_pvt);
  1656. agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
  1657. }
  1658. ast_free(agent_pvt);
  1659. }
  1660. struct ao2_container *sip_monitor_instances;
  1661. static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
  1662. {
  1663. const struct sip_monitor_instance *monitor_instance = obj;
  1664. return monitor_instance->core_id;
  1665. }
  1666. static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
  1667. {
  1668. struct sip_monitor_instance *monitor_instance1 = obj;
  1669. struct sip_monitor_instance *monitor_instance2 = arg;
  1670. return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
  1671. }
  1672. static void sip_monitor_instance_destructor(void *data)
  1673. {
  1674. struct sip_monitor_instance *monitor_instance = data;
  1675. if (monitor_instance->subscription_pvt) {
  1676. sip_pvt_lock(monitor_instance->subscription_pvt);
  1677. monitor_instance->subscription_pvt->expiry = 0;
  1678. transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
  1679. sip_pvt_unlock(monitor_instance->subscription_pvt);
  1680. dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
  1681. }
  1682. if (monitor_instance->suspension_entry) {
  1683. monitor_instance->suspension_entry->body[0] = '\0';
  1684. transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
  1685. ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
  1686. }
  1687. ast_string_field_free_memory(monitor_instance);
  1688. }
  1689. 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)
  1690. {
  1691. struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
  1692. if (!monitor_instance) {
  1693. return NULL;
  1694. }
  1695. if (ast_string_field_init(monitor_instance, 256)) {
  1696. ao2_ref(monitor_instance, -1);
  1697. return NULL;
  1698. }
  1699. ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
  1700. ast_string_field_set(monitor_instance, peername, peername);
  1701. ast_string_field_set(monitor_instance, device_name, device_name);
  1702. monitor_instance->core_id = core_id;
  1703. ao2_link(sip_monitor_instances, monitor_instance);
  1704. return monitor_instance;
  1705. }
  1706. static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
  1707. {
  1708. struct sip_monitor_instance *monitor_instance = obj;
  1709. return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
  1710. }
  1711. static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
  1712. {
  1713. struct sip_monitor_instance *monitor_instance = obj;
  1714. return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
  1715. }
  1716. static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
  1717. static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
  1718. static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
  1719. static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
  1720. static void sip_cc_monitor_destructor(void *private_data);
  1721. static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
  1722. .type = "SIP",
  1723. .request_cc = sip_cc_monitor_request_cc,
  1724. .suspend = sip_cc_monitor_suspend,
  1725. .unsuspend = sip_cc_monitor_unsuspend,
  1726. .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
  1727. .destructor = sip_cc_monitor_destructor,
  1728. };
  1729. static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
  1730. {
  1731. struct sip_monitor_instance *monitor_instance = monitor->private_data;
  1732. enum ast_cc_service_type service = monitor->service_offered;
  1733. int when;
  1734. if (!monitor_instance) {
  1735. return -1;
  1736. }
  1737. if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
  1738. return -1;
  1739. }
  1740. when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
  1741. ast_get_ccnr_available_timer(monitor->interface->config_params);
  1742. sip_pvt_lock(monitor_instance->subscription_pvt);
  1743. ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
  1744. create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
  1745. ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
  1746. monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
  1747. monitor_instance->subscription_pvt->expiry = when;
  1748. transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
  1749. sip_pvt_unlock(monitor_instance->subscription_pvt);
  1750. ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
  1751. *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
  1752. return 0;
  1753. }
  1754. static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
  1755. {
  1756. struct ast_str *body = ast_str_alloca(size);
  1757. char tuple_id[32];
  1758. generate_random_string(tuple_id, sizeof(tuple_id));
  1759. /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
  1760. * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
  1761. */
  1762. ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  1763. /* XXX The entity attribute is currently set to the peer name associated with the
  1764. * dialog. This is because we currently only call this function for call-completion
  1765. * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
  1766. * event packages, it may be crucial to have a proper URI as the presentity so this
  1767. * should be revisited as support is expanded.
  1768. */
  1769. ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
  1770. ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
  1771. ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
  1772. ast_str_append(&body, 0, "</tuple>\n");
  1773. ast_str_append(&body, 0, "</presence>\n");
  1774. ast_copy_string(pidf_body, ast_str_buffer(body), size);
  1775. return 0;
  1776. }
  1777. static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
  1778. {
  1779. struct sip_monitor_instance *monitor_instance = monitor->private_data;
  1780. enum sip_publish_type publish_type;
  1781. struct cc_epa_entry *cc_entry;
  1782. if (!monitor_instance) {
  1783. return -1;
  1784. }
  1785. if (!monitor_instance->suspension_entry) {
  1786. /* We haven't yet allocated the suspension entry, so let's give it a shot */
  1787. if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
  1788. ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
  1789. ao2_ref(monitor_instance, -1);
  1790. return -1;
  1791. }
  1792. if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
  1793. ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
  1794. ao2_ref(monitor_instance, -1);
  1795. return -1;
  1796. }
  1797. cc_entry->core_id = monitor->core_id;
  1798. monitor_instance->suspension_entry->instance_data = cc_entry;
  1799. publish_type = SIP_PUBLISH_INITIAL;
  1800. } else {
  1801. publish_type = SIP_PUBLISH_MODIFY;
  1802. cc_entry = monitor_instance->suspension_entry->instance_data;
  1803. }
  1804. cc_entry->current_state = CC_CLOSED;
  1805. if (ast_strlen_zero(monitor_instance->notify_uri)) {
  1806. /* If we have no set notify_uri, then what this means is that we have
  1807. * not received a NOTIFY from this destination stating that he is
  1808. * currently available.
  1809. *
  1810. * This situation can arise when the core calls the suspend callbacks
  1811. * of multiple destinations. If one of the other destinations aside
  1812. * from this one notified Asterisk that he is available, then there
  1813. * is no reason to take any suspension action on this device. Rather,
  1814. * we should return now and if we receive a NOTIFY while monitoring
  1815. * is still "suspended" then we can immediately respond with the
  1816. * proper PUBLISH to let this endpoint know what is going on.
  1817. */
  1818. return 0;
  1819. }
  1820. construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
  1821. return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
  1822. }
  1823. static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
  1824. {
  1825. struct sip_monitor_instance *monitor_instance = monitor->private_data;
  1826. struct cc_epa_entry *cc_entry;
  1827. if (!monitor_instance) {
  1828. return -1;
  1829. }
  1830. ast_assert(monitor_instance->suspension_entry != NULL);
  1831. cc_entry = monitor_instance->suspension_entry->instance_data;
  1832. cc_entry->current_state = CC_OPEN;
  1833. if (ast_strlen_zero(monitor_instance->notify_uri)) {
  1834. /* This means we are being asked to unsuspend a call leg we never
  1835. * sent a PUBLISH on. As such, there is no reason to send another
  1836. * PUBLISH at this point either. We can just return instead.
  1837. */
  1838. return 0;
  1839. }
  1840. construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
  1841. return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
  1842. }
  1843. static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
  1844. {
  1845. if (*sched_id != -1) {
  1846. AST_SCHED_DEL(sched, *sched_id);
  1847. ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
  1848. }
  1849. return 0;
  1850. }
  1851. static void sip_cc_monitor_destructor(void *private_data)
  1852. {
  1853. struct sip_monitor_instance *monitor_instance = private_data;
  1854. ao2_unlink(sip_monitor_instances, monitor_instance);
  1855. ast_module_unref(ast_module_info->self);
  1856. }
  1857. static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
  1858. {
  1859. char *call_info = ast_strdupa(get_header(req, "Call-Info"));
  1860. char *uri;
  1861. char *purpose;
  1862. char *service_str;
  1863. static const char cc_purpose[] = "purpose=call-completion";
  1864. static const int cc_purpose_len = sizeof(cc_purpose) - 1;
  1865. if (ast_strlen_zero(call_info)) {
  1866. /* No Call-Info present. Definitely no CC offer */
  1867. return -1;
  1868. }
  1869. uri = strsep(&call_info, ";");
  1870. while ((purpose = strsep(&call_info, ";"))) {
  1871. if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
  1872. break;
  1873. }
  1874. }
  1875. if (!purpose) {
  1876. /* We didn't find the appropriate purpose= parameter. Oh well */
  1877. return -1;
  1878. }
  1879. /* Okay, call-completion has been offered. Let's figure out what type of service this is */
  1880. while ((service_str = strsep(&call_info, ";"))) {
  1881. if (!strncmp(service_str, "m=", 2)) {
  1882. break;
  1883. }
  1884. }
  1885. if (!service_str) {
  1886. /* So they didn't offer a particular service, We'll just go with CCBS since it really
  1887. * doesn't matter anyway
  1888. */
  1889. service_str = "BS";
  1890. } else {
  1891. /* We already determined that there is an "m=" so no need to check
  1892. * the result of this strsep
  1893. */
  1894. strsep(&service_str, "=");
  1895. }
  1896. if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
  1897. /* Invalid service offered */
  1898. return -1;
  1899. }
  1900. ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
  1901. return 0;
  1902. }
  1903. /*
  1904. * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
  1905. *
  1906. * After taking care of some formalities to be sure that this call is eligible for CC,
  1907. * we first try to see if we can make use of native CC. We grab the information from
  1908. * the passed-in sip_request (which is always a response to an INVITE). If we can
  1909. * use native CC monitoring for the call, then so be it.
  1910. *
  1911. * If native cc monitoring is not possible or not supported, then we will instead attempt
  1912. * to use generic monitoring. Falling back to generic from a failed attempt at using native
  1913. * monitoring will only work if the monitor policy of the endpoint is "always"
  1914. *
  1915. * \param pvt The current dialog. Contains CC parameters for the endpoint
  1916. * \param req The response to the INVITE we want to inspect
  1917. * \param service The service to use if generic monitoring is to be used. For native
  1918. * monitoring, we get the service from the SIP response itself
  1919. */
  1920. static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
  1921. {
  1922. enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
  1923. int core_id;
  1924. char interface_name[AST_CHANNEL_NAME];
  1925. if (monitor_policy == AST_CC_MONITOR_NEVER) {
  1926. /* Don't bother, just return */
  1927. return;
  1928. }
  1929. if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
  1930. /* For some reason, CC is invalid, so don't try it! */
  1931. return;
  1932. }
  1933. ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
  1934. if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
  1935. char subscribe_uri[SIPBUFSIZE];
  1936. char device_name[AST_CHANNEL_NAME];
  1937. enum ast_cc_service_type offered_service;
  1938. struct sip_monitor_instance *monitor_instance;
  1939. if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
  1940. /* If CC isn't being offered to us, or for some reason the CC offer is
  1941. * not formatted correctly, then it may still be possible to use generic
  1942. * call completion since the monitor policy may be "always"
  1943. */
  1944. goto generic;
  1945. }
  1946. ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
  1947. if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
  1948. /* Same deal. We can try using generic still */
  1949. goto generic;
  1950. }
  1951. /* We bump the refcount of chan_sip because once we queue this frame, the CC core
  1952. * will have a reference to callbacks in this module. We decrement the module
  1953. * refcount once the monitor destructor is called
  1954. */
  1955. ast_module_ref(ast_module_info->self);
  1956. ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
  1957. ao2_ref(monitor_instance, -1);
  1958. return;
  1959. }
  1960. generic:
  1961. if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
  1962. ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
  1963. }
  1964. }
  1965. /*! \brief Working TLS connection configuration */
  1966. static struct ast_tls_config sip_tls_cfg;
  1967. /*! \brief Default TLS connection configuration */
  1968. static struct ast_tls_config default_tls_cfg;
  1969. /*! \brief The TCP server definition */
  1970. static struct ast_tcptls_session_args sip_tcp_desc = {
  1971. .accept_fd = -1,
  1972. .master = AST_PTHREADT_NULL,
  1973. .tls_cfg = NULL,
  1974. .poll_timeout = -1,
  1975. .name = "SIP TCP server",
  1976. .accept_fn = ast_tcptls_server_root,
  1977. .worker_fn = sip_tcp_worker_fn,
  1978. };
  1979. /*! \brief The TCP/TLS server definition */
  1980. static struct ast_tcptls_session_args sip_tls_desc = {
  1981. .accept_fd = -1,
  1982. .master = AST_PTHREADT_NULL,
  1983. .tls_cfg = &sip_tls_cfg,
  1984. .poll_timeout = -1,
  1985. .name = "SIP TLS server",
  1986. .accept_fn = ast_tcptls_server_root,
  1987. .worker_fn = sip_tcp_worker_fn,
  1988. };
  1989. /*! \brief Append to SIP dialog history
  1990. \return Always returns 0 */
  1991. #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
  1992. struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
  1993. {
  1994. if (p)
  1995. #ifdef REF_DEBUG
  1996. __ao2_ref_debug(p, 1, tag, file, line, func);
  1997. #else
  1998. ao2_ref(p, 1);
  1999. #endif
  2000. else
  2001. ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
  2002. return p;
  2003. }
  2004. struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
  2005. {
  2006. if (p)
  2007. #ifdef REF_DEBUG
  2008. __ao2_ref_debug(p, -1, tag, file, line, func);
  2009. #else
  2010. ao2_ref(p, -1);
  2011. #endif
  2012. return NULL;
  2013. }
  2014. /*! \brief map from an integer value to a string.
  2015. * If no match is found, return errorstring
  2016. */
  2017. static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
  2018. {
  2019. const struct _map_x_s *cur;
  2020. for (cur = table; cur->s; cur++)
  2021. if (cur->x == x)
  2022. return cur->s;
  2023. return errorstring;
  2024. }
  2025. /*! \brief map from a string to an integer value, case insensitive.
  2026. * If no match is found, return errorvalue.
  2027. */
  2028. static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
  2029. {
  2030. const struct _map_x_s *cur;
  2031. for (cur = table; cur->s; cur++)
  2032. if (!strcasecmp(cur->s, s))
  2033. return cur->x;
  2034. return errorvalue;
  2035. }
  2036. static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
  2037. {
  2038. enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
  2039. int i;
  2040. for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
  2041. if (!strcasecmp(text, sip_reason_table[i].text)) {
  2042. ast = sip_reason_table[i].code;
  2043. break;
  2044. }
  2045. }
  2046. return ast;
  2047. }
  2048. static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
  2049. {
  2050. if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
  2051. return sip_reason_table[code].text;
  2052. }
  2053. return "unknown";
  2054. }
  2055. /*!
  2056. * \brief generic function for determining if a correct transport is being
  2057. * used to contact a peer
  2058. *
  2059. * this is done as a macro so that the "tmpl" var can be passed either a
  2060. * sip_request or a sip_peer
  2061. */
  2062. #define check_request_transport(peer, tmpl) ({ \
  2063. int ret = 0; \
  2064. if (peer->socket.type == tmpl->socket.type) \
  2065. ; \
  2066. else if (!(peer->transports & tmpl->socket.type)) {\
  2067. ast_log(LOG_ERROR, \
  2068. "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
  2069. get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
  2070. ); \
  2071. ret = 1; \
  2072. } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
  2073. ast_log(LOG_WARNING, \
  2074. "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
  2075. peer->name, get_transport(tmpl->socket.type) \
  2076. ); \
  2077. } else { \
  2078. ast_debug(1, \
  2079. "peer '%s' has contacted us over %s even though we prefer %s.\n", \
  2080. peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
  2081. ); \
  2082. }\
  2083. (ret); \
  2084. })
  2085. /*! \brief
  2086. * duplicate a list of channel variables, \return the copy.
  2087. */
  2088. static struct ast_variable *copy_vars(struct ast_variable *src)
  2089. {
  2090. struct ast_variable *res = NULL, *tmp, *v = NULL;
  2091. for (v = src ; v ; v = v->next) {
  2092. if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
  2093. tmp->next = res;
  2094. res = tmp;
  2095. }
  2096. }
  2097. return res;
  2098. }
  2099. static void tcptls_packet_destructor(void *obj)
  2100. {
  2101. struct tcptls_packet *packet = obj;
  2102. ast_free(packet->data);
  2103. }
  2104. static void sip_tcptls_client_args_destructor(void *obj)
  2105. {
  2106. struct ast_tcptls_session_args *args = obj;
  2107. if (args->tls_cfg) {
  2108. ast_free(args->tls_cfg->certfile);
  2109. ast_free(args->tls_cfg->pvtfile);
  2110. ast_free(args->tls_cfg->cipher);
  2111. ast_free(args->tls_cfg->cafile);
  2112. ast_free(args->tls_cfg->capath);
  2113. ast_ssl_teardown(args->tls_cfg);
  2114. }
  2115. ast_free(args->tls_cfg);
  2116. ast_free((char *) args->name);
  2117. }
  2118. static void sip_threadinfo_destructor(void *obj)
  2119. {
  2120. struct sip_threadinfo *th = obj;
  2121. struct tcptls_packet *packet;
  2122. if (th->alert_pipe[1] > -1) {
  2123. close(th->alert_pipe[0]);
  2124. }
  2125. if (th->alert_pipe[1] > -1) {
  2126. close(th->alert_pipe[1]);
  2127. }
  2128. th->alert_pipe[0] = th->alert_pipe[1] = -1;
  2129. while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
  2130. ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
  2131. }
  2132. if (th->tcptls_session) {
  2133. ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
  2134. }
  2135. }
  2136. /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
  2137. static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
  2138. {
  2139. struct sip_threadinfo *th;
  2140. if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
  2141. return NULL;
  2142. }
  2143. th->alert_pipe[0] = th->alert_pipe[1] = -1;
  2144. if (pipe(th->alert_pipe) == -1) {
  2145. ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
  2146. ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
  2147. return NULL;
  2148. }
  2149. ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
  2150. th->tcptls_session = tcptls_session;
  2151. th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
  2152. ao2_t_link(threadt, th, "Adding new tcptls helper thread");
  2153. ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
  2154. return th;
  2155. }
  2156. /*! \brief used to indicate to a tcptls thread that data is ready to be written */
  2157. static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
  2158. {
  2159. int res = len;
  2160. struct sip_threadinfo *th = NULL;
  2161. struct tcptls_packet *packet = NULL;
  2162. struct sip_threadinfo tmp = {
  2163. .tcptls_session = tcptls_session,
  2164. };
  2165. enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
  2166. if (!tcptls_session) {
  2167. return XMIT_ERROR;
  2168. }
  2169. ast_mutex_lock(&tcptls_session->lock);
  2170. if ((tcptls_session->fd == -1) ||
  2171. !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
  2172. !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
  2173. !(packet->data = ast_str_create(len))) {
  2174. goto tcptls_write_setup_error;
  2175. }
  2176. /* goto tcptls_write_error should _NOT_ be used beyond this point */
  2177. ast_str_set(&packet->data, 0, "%s", (char *) buf);
  2178. packet->len = len;
  2179. /* alert tcptls thread handler that there is a packet to be sent.
  2180. * must lock the thread info object to guarantee control of the
  2181. * packet queue */
  2182. ao2_lock(th);
  2183. if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
  2184. ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
  2185. ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
  2186. packet = NULL;
  2187. res = XMIT_ERROR;
  2188. } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
  2189. AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
  2190. }
  2191. ao2_unlock(th);
  2192. ast_mutex_unlock(&tcptls_session->lock);
  2193. ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
  2194. return res;
  2195. tcptls_write_setup_error:
  2196. if (th) {
  2197. ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
  2198. }
  2199. if (packet) {
  2200. ao2_t_ref(packet, -1, "could not allocate packet's data");
  2201. }
  2202. ast_mutex_unlock(&tcptls_session->lock);
  2203. return XMIT_ERROR;
  2204. }
  2205. /*! \brief SIP TCP connection handler */
  2206. static void *sip_tcp_worker_fn(void *data)
  2207. {
  2208. struct ast_tcptls_session_instance *tcptls_session = data;
  2209. return _sip_tcp_helper_thread(tcptls_session);
  2210. }
  2211. /*! \brief Check if the authtimeout has expired.
  2212. * \param start the time when the session started
  2213. *
  2214. * \retval 0 the timeout has expired
  2215. * \retval -1 error
  2216. * \return the number of milliseconds until the timeout will expire
  2217. */
  2218. static int sip_check_authtimeout(time_t start)
  2219. {
  2220. int timeout;
  2221. time_t now;
  2222. if(time(&now) == -1) {
  2223. ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
  2224. return -1;
  2225. }
  2226. timeout = (authtimeout - (now - start)) * 1000;
  2227. if (timeout < 0) {
  2228. /* we have timed out */
  2229. return 0;
  2230. }
  2231. return timeout;
  2232. }
  2233. /*!
  2234. * \brief Indication of a TCP message's integrity
  2235. */
  2236. enum message_integrity {
  2237. /*!
  2238. * The message has an error in it with
  2239. * regards to its Content-Length header
  2240. */
  2241. MESSAGE_INVALID,
  2242. /*!
  2243. * The message is incomplete
  2244. */
  2245. MESSAGE_FRAGMENT,
  2246. /*!
  2247. * The data contains a complete message
  2248. * plus a fragment of another.
  2249. */
  2250. MESSAGE_FRAGMENT_COMPLETE,
  2251. /*!
  2252. * The message is complete
  2253. */
  2254. MESSAGE_COMPLETE,
  2255. };
  2256. /*!
  2257. * \brief
  2258. * Get the content length from an unparsed SIP message
  2259. *
  2260. * \param message The unparsed SIP message headers
  2261. * \return The value of the Content-Length header or -1 if message is invalid
  2262. */
  2263. static int read_raw_content_length(const char *message)
  2264. {
  2265. char *content_length_str;
  2266. int content_length = -1;
  2267. struct ast_str *msg_copy;
  2268. char *msg;
  2269. /* Using a ast_str because lws2sws takes one of those */
  2270. if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
  2271. return -1;
  2272. }
  2273. ast_str_set(&msg_copy, 0, "%s", message);
  2274. if (sip_cfg.pedanticsipchecking) {
  2275. lws2sws(msg_copy);
  2276. }
  2277. msg = ast_str_buffer(msg_copy);
  2278. /* Let's find a Content-Length header */
  2279. if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
  2280. content_length_str += sizeof("\nContent-Length:") - 1;
  2281. } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
  2282. content_length_str += sizeof("\nl:") - 1;
  2283. } else {
  2284. /* RFC 3261 18.3
  2285. * "In the case of stream-oriented transports such as TCP, the Content-
  2286. * Length header field indicates the size of the body. The Content-
  2287. * Length header field MUST be used with stream oriented transports."
  2288. */
  2289. goto done;
  2290. }
  2291. /* Double-check that this is a complete header */
  2292. if (!strchr(content_length_str, '\n')) {
  2293. goto done;
  2294. }
  2295. if (sscanf(content_length_str, "%30d", &content_length) != 1) {
  2296. content_length = -1;
  2297. }
  2298. done:
  2299. ast_free(msg_copy);
  2300. return content_length;
  2301. }
  2302. /*!
  2303. * \brief Check that a message received over TCP is a full message
  2304. *
  2305. * This will take the information read in and then determine if
  2306. * 1) The message is a full SIP request
  2307. * 2) The message is a partial SIP request
  2308. * 3) The message contains a full SIP request along with another partial request
  2309. * \param data The unparsed incoming SIP message.
  2310. * \param request The resulting request with extra fragments removed.
  2311. * \param overflow If the message contains more than a full request, this is the remainder of the message
  2312. * \return The resulting integrity of the message
  2313. */
  2314. static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
  2315. {
  2316. char *message = ast_str_buffer(*request);
  2317. char *body;
  2318. int content_length;
  2319. int message_len = ast_str_strlen(*request);
  2320. int body_len;
  2321. /* Important pieces to search for in a SIP request are \r\n\r\n. This
  2322. * marks either
  2323. * 1) The division between the headers and body
  2324. * 2) The end of the SIP request
  2325. */
  2326. body = strstr(message, "\r\n\r\n");
  2327. if (!body) {
  2328. /* This is clearly a partial message since we haven't reached an end
  2329. * yet.
  2330. */
  2331. return MESSAGE_FRAGMENT;
  2332. }
  2333. body += sizeof("\r\n\r\n") - 1;
  2334. body_len = message_len - (body - message);
  2335. body[-1] = '\0';
  2336. content_length = read_raw_content_length(message);
  2337. body[-1] = '\n';
  2338. if (content_length < 0) {
  2339. return MESSAGE_INVALID;
  2340. } else if (content_length == 0) {
  2341. /* We've definitely received an entire message. We need
  2342. * to check if there's also a fragment of another message
  2343. * in addition.
  2344. */
  2345. if (body_len == 0) {
  2346. return MESSAGE_COMPLETE;
  2347. } else {
  2348. ast_str_append(overflow, 0, "%s", body);
  2349. ast_str_truncate(*request, message_len - body_len);
  2350. return MESSAGE_FRAGMENT_COMPLETE;
  2351. }
  2352. }
  2353. /* Positive content length. Let's see what sort of
  2354. * message body we're dealing with.
  2355. */
  2356. if (body_len < content_length) {
  2357. /* We don't have the full message body yet */
  2358. return MESSAGE_FRAGMENT;
  2359. } else if (body_len > content_length) {
  2360. /* We have the full message plus a fragment of a further
  2361. * message
  2362. */
  2363. ast_str_append(overflow, 0, "%s", body + content_length);
  2364. ast_str_truncate(*request, message_len - (body_len - content_length));
  2365. return MESSAGE_FRAGMENT_COMPLETE;
  2366. } else {
  2367. /* Yay! Full message with no extra content */
  2368. return MESSAGE_COMPLETE;
  2369. }
  2370. }
  2371. /*!
  2372. * \brief Read SIP request or response from a TCP/TLS connection
  2373. *
  2374. * \param req The request structure to be filled in
  2375. * \param tcptls_session The TCP/TLS connection from which to read
  2376. * \retval -1 Failed to read data
  2377. * \retval 0 Successfully read data
  2378. */
  2379. static int sip_tcptls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
  2380. int authenticated, time_t start)
  2381. {
  2382. enum message_integrity message_integrity = MESSAGE_FRAGMENT;
  2383. while (message_integrity == MESSAGE_FRAGMENT) {
  2384. size_t datalen;
  2385. if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
  2386. char readbuf[4097];
  2387. int timeout;
  2388. int res;
  2389. if (!tcptls_session->client && !authenticated) {
  2390. if ((timeout = sip_check_authtimeout(start)) < 0) {
  2391. return -1;
  2392. }
  2393. if (timeout == 0) {
  2394. ast_debug(2, "SIP TCP/TLS server timed out\n");
  2395. return -1;
  2396. }
  2397. } else {
  2398. timeout = -1;
  2399. }
  2400. res = ast_wait_for_input(tcptls_session->fd, timeout);
  2401. if (res < 0) {
  2402. ast_debug(2, "SIP TCP/TLS server :: ast_wait_for_input returned %d\n", res);
  2403. return -1;
  2404. } else if (res == 0) {
  2405. ast_debug(2, "SIP TCP/TLS server timed out\n");
  2406. return -1;
  2407. }
  2408. res = ast_tcptls_server_read(tcptls_session, readbuf, sizeof(readbuf) - 1);
  2409. if (res < 0) {
  2410. if (errno == EAGAIN || errno == EINTR) {
  2411. continue;
  2412. }
  2413. ast_debug(2, "SIP TCP/TLS server error when receiving data\n");
  2414. return -1;
  2415. } else if (res == 0) {
  2416. ast_debug(2, "SIP TCP/TLS server has shut down\n");
  2417. return -1;
  2418. }
  2419. readbuf[res] = '\0';
  2420. ast_str_append(&req->data, 0, "%s", readbuf);
  2421. } else {
  2422. ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
  2423. ast_str_reset(tcptls_session->overflow_buf);
  2424. }
  2425. datalen = ast_str_strlen(req->data);
  2426. if (datalen > SIP_MAX_PACKET_SIZE) {
  2427. ast_log(LOG_WARNING, "Rejecting TCP/TLS packet from '%s' because way too large: %zu\n",
  2428. ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
  2429. return -1;
  2430. }
  2431. message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
  2432. }
  2433. return 0;
  2434. }
  2435. /*! \brief SIP TCP thread management function
  2436. This function reads from the socket, parses the packet into a request
  2437. */
  2438. static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
  2439. {
  2440. int res, timeout = -1, authenticated = 0, flags;
  2441. time_t start;
  2442. struct sip_request req = { 0, } , reqcpy = { 0, };
  2443. struct sip_threadinfo *me = NULL;
  2444. char buf[1024] = "";
  2445. struct pollfd fds[2] = { { 0 }, { 0 }, };
  2446. struct ast_tcptls_session_args *ca = NULL;
  2447. /* If this is a server session, then the connection has already been
  2448. * setup. Check if the authlimit has been reached and if not create the
  2449. * threadinfo object so we can access this thread for writing.
  2450. *
  2451. * if this is a client connection more work must be done.
  2452. * 1. We own the parent session args for a client connection. This pointer needs
  2453. * to be held on to so we can decrement it's ref count on thread destruction.
  2454. * 2. The threadinfo object was created before this thread was launched, however
  2455. * it must be found within the threadt table.
  2456. * 3. Last, the tcptls_session must be started.
  2457. */
  2458. if (!tcptls_session->client) {
  2459. if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
  2460. /* unauth_sessions is decremented in the cleanup code */
  2461. goto cleanup;
  2462. }
  2463. if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
  2464. ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
  2465. goto cleanup;
  2466. }
  2467. flags |= O_NONBLOCK;
  2468. if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
  2469. ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
  2470. goto cleanup;
  2471. }
  2472. if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
  2473. goto cleanup;
  2474. }
  2475. ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
  2476. } else {
  2477. struct sip_threadinfo tmp = {
  2478. .tcptls_session = tcptls_session,
  2479. };
  2480. if ((!(ca = tcptls_session->parent)) ||
  2481. (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
  2482. (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
  2483. goto cleanup;
  2484. }
  2485. }
  2486. flags = 1;
  2487. if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
  2488. ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
  2489. goto cleanup;
  2490. }
  2491. me->threadid = pthread_self();
  2492. ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
  2493. /* set up pollfd to watch for reads on both the socket and the alert_pipe */
  2494. fds[0].fd = tcptls_session->fd;
  2495. fds[1].fd = me->alert_pipe[0];
  2496. fds[0].events = fds[1].events = POLLIN | POLLPRI;
  2497. if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
  2498. goto cleanup;
  2499. }
  2500. if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
  2501. goto cleanup;
  2502. }
  2503. if(time(&start) == -1) {
  2504. ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
  2505. goto cleanup;
  2506. }
  2507. /*
  2508. * We cannot let the stream exclusively wait for data to arrive.
  2509. * We have to wake up the task to send outgoing messages.
  2510. */
  2511. ast_tcptls_stream_set_exclusive_input(tcptls_session->stream_cookie, 0);
  2512. ast_tcptls_stream_set_timeout_sequence(tcptls_session->stream_cookie, ast_tvnow(),
  2513. tcptls_session->client ? -1 : (authtimeout * 1000));
  2514. for (;;) {
  2515. struct ast_str *str_save;
  2516. if (!tcptls_session->client && req.authenticated && !authenticated) {
  2517. authenticated = 1;
  2518. ast_tcptls_stream_set_timeout_disable(tcptls_session->stream_cookie);
  2519. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  2520. }
  2521. /* calculate the timeout for unauthenticated server sessions */
  2522. if (!tcptls_session->client && !authenticated ) {
  2523. if ((timeout = sip_check_authtimeout(start)) < 0) {
  2524. goto cleanup;
  2525. }
  2526. if (timeout == 0) {
  2527. ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
  2528. goto cleanup;
  2529. }
  2530. } else {
  2531. timeout = -1;
  2532. }
  2533. if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
  2534. res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
  2535. if (res < 0) {
  2536. ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
  2537. goto cleanup;
  2538. } else if (res == 0) {
  2539. /* timeout */
  2540. ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
  2541. goto cleanup;
  2542. }
  2543. }
  2544. /*
  2545. * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
  2546. * and writes from alert_pipe fd.
  2547. */
  2548. if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
  2549. fds[0].revents = 0;
  2550. /* clear request structure */
  2551. str_save = req.data;
  2552. memset(&req, 0, sizeof(req));
  2553. req.data = str_save;
  2554. ast_str_reset(req.data);
  2555. str_save = reqcpy.data;
  2556. memset(&reqcpy, 0, sizeof(reqcpy));
  2557. reqcpy.data = str_save;
  2558. ast_str_reset(reqcpy.data);
  2559. memset(buf, 0, sizeof(buf));
  2560. if (tcptls_session->ssl) {
  2561. set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
  2562. req.socket.port = htons(ourport_tls);
  2563. } else {
  2564. set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
  2565. req.socket.port = htons(ourport_tcp);
  2566. }
  2567. req.socket.fd = tcptls_session->fd;
  2568. res = sip_tcptls_read(&req, tcptls_session, authenticated, start);
  2569. if (res < 0) {
  2570. goto cleanup;
  2571. }
  2572. req.socket.tcptls_session = tcptls_session;
  2573. handle_request_do(&req, &tcptls_session->remote_address);
  2574. }
  2575. if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
  2576. enum sip_tcptls_alert alert;
  2577. struct tcptls_packet *packet;
  2578. fds[1].revents = 0;
  2579. if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
  2580. ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
  2581. continue;
  2582. }
  2583. switch (alert) {
  2584. case TCPTLS_ALERT_STOP:
  2585. goto cleanup;
  2586. case TCPTLS_ALERT_DATA:
  2587. ao2_lock(me);
  2588. if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
  2589. ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
  2590. }
  2591. ao2_unlock(me);
  2592. if (packet) {
  2593. if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
  2594. ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
  2595. }
  2596. ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
  2597. }
  2598. break;
  2599. default:
  2600. ast_log(LOG_ERROR, "Unknown tcptls thread alert '%u'\n", alert);
  2601. }
  2602. }
  2603. }
  2604. ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
  2605. cleanup:
  2606. if (tcptls_session && !tcptls_session->client && !authenticated) {
  2607. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  2608. }
  2609. if (me) {
  2610. ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
  2611. ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
  2612. }
  2613. deinit_req(&reqcpy);
  2614. deinit_req(&req);
  2615. /* if client, we own the parent session arguments and must decrement ref */
  2616. if (ca) {
  2617. ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
  2618. }
  2619. if (tcptls_session) {
  2620. ast_mutex_lock(&tcptls_session->lock);
  2621. ast_tcptls_close_session_file(tcptls_session);
  2622. tcptls_session->parent = NULL;
  2623. ast_mutex_unlock(&tcptls_session->lock);
  2624. ao2_ref(tcptls_session, -1);
  2625. tcptls_session = NULL;
  2626. }
  2627. return NULL;
  2628. }
  2629. #ifdef REF_DEBUG
  2630. #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
  2631. #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
  2632. static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
  2633. {
  2634. if (peer)
  2635. __ao2_ref_debug(peer, 1, tag, file, line, func);
  2636. else
  2637. ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
  2638. return peer;
  2639. }
  2640. static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
  2641. {
  2642. if (peer)
  2643. __ao2_ref_debug(peer, -1, tag, file, line, func);
  2644. return NULL;
  2645. }
  2646. #else
  2647. /*!
  2648. * helper functions to unreference various types of objects.
  2649. * By handling them this way, we don't have to declare the
  2650. * destructor on each call, which removes the chance of errors.
  2651. */
  2652. static void *unref_peer(struct sip_peer *peer, char *tag)
  2653. {
  2654. ao2_t_ref(peer, -1, tag);
  2655. return NULL;
  2656. }
  2657. static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
  2658. {
  2659. ao2_t_ref(peer, 1, tag);
  2660. return peer;
  2661. }
  2662. #endif /* REF_DEBUG */
  2663. static void peer_sched_cleanup(struct sip_peer *peer)
  2664. {
  2665. if (peer->pokeexpire != -1) {
  2666. AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
  2667. unref_peer(peer, "removing poke peer ref"));
  2668. }
  2669. if (peer->expire != -1) {
  2670. AST_SCHED_DEL_UNREF(sched, peer->expire,
  2671. unref_peer(peer, "remove register expire ref"));
  2672. }
  2673. }
  2674. typedef enum {
  2675. SIP_PEERS_MARKED,
  2676. SIP_PEERS_ALL,
  2677. } peer_unlink_flag_t;
  2678. /* this func is used with ao2_callback to unlink/delete all marked or linked
  2679. peers, depending on arg */
  2680. static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
  2681. {
  2682. struct sip_peer *peer = peerobj;
  2683. peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
  2684. if (which == SIP_PEERS_ALL || peer->the_mark) {
  2685. peer_sched_cleanup(peer);
  2686. if (peer->dnsmgr) {
  2687. ast_dnsmgr_release(peer->dnsmgr);
  2688. peer->dnsmgr = NULL;
  2689. unref_peer(peer, "Release peer from dnsmgr");
  2690. }
  2691. return CMP_MATCH;
  2692. }
  2693. return 0;
  2694. }
  2695. static void unlink_peers_from_tables(peer_unlink_flag_t flag)
  2696. {
  2697. ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
  2698. match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
  2699. ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
  2700. match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
  2701. }
  2702. /* \brief Unlink all marked peers from ao2 containers */
  2703. static void unlink_marked_peers_from_tables(void)
  2704. {
  2705. unlink_peers_from_tables(SIP_PEERS_MARKED);
  2706. }
  2707. static void unlink_all_peers_from_tables(void)
  2708. {
  2709. unlink_peers_from_tables(SIP_PEERS_ALL);
  2710. }
  2711. /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
  2712. *
  2713. * This function sets pvt's outboundproxy pointer to the one referenced
  2714. * by the proxy parameter. Because proxy may be a refcounted object, and
  2715. * because pvt's old outboundproxy may also be a refcounted object, we need
  2716. * to maintain the proper refcounts.
  2717. *
  2718. * \param pvt The sip_pvt for which we wish to set the outboundproxy
  2719. * \param proxy The sip_proxy which we will point pvt towards.
  2720. * \return Returns void
  2721. */
  2722. static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
  2723. {
  2724. struct sip_proxy *old_obproxy = pvt->outboundproxy;
  2725. /* The sip_cfg.outboundproxy is statically allocated, and so
  2726. * we don't ever need to adjust refcounts for it
  2727. */
  2728. if (proxy && proxy != &sip_cfg.outboundproxy) {
  2729. ao2_ref(proxy, +1);
  2730. }
  2731. pvt->outboundproxy = proxy;
  2732. if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
  2733. ao2_ref(old_obproxy, -1);
  2734. }
  2735. }
  2736. /*!
  2737. * \brief Unlink a dialog from the dialogs container, as well as any other places
  2738. * that it may be currently stored.
  2739. *
  2740. * \note A reference to the dialog must be held before calling this function, and this
  2741. * function does not release that reference.
  2742. */
  2743. void dialog_unlink_all(struct sip_pvt *dialog)
  2744. {
  2745. struct sip_pkt *cp;
  2746. struct ast_channel *owner;
  2747. dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
  2748. ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
  2749. /* Unlink us from the owner (channel) if we have one */
  2750. owner = sip_pvt_lock_full(dialog);
  2751. if (owner) {
  2752. ast_debug(1, "Detaching from channel %s\n", owner->name);
  2753. owner->tech_pvt = dialog_unref(owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
  2754. ast_channel_unlock(owner);
  2755. ast_channel_unref(owner);
  2756. dialog->owner = NULL;
  2757. }
  2758. sip_pvt_unlock(dialog);
  2759. if (dialog->registry) {
  2760. if (dialog->registry->call == dialog) {
  2761. dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
  2762. }
  2763. dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
  2764. }
  2765. if (dialog->stateid != -1) {
  2766. ast_extension_state_del(dialog->stateid, cb_extensionstate);
  2767. dialog->stateid = -1;
  2768. }
  2769. /* Remove link from peer to subscription of MWI */
  2770. if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
  2771. dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
  2772. }
  2773. if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
  2774. dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
  2775. }
  2776. /* remove all current packets in this dialog */
  2777. while((cp = dialog->packets)) {
  2778. dialog->packets = dialog->packets->next;
  2779. AST_SCHED_DEL(sched, cp->retransid);
  2780. dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
  2781. if (cp->data) {
  2782. ast_free(cp->data);
  2783. }
  2784. ast_free(cp);
  2785. }
  2786. 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"));
  2787. 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"));
  2788. if (dialog->autokillid > -1) {
  2789. 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"));
  2790. }
  2791. if (dialog->request_queue_sched_id > -1) {
  2792. 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"));
  2793. }
  2794. 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"));
  2795. if (dialog->t38id > -1) {
  2796. 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"));
  2797. }
  2798. if (dialog->stimer) {
  2799. stop_session_timer(dialog);
  2800. }
  2801. dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
  2802. }
  2803. void *registry_unref(struct sip_registry *reg, char *tag)
  2804. {
  2805. ast_debug(3, "SIP Registry %s: refcount now %u\n", reg->hostname, reg->refcount - 1);
  2806. ASTOBJ_UNREF(reg, sip_registry_destroy);
  2807. return NULL;
  2808. }
  2809. /*! \brief Add object reference to SIP registry */
  2810. static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
  2811. {
  2812. ast_debug(3, "SIP Registry %s: refcount now %u\n", reg->hostname, reg->refcount + 1);
  2813. return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
  2814. }
  2815. /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
  2816. static struct ast_udptl_protocol sip_udptl = {
  2817. .type = "SIP",
  2818. .get_udptl_info = sip_get_udptl_peer,
  2819. .set_udptl_peer = sip_set_udptl_peer,
  2820. };
  2821. static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
  2822. __attribute__((format(printf, 2, 3)));
  2823. /*! \brief Convert transfer status to string */
  2824. static const char *referstatus2str(enum referstatus rstatus)
  2825. {
  2826. return map_x_s(referstatusstrings, rstatus, "");
  2827. }
  2828. static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
  2829. {
  2830. if (pvt->final_destruction_scheduled) {
  2831. return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
  2832. }
  2833. append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
  2834. pvt->needdestroy = 1;
  2835. }
  2836. /*! \brief Initialize the initital request packet in the pvt structure.
  2837. This packet is used for creating replies and future requests in
  2838. a dialog */
  2839. static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
  2840. {
  2841. if (p->initreq.headers) {
  2842. ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
  2843. } else {
  2844. ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  2845. }
  2846. /* Use this as the basis */
  2847. copy_request(&p->initreq, req);
  2848. parse_request(&p->initreq);
  2849. if (req->debug) {
  2850. ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  2851. }
  2852. }
  2853. /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
  2854. static void sip_alreadygone(struct sip_pvt *dialog)
  2855. {
  2856. ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
  2857. dialog->alreadygone = 1;
  2858. }
  2859. /*! Resolve DNS srv name or host name in a sip_proxy structure */
  2860. static int proxy_update(struct sip_proxy *proxy)
  2861. {
  2862. /* if it's actually an IP address and not a name,
  2863. there's no need for a managed lookup */
  2864. if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
  2865. /* Ok, not an IP address, then let's check if it's a domain or host */
  2866. /* XXX Todo - if we have proxy port, don't do SRV */
  2867. proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP); /* Filter address family */
  2868. if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
  2869. ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
  2870. return FALSE;
  2871. }
  2872. }
  2873. ast_sockaddr_set_port(&proxy->ip, proxy->port);
  2874. proxy->last_dnsupdate = time(NULL);
  2875. return TRUE;
  2876. }
  2877. /*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is
  2878. * non-NULL, no allocation is performed and dest is used instead.
  2879. * On error NULL is returned. */
  2880. static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
  2881. {
  2882. char *mutable_proxy, *sep, *name;
  2883. int allocated = 0;
  2884. if (!dest) {
  2885. dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
  2886. if (!dest) {
  2887. ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
  2888. return NULL;
  2889. }
  2890. allocated = 1;
  2891. }
  2892. /* Format is: [transport://]name[:port][,force] */
  2893. mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
  2894. sep = strchr(mutable_proxy, ',');
  2895. if (sep) {
  2896. *sep++ = '\0';
  2897. dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
  2898. } else {
  2899. dest->force = FALSE;
  2900. }
  2901. sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
  2902. /* Check that there is a name at all */
  2903. if (ast_strlen_zero(name)) {
  2904. if (allocated) {
  2905. ao2_ref(dest, -1);
  2906. } else {
  2907. dest->name[0] = '\0';
  2908. }
  2909. return NULL;
  2910. }
  2911. ast_copy_string(dest->name, name, sizeof(dest->name));
  2912. /* Resolve host immediately */
  2913. proxy_update(dest);
  2914. return dest;
  2915. }
  2916. /*! \brief converts ascii port to int representation. If no
  2917. * pt buffer is provided or the pt has errors when being converted
  2918. * to an int value, the port provided as the standard is used.
  2919. */
  2920. unsigned int port_str2int(const char *pt, unsigned int standard)
  2921. {
  2922. int port = standard;
  2923. if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
  2924. port = standard;
  2925. }
  2926. return port;
  2927. }
  2928. /*! \brief Get default outbound proxy or global proxy */
  2929. static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
  2930. {
  2931. if (dialog && dialog->options && dialog->options->outboundproxy) {
  2932. if (sipdebug) {
  2933. ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
  2934. }
  2935. append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
  2936. return dialog->options->outboundproxy;
  2937. }
  2938. if (peer && peer->outboundproxy) {
  2939. if (sipdebug) {
  2940. ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
  2941. }
  2942. append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
  2943. return peer->outboundproxy;
  2944. }
  2945. if (sip_cfg.outboundproxy.name[0]) {
  2946. if (sipdebug) {
  2947. ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
  2948. }
  2949. append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
  2950. return &sip_cfg.outboundproxy;
  2951. }
  2952. if (sipdebug) {
  2953. ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
  2954. }
  2955. return NULL;
  2956. }
  2957. /*! \brief returns true if 'name' (with optional trailing whitespace)
  2958. * matches the sip method 'id'.
  2959. * Strictly speaking, SIP methods are case SENSITIVE, but we do
  2960. * a case-insensitive comparison to be more tolerant.
  2961. * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
  2962. */
  2963. static int method_match(enum sipmethod id, const char *name)
  2964. {
  2965. int len = strlen(sip_methods[id].text);
  2966. int l_name = name ? strlen(name) : 0;
  2967. /* true if the string is long enough, and ends with whitespace, and matches */
  2968. return (l_name >= len && name && name[len] < 33 &&
  2969. !strncasecmp(sip_methods[id].text, name, len));
  2970. }
  2971. /*! \brief find_sip_method: Find SIP method from header */
  2972. static int find_sip_method(const char *msg)
  2973. {
  2974. int i, res = 0;
  2975. if (ast_strlen_zero(msg)) {
  2976. return 0;
  2977. }
  2978. for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
  2979. if (method_match(i, msg)) {
  2980. res = sip_methods[i].id;
  2981. }
  2982. }
  2983. return res;
  2984. }
  2985. /*! \brief See if we pass debug IP filter */
  2986. static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
  2987. {
  2988. /* Can't debug if sipdebug is not enabled */
  2989. if (!sipdebug) {
  2990. return 0;
  2991. }
  2992. /* A null debug_addr means we'll debug any address */
  2993. if (ast_sockaddr_isnull(&debugaddr)) {
  2994. return 1;
  2995. }
  2996. /* If no port was specified for a debug address, just compare the
  2997. * addresses, otherwise compare the address and port
  2998. */
  2999. if (ast_sockaddr_port(&debugaddr)) {
  3000. return !ast_sockaddr_cmp(&debugaddr, addr);
  3001. } else {
  3002. return !ast_sockaddr_cmp_addr(&debugaddr, addr);
  3003. }
  3004. }
  3005. /*! \brief The real destination address for a write */
  3006. static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
  3007. {
  3008. if (p->outboundproxy) {
  3009. return &p->outboundproxy->ip;
  3010. }
  3011. 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;
  3012. }
  3013. /*! \brief Display SIP nat mode */
  3014. static const char *sip_nat_mode(const struct sip_pvt *p)
  3015. {
  3016. return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
  3017. }
  3018. /*! \brief Test PVT for debugging output */
  3019. static inline int sip_debug_test_pvt(struct sip_pvt *p)
  3020. {
  3021. if (!sipdebug) {
  3022. return 0;
  3023. }
  3024. return sip_debug_test_addr(sip_real_dst(p));
  3025. }
  3026. /*! \brief Return int representing a bit field of transport types found in const char *transport */
  3027. static int get_transport_str2enum(const char *transport)
  3028. {
  3029. int res = 0;
  3030. if (ast_strlen_zero(transport)) {
  3031. return res;
  3032. }
  3033. if (!strcasecmp(transport, "udp")) {
  3034. res |= SIP_TRANSPORT_UDP;
  3035. }
  3036. if (!strcasecmp(transport, "tcp")) {
  3037. res |= SIP_TRANSPORT_TCP;
  3038. }
  3039. if (!strcasecmp(transport, "tls")) {
  3040. res |= SIP_TRANSPORT_TLS;
  3041. }
  3042. return res;
  3043. }
  3044. /*! \brief Return configuration of transports for a device */
  3045. static inline const char *get_transport_list(unsigned int transports) {
  3046. switch (transports) {
  3047. case SIP_TRANSPORT_UDP:
  3048. return "UDP";
  3049. case SIP_TRANSPORT_TCP:
  3050. return "TCP";
  3051. case SIP_TRANSPORT_TLS:
  3052. return "TLS";
  3053. case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
  3054. return "TCP,UDP";
  3055. case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
  3056. return "TLS,UDP";
  3057. case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
  3058. return "TLS,TCP";
  3059. default:
  3060. return transports ?
  3061. "TLS,TCP,UDP" : "UNKNOWN";
  3062. }
  3063. }
  3064. /*! \brief Return transport as string */
  3065. static inline const char *get_transport(enum sip_transport t)
  3066. {
  3067. switch (t) {
  3068. case SIP_TRANSPORT_UDP:
  3069. return "UDP";
  3070. case SIP_TRANSPORT_TCP:
  3071. return "TCP";
  3072. case SIP_TRANSPORT_TLS:
  3073. return "TLS";
  3074. }
  3075. return "UNKNOWN";
  3076. }
  3077. /*! \brief Return protocol string for srv dns query */
  3078. static inline const char *get_srv_protocol(enum sip_transport t)
  3079. {
  3080. switch (t) {
  3081. case SIP_TRANSPORT_UDP:
  3082. return "udp";
  3083. case SIP_TRANSPORT_TLS:
  3084. case SIP_TRANSPORT_TCP:
  3085. return "tcp";
  3086. }
  3087. return "udp";
  3088. }
  3089. /*! \brief Return service string for srv dns query */
  3090. static inline const char *get_srv_service(enum sip_transport t)
  3091. {
  3092. switch (t) {
  3093. case SIP_TRANSPORT_TCP:
  3094. case SIP_TRANSPORT_UDP:
  3095. return "sip";
  3096. case SIP_TRANSPORT_TLS:
  3097. return "sips";
  3098. }
  3099. return "sip";
  3100. }
  3101. /*! \brief Return transport of dialog.
  3102. \note this is based on a false assumption. We don't always use the
  3103. outbound proxy for all requests in a dialog. It depends on the
  3104. "force" parameter. The FIRST request is always sent to the ob proxy.
  3105. \todo Fix this function to work correctly
  3106. */
  3107. static inline const char *get_transport_pvt(struct sip_pvt *p)
  3108. {
  3109. if (p->outboundproxy && p->outboundproxy->transport) {
  3110. set_socket_transport(&p->socket, p->outboundproxy->transport);
  3111. }
  3112. return get_transport(p->socket.type);
  3113. }
  3114. /*!
  3115. * \internal
  3116. * \brief Transmit SIP message
  3117. *
  3118. * \details
  3119. * Sends a SIP request or response on a given socket (in the pvt)
  3120. * \note
  3121. * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
  3122. *
  3123. * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
  3124. */
  3125. static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
  3126. {
  3127. int res = 0;
  3128. const struct ast_sockaddr *dst = sip_real_dst(p);
  3129. 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));
  3130. if (sip_prepare_socket(p) < 0) {
  3131. return XMIT_ERROR;
  3132. }
  3133. if (p->socket.type == SIP_TRANSPORT_UDP) {
  3134. res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
  3135. } else if (p->socket.tcptls_session) {
  3136. res = sip_tcptls_write(p->socket.tcptls_session, ast_str_buffer(data), ast_str_strlen(data));
  3137. } else {
  3138. ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
  3139. return XMIT_ERROR;
  3140. }
  3141. if (res == -1) {
  3142. switch (errno) {
  3143. case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
  3144. case EHOSTUNREACH: /* Host can't be reached */
  3145. case ENETDOWN: /* Interface down */
  3146. case ENETUNREACH: /* Network failure */
  3147. case ECONNREFUSED: /* ICMP port unreachable */
  3148. res = XMIT_ERROR; /* Don't bother with trying to transmit again */
  3149. }
  3150. }
  3151. if (res != ast_str_strlen(data)) {
  3152. 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));
  3153. }
  3154. return res;
  3155. }
  3156. /*! \brief Build a Via header for a request */
  3157. static void build_via(struct sip_pvt *p)
  3158. {
  3159. /* Work around buggy UNIDEN UIP200 firmware */
  3160. const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
  3161. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  3162. snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
  3163. get_transport_pvt(p),
  3164. ast_sockaddr_stringify_remote(&p->ourip),
  3165. (unsigned)p->branch, rport);
  3166. }
  3167. /*! \brief NAT fix - decide which IP address to use for Asterisk server?
  3168. *
  3169. * Using the localaddr structure built up with localnet statements in sip.conf
  3170. * apply it to their address to see if we need to substitute our
  3171. * externaddr or can get away with our internal bindaddr
  3172. * 'us' is always overwritten.
  3173. */
  3174. static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
  3175. {
  3176. struct ast_sockaddr theirs;
  3177. /* Set want_remap to non-zero if we want to remap 'us' to an externally
  3178. * reachable IP address and port. This is done if:
  3179. * 1. we have a localaddr list (containing 'internal' addresses marked
  3180. * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
  3181. * and AST_SENSE_ALLOW on 'external' ones);
  3182. * 2. externaddr is set, so we know what to use as the
  3183. * externally visible address;
  3184. * 3. the remote address, 'them', is external;
  3185. * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
  3186. * when passed to ast_apply_ha() so it does need to be remapped.
  3187. * This fourth condition is checked later.
  3188. */
  3189. int want_remap = 0;
  3190. ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
  3191. /* now ask the system what would it use to talk to 'them' */
  3192. ast_ouraddrfor(them, us);
  3193. ast_sockaddr_copy(&theirs, them);
  3194. if (ast_sockaddr_is_ipv6(&theirs)) {
  3195. if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
  3196. ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
  3197. "but we're using IPv6, which doesn't need it. Please "
  3198. "remove \"localnet\" and/or \"externaddr\" settings.\n");
  3199. }
  3200. } else {
  3201. want_remap = localaddr &&
  3202. !ast_sockaddr_isnull(&externaddr) &&
  3203. ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
  3204. }
  3205. if (want_remap &&
  3206. (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
  3207. /* if we used externhost, see if it is time to refresh the info */
  3208. if (externexpire && time(NULL) >= externexpire) {
  3209. if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
  3210. ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
  3211. }
  3212. externexpire = time(NULL) + externrefresh;
  3213. }
  3214. if (!ast_sockaddr_isnull(&externaddr)) {
  3215. ast_sockaddr_copy(us, &externaddr);
  3216. switch (p->socket.type) {
  3217. case SIP_TRANSPORT_TCP:
  3218. if (!externtcpport && ast_sockaddr_port(&externaddr)) {
  3219. /* for consistency, default to the externaddr port */
  3220. externtcpport = ast_sockaddr_port(&externaddr);
  3221. }
  3222. ast_sockaddr_set_port(us, externtcpport);
  3223. break;
  3224. case SIP_TRANSPORT_TLS:
  3225. ast_sockaddr_set_port(us, externtlsport);
  3226. break;
  3227. case SIP_TRANSPORT_UDP:
  3228. if (!ast_sockaddr_port(&externaddr)) {
  3229. ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
  3230. }
  3231. break;
  3232. default:
  3233. break;
  3234. }
  3235. }
  3236. ast_debug(1, "Target address %s is not local, substituting externaddr\n",
  3237. ast_sockaddr_stringify(them));
  3238. } else {
  3239. /* no remapping, but we bind to a specific address, so use it. */
  3240. switch (p->socket.type) {
  3241. case SIP_TRANSPORT_TCP:
  3242. if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
  3243. ast_sockaddr_copy(us,
  3244. &sip_tcp_desc.local_address);
  3245. } else {
  3246. ast_sockaddr_set_port(us,
  3247. ast_sockaddr_port(&sip_tcp_desc.local_address));
  3248. }
  3249. break;
  3250. case SIP_TRANSPORT_TLS:
  3251. if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
  3252. ast_sockaddr_copy(us,
  3253. &sip_tls_desc.local_address);
  3254. } else {
  3255. ast_sockaddr_set_port(us,
  3256. ast_sockaddr_port(&sip_tls_desc.local_address));
  3257. }
  3258. break;
  3259. case SIP_TRANSPORT_UDP:
  3260. /* fall through on purpose */
  3261. default:
  3262. if (!ast_sockaddr_is_any(&bindaddr)) {
  3263. ast_sockaddr_copy(us, &bindaddr);
  3264. }
  3265. if (!ast_sockaddr_port(us)) {
  3266. ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
  3267. }
  3268. }
  3269. }
  3270. ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
  3271. }
  3272. /*! \brief Append to SIP dialog history with arg list */
  3273. static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
  3274. {
  3275. char buf[80], *c = buf; /* max history length */
  3276. struct sip_history *hist;
  3277. int l;
  3278. vsnprintf(buf, sizeof(buf), fmt, ap);
  3279. strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
  3280. l = strlen(buf) + 1;
  3281. if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
  3282. return;
  3283. }
  3284. if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
  3285. ast_free(hist);
  3286. return;
  3287. }
  3288. memcpy(hist->event, buf, l);
  3289. if (p->history_entries == MAX_HISTORY_ENTRIES) {
  3290. struct sip_history *oldest;
  3291. oldest = AST_LIST_REMOVE_HEAD(p->history, list);
  3292. p->history_entries--;
  3293. ast_free(oldest);
  3294. }
  3295. AST_LIST_INSERT_TAIL(p->history, hist, list);
  3296. p->history_entries++;
  3297. }
  3298. /*! \brief Append to SIP dialog history with arg list */
  3299. static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
  3300. {
  3301. va_list ap;
  3302. if (!p) {
  3303. return;
  3304. }
  3305. if (!p->do_history && !recordhistory && !dumphistory) {
  3306. return;
  3307. }
  3308. va_start(ap, fmt);
  3309. append_history_va(p, fmt, ap);
  3310. va_end(ap);
  3311. return;
  3312. }
  3313. /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
  3314. static int retrans_pkt(const void *data)
  3315. {
  3316. struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
  3317. int reschedule = DEFAULT_RETRANS;
  3318. int xmitres = 0;
  3319. /* how many ms until retrans timeout is reached */
  3320. int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
  3321. /* Do not retransmit if time out is reached. This will be negative if the time between
  3322. * the first transmission and now is larger than our timeout period. This is a fail safe
  3323. * check in case the scheduler gets behind or the clock is changed. */
  3324. if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
  3325. pkt->retrans_stop = 1;
  3326. }
  3327. /* Lock channel PVT */
  3328. sip_pvt_lock(pkt->owner);
  3329. if (!pkt->retrans_stop) {
  3330. pkt->retrans++;
  3331. if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
  3332. if (sipdebug) {
  3333. ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
  3334. pkt->retransid,
  3335. sip_methods[pkt->method].text,
  3336. pkt->method);
  3337. }
  3338. } else {
  3339. int siptimer_a;
  3340. if (sipdebug) {
  3341. ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
  3342. pkt->retransid,
  3343. pkt->retrans,
  3344. sip_methods[pkt->method].text,
  3345. pkt->method);
  3346. }
  3347. if (!pkt->timer_a) {
  3348. pkt->timer_a = 2 ;
  3349. } else {
  3350. pkt->timer_a = 2 * pkt->timer_a;
  3351. }
  3352. /* For non-invites, a maximum of 4 secs */
  3353. siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
  3354. if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
  3355. siptimer_a = 4000;
  3356. }
  3357. /* Reschedule re-transmit */
  3358. reschedule = siptimer_a;
  3359. ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
  3360. pkt->retrans + 1,
  3361. siptimer_a,
  3362. pkt->timer_t1,
  3363. pkt->retransid);
  3364. }
  3365. if (sip_debug_test_pvt(pkt->owner)) {
  3366. const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
  3367. ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
  3368. pkt->retrans, sip_nat_mode(pkt->owner),
  3369. ast_sockaddr_stringify(dst),
  3370. ast_str_buffer(pkt->data));
  3371. }
  3372. append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
  3373. xmitres = __sip_xmit(pkt->owner, pkt->data);
  3374. /* If there was no error during the network transmission, schedule the next retransmission,
  3375. * but if the next retransmission is going to be beyond our timeout period, mark the packet's
  3376. * stop_retrans value and set the next retransmit to be the exact time of timeout. This will
  3377. * allow any responses to the packet to be processed before the packet is destroyed on the next
  3378. * call to this function by the scheduler. */
  3379. if (xmitres != XMIT_ERROR) {
  3380. if (reschedule >= diff) {
  3381. pkt->retrans_stop = 1;
  3382. reschedule = diff;
  3383. }
  3384. sip_pvt_unlock(pkt->owner);
  3385. return reschedule;
  3386. }
  3387. }
  3388. /* At this point, either the packet's retransmission timed out, or there was a
  3389. * transmission error, either way destroy the scheduler item and this packet. */
  3390. pkt->retransid = -1; /* Kill this scheduler item */
  3391. if (pkt->method != SIP_OPTIONS && xmitres == 0) {
  3392. if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
  3393. 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"
  3394. "Packet timed out after %dms with no response\n",
  3395. pkt->owner->callid,
  3396. pkt->seqno,
  3397. pkt->is_fatal ? "Critical" : "Non-critical",
  3398. pkt->is_resp ? "Response" : "Request",
  3399. (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
  3400. }
  3401. } else if (pkt->method == SIP_OPTIONS && sipdebug) {
  3402. 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);
  3403. }
  3404. if (xmitres == XMIT_ERROR) {
  3405. ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
  3406. append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
  3407. } else {
  3408. append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
  3409. }
  3410. if (pkt->is_fatal) {
  3411. while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
  3412. sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
  3413. usleep(1);
  3414. sip_pvt_lock(pkt->owner);
  3415. }
  3416. if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
  3417. pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
  3418. }
  3419. if (pkt->owner->owner) {
  3420. 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);
  3421. if (pkt->is_resp &&
  3422. (pkt->response_code >= 200) &&
  3423. (pkt->response_code < 300) &&
  3424. pkt->owner->pendinginvite &&
  3425. ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  3426. /* This is a timeout of the 2XX response to a pending INVITE. In this case terminate the INVITE
  3427. * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
  3428. * will send the BYE as long as the dialog is not set as "alreadygone")
  3429. * RFC 3261 section 13.3.1.4.
  3430. * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
  3431. * an ACK, the dialog is confirmed, but the session SHOULD be terminated. This is
  3432. * accomplished with a BYE, as described in Section 15." */
  3433. pkt->owner->invitestate = INV_TERMINATED;
  3434. pkt->owner->pendinginvite = 0;
  3435. } else {
  3436. /* there is nothing left to do, mark the dialog as gone */
  3437. sip_alreadygone(pkt->owner);
  3438. }
  3439. ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
  3440. ast_channel_unlock(pkt->owner->owner);
  3441. } else {
  3442. /* If no channel owner, destroy now */
  3443. /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
  3444. if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
  3445. pvt_set_needdestroy(pkt->owner, "no response to critical packet");
  3446. sip_alreadygone(pkt->owner);
  3447. append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
  3448. }
  3449. }
  3450. } else if (pkt->owner->pendinginvite == pkt->seqno) {
  3451. ast_log(LOG_WARNING, "Timeout on %s on non-critical invite transaction.\n", pkt->owner->callid);
  3452. pkt->owner->invitestate = INV_TERMINATED;
  3453. pkt->owner->pendinginvite = 0;
  3454. check_pendings(pkt->owner);
  3455. }
  3456. if (pkt->method == SIP_BYE) {
  3457. /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
  3458. sip_alreadygone(pkt->owner);
  3459. if (pkt->owner->owner) {
  3460. ast_channel_unlock(pkt->owner->owner);
  3461. }
  3462. append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
  3463. pvt_set_needdestroy(pkt->owner, "no response to BYE");
  3464. }
  3465. /* Remove the packet */
  3466. for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
  3467. if (cur == pkt) {
  3468. UNLINK(cur, pkt->owner->packets, prev);
  3469. sip_pvt_unlock(pkt->owner);
  3470. if (pkt->owner) {
  3471. pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
  3472. }
  3473. if (pkt->data) {
  3474. ast_free(pkt->data);
  3475. }
  3476. pkt->data = NULL;
  3477. ast_free(pkt);
  3478. return 0;
  3479. }
  3480. }
  3481. /* error case */
  3482. ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
  3483. sip_pvt_unlock(pkt->owner);
  3484. return 0;
  3485. }
  3486. /*!
  3487. * \internal
  3488. * \brief Transmit packet with retransmits
  3489. * \return 0 on success, -1 on failure to allocate packet
  3490. */
  3491. static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
  3492. {
  3493. struct sip_pkt *pkt = NULL;
  3494. int siptimer_a = DEFAULT_RETRANS;
  3495. int xmitres = 0;
  3496. unsigned respid;
  3497. if (sipmethod == SIP_INVITE) {
  3498. /* Note this is a pending invite */
  3499. p->pendinginvite = seqno;
  3500. }
  3501. /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
  3502. /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
  3503. /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
  3504. if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
  3505. xmitres = __sip_xmit(p, data); /* Send packet */
  3506. if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
  3507. append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
  3508. return AST_FAILURE;
  3509. } else {
  3510. return AST_SUCCESS;
  3511. }
  3512. }
  3513. if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
  3514. return AST_FAILURE;
  3515. }
  3516. /* copy data, add a terminator and save length */
  3517. if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
  3518. ast_free(pkt);
  3519. return AST_FAILURE;
  3520. }
  3521. ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
  3522. /* copy other parameters from the caller */
  3523. pkt->method = sipmethod;
  3524. pkt->seqno = seqno;
  3525. pkt->is_resp = resp;
  3526. pkt->is_fatal = fatal;
  3527. pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
  3528. pkt->next = p->packets;
  3529. p->packets = pkt; /* Add it to the queue */
  3530. if (resp) {
  3531. /* Parse out the response code */
  3532. if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
  3533. pkt->response_code = respid;
  3534. }
  3535. }
  3536. pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
  3537. pkt->retransid = -1;
  3538. if (pkt->timer_t1) {
  3539. siptimer_a = pkt->timer_t1;
  3540. }
  3541. pkt->time_sent = ast_tvnow(); /* time packet was sent */
  3542. pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
  3543. /* Schedule retransmission */
  3544. AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
  3545. if (sipdebug) {
  3546. ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
  3547. }
  3548. xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
  3549. if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
  3550. append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
  3551. ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
  3552. AST_SCHED_DEL(sched, pkt->retransid);
  3553. p->packets = pkt->next;
  3554. pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
  3555. ast_free(pkt->data);
  3556. ast_free(pkt);
  3557. return AST_FAILURE;
  3558. } else {
  3559. /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
  3560. * only wakes up every 1000ms by default, we have to poke the thread here to make
  3561. * sure it successfully detects this must be retransmitted in less time than
  3562. * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
  3563. if (monitor_thread != AST_PTHREADT_NULL) {
  3564. pthread_kill(monitor_thread, SIGURG);
  3565. }
  3566. return AST_SUCCESS;
  3567. }
  3568. }
  3569. /*! \brief Kill a SIP dialog (called only by the scheduler)
  3570. * The scheduler has a reference to this dialog when p->autokillid != -1,
  3571. * and we are called using that reference. So if the event is not
  3572. * rescheduled, we need to call dialog_unref().
  3573. */
  3574. static int __sip_autodestruct(const void *data)
  3575. {
  3576. struct sip_pvt *p = (struct sip_pvt *)data;
  3577. struct ast_channel *owner;
  3578. /* If this is a subscription, tell the phone that we got a timeout */
  3579. if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
  3580. transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
  3581. p->subscribed = NONE;
  3582. append_history(p, "Subscribestatus", "timeout");
  3583. ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
  3584. return 10000; /* Reschedule this destruction so that we know that it's gone */
  3585. }
  3586. /* If there are packets still waiting for delivery, delay the destruction */
  3587. if (p->packets) {
  3588. if (!p->needdestroy) {
  3589. char method_str[31];
  3590. ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
  3591. append_history(p, "ReliableXmit", "timeout");
  3592. if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
  3593. if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
  3594. pvt_set_needdestroy(p, "autodestruct");
  3595. }
  3596. }
  3597. return 10000;
  3598. } else {
  3599. /* They've had their chance to respond. Time to bail */
  3600. __sip_pretend_ack(p);
  3601. }
  3602. }
  3603. /* Reset schedule ID */
  3604. p->autokillid = -1;
  3605. /*
  3606. * Lock both the pvt and the channel safely so that we can queue up a frame.
  3607. */
  3608. owner = sip_pvt_lock_full(p);
  3609. if (owner) {
  3610. ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner %s in place (Method: %s). Rescheduling destruction for 10000 ms\n", p->callid, owner->name, sip_methods[p->method].text);
  3611. ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
  3612. ast_channel_unlock(owner);
  3613. ast_channel_unref(owner);
  3614. sip_pvt_unlock(p);
  3615. return 10000;
  3616. } else if (p->refer && !p->alreadygone) {
  3617. ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
  3618. stop_media_flows(p);
  3619. transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
  3620. append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
  3621. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  3622. } else {
  3623. append_history(p, "AutoDestroy", "%s", p->callid);
  3624. ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
  3625. sip_pvt_unlock(p);
  3626. dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
  3627. sip_pvt_lock(p);
  3628. /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
  3629. /* sip_destroy(p); */ /* Go ahead and destroy dialog. All attempts to recover is done */
  3630. /* sip_destroy also absorbs the reference */
  3631. }
  3632. sip_pvt_unlock(p);
  3633. dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
  3634. return 0;
  3635. }
  3636. /*! \brief Schedule final destruction of SIP dialog. This can not be canceled.
  3637. * This function is used to keep a dialog around for a period of time in order
  3638. * to properly respond to any retransmits. */
  3639. void sip_scheddestroy_final(struct sip_pvt *p, int ms)
  3640. {
  3641. if (p->final_destruction_scheduled) {
  3642. return; /* already set final destruction */
  3643. }
  3644. sip_scheddestroy(p, ms);
  3645. if (p->autokillid != -1) {
  3646. p->final_destruction_scheduled = 1;
  3647. }
  3648. }
  3649. /*! \brief Schedule destruction of SIP dialog */
  3650. void sip_scheddestroy(struct sip_pvt *p, int ms)
  3651. {
  3652. if (p->final_destruction_scheduled) {
  3653. return; /* already set final destruction */
  3654. }
  3655. if (ms < 0) {
  3656. if (p->timer_t1 == 0) {
  3657. p->timer_t1 = global_t1; /* Set timer T1 if not set (RFC 3261) */
  3658. }
  3659. if (p->timer_b == 0) {
  3660. p->timer_b = global_timer_b; /* Set timer B if not set (RFC 3261) */
  3661. }
  3662. ms = p->timer_t1 * 64;
  3663. }
  3664. if (sip_debug_test_pvt(p)) {
  3665. ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
  3666. }
  3667. if (sip_cancel_destroy(p)) {
  3668. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  3669. }
  3670. if (p->do_history) {
  3671. append_history(p, "SchedDestroy", "%d ms", ms);
  3672. }
  3673. p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
  3674. if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
  3675. stop_session_timer(p);
  3676. }
  3677. }
  3678. /*! \brief Cancel destruction of SIP dialog.
  3679. * Be careful as this also absorbs the reference - if you call it
  3680. * from within the scheduler, this might be the last reference.
  3681. */
  3682. int sip_cancel_destroy(struct sip_pvt *p)
  3683. {
  3684. if (p->final_destruction_scheduled) {
  3685. return 0;
  3686. }
  3687. if (p->autokillid > -1) {
  3688. append_history(p, "CancelDestroy", "");
  3689. AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
  3690. }
  3691. return 0;
  3692. }
  3693. /*! \brief Acknowledges receipt of a packet and stops retransmission
  3694. * called with p locked*/
  3695. int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
  3696. {
  3697. struct sip_pkt *cur, *prev = NULL;
  3698. const char *msg = "Not Found"; /* used only for debugging */
  3699. int res = FALSE;
  3700. /* If we have an outbound proxy for this dialog, then delete it now since
  3701. the rest of the requests in this dialog needs to follow the routing.
  3702. If obforcing is set, we will keep the outbound proxy during the whole
  3703. dialog, regardless of what the SIP rfc says
  3704. */
  3705. if (p->outboundproxy && !p->outboundproxy->force) {
  3706. ref_proxy(p, NULL);
  3707. }
  3708. for (cur = p->packets; cur; prev = cur, cur = cur->next) {
  3709. if (cur->seqno != seqno || cur->is_resp != resp) {
  3710. continue;
  3711. }
  3712. if (cur->is_resp || cur->method == sipmethod) {
  3713. res = TRUE;
  3714. msg = "Found";
  3715. if (!resp && (seqno == p->pendinginvite)) {
  3716. ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
  3717. p->pendinginvite = 0;
  3718. }
  3719. if (cur->retransid > -1) {
  3720. if (sipdebug)
  3721. ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
  3722. }
  3723. /* This odd section is designed to thwart a
  3724. * race condition in the packet scheduler. There are
  3725. * two conditions under which deleting the packet from the
  3726. * scheduler can fail.
  3727. *
  3728. * 1. The packet has been removed from the scheduler because retransmission
  3729. * is being attempted. The problem is that if the packet is currently attempting
  3730. * retransmission and we are at this point in the code, then that MUST mean
  3731. * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
  3732. * lock temporarily to allow retransmission.
  3733. *
  3734. * 2. The packet has reached its maximum number of retransmissions and has
  3735. * been permanently removed from the packet scheduler. If this is the case, then
  3736. * the packet's retransid will be set to -1. The atomicity of the setting and checking
  3737. * of the retransid to -1 is ensured since in both cases p's lock is held.
  3738. */
  3739. while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
  3740. sip_pvt_unlock(p);
  3741. usleep(1);
  3742. sip_pvt_lock(p);
  3743. }
  3744. UNLINK(cur, p->packets, prev);
  3745. dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
  3746. if (cur->data) {
  3747. ast_free(cur->data);
  3748. }
  3749. ast_free(cur);
  3750. break;
  3751. }
  3752. }
  3753. ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
  3754. p->callid, resp ? "Response" : "Request", seqno, msg);
  3755. return res;
  3756. }
  3757. /*! \brief Pretend to ack all packets
  3758. * called with p locked */
  3759. void __sip_pretend_ack(struct sip_pvt *p)
  3760. {
  3761. struct sip_pkt *cur = NULL;
  3762. while (p->packets) {
  3763. int method;
  3764. if (cur == p->packets) {
  3765. ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
  3766. return;
  3767. }
  3768. cur = p->packets;
  3769. method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
  3770. __sip_ack(p, cur->seqno, cur->is_resp, method);
  3771. }
  3772. }
  3773. /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
  3774. int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
  3775. {
  3776. struct sip_pkt *cur;
  3777. int res = FALSE;
  3778. for (cur = p->packets; cur; cur = cur->next) {
  3779. if (cur->seqno == seqno && cur->is_resp == resp &&
  3780. (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
  3781. /* this is our baby */
  3782. if (cur->retransid > -1) {
  3783. if (sipdebug)
  3784. ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
  3785. }
  3786. AST_SCHED_DEL(sched, cur->retransid);
  3787. res = TRUE;
  3788. break;
  3789. }
  3790. }
  3791. 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");
  3792. return res;
  3793. }
  3794. /*! \brief Copy SIP request, parse it */
  3795. static void parse_copy(struct sip_request *dst, const struct sip_request *src)
  3796. {
  3797. copy_request(dst, src);
  3798. parse_request(dst);
  3799. }
  3800. /*! \brief add a blank line if no body */
  3801. static void add_blank(struct sip_request *req)
  3802. {
  3803. if (!req->lines) {
  3804. /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
  3805. ast_str_append(&req->data, 0, "\r\n");
  3806. }
  3807. }
  3808. static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
  3809. {
  3810. const char *msg = NULL;
  3811. struct ast_channel *chan;
  3812. int res = 0;
  3813. int old_sched_id = pvt->provisional_keepalive_sched_id;
  3814. chan = sip_pvt_lock_full(pvt);
  3815. /* Check that nothing has changed while we were waiting for the lock */
  3816. if (old_sched_id != pvt->provisional_keepalive_sched_id) {
  3817. /* Keepalive has been cancelled or rescheduled, clean up and leave */
  3818. if (chan) {
  3819. ast_channel_unlock(chan);
  3820. chan = ast_channel_unref(chan);
  3821. }
  3822. sip_pvt_unlock(pvt);
  3823. dialog_unref(pvt, "dialog ref for provisional keepalive");
  3824. return 0;
  3825. }
  3826. if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
  3827. msg = "183 Session Progress";
  3828. }
  3829. if (pvt->invitestate < INV_COMPLETED) {
  3830. if (with_sdp) {
  3831. transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
  3832. } else {
  3833. transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
  3834. }
  3835. res = PROVIS_KEEPALIVE_TIMEOUT;
  3836. }
  3837. if (chan) {
  3838. ast_channel_unlock(chan);
  3839. chan = ast_channel_unref(chan);
  3840. }
  3841. if (!res) {
  3842. pvt->provisional_keepalive_sched_id = -1;
  3843. }
  3844. sip_pvt_unlock(pvt);
  3845. if (!res) {
  3846. dialog_unref(pvt, "dialog ref for provisional keepalive");
  3847. }
  3848. return res;
  3849. }
  3850. static int send_provisional_keepalive(const void *data) {
  3851. struct sip_pvt *pvt = (struct sip_pvt *) data;
  3852. return send_provisional_keepalive_full(pvt, 0);
  3853. }
  3854. static int send_provisional_keepalive_with_sdp(const void *data) {
  3855. struct sip_pvt *pvt = (void *)data;
  3856. return send_provisional_keepalive_full(pvt, 1);
  3857. }
  3858. static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
  3859. {
  3860. 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"));
  3861. pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
  3862. with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
  3863. }
  3864. static void add_required_respheader(struct sip_request *req)
  3865. {
  3866. struct ast_str *str;
  3867. int i;
  3868. if (!req->reqsipoptions) {
  3869. return;
  3870. }
  3871. str = ast_str_create(32);
  3872. for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
  3873. if (!(req->reqsipoptions & sip_options[i].id)) {
  3874. continue;
  3875. }
  3876. if (ast_str_strlen(str) > 0) {
  3877. ast_str_append(&str, 0, ", ");
  3878. }
  3879. ast_str_append(&str, 0, "%s", sip_options[i].text);
  3880. }
  3881. if (ast_str_strlen(str) > 0) {
  3882. add_header(req, "Require", ast_str_buffer(str));
  3883. }
  3884. ast_free(str);
  3885. }
  3886. /*! \brief Transmit response on SIP request*/
  3887. static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
  3888. {
  3889. int res;
  3890. finalize_content(req);
  3891. add_blank(req);
  3892. if (sip_debug_test_pvt(p)) {
  3893. const struct ast_sockaddr *dst = sip_real_dst(p);
  3894. ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
  3895. reliable ? "Reliably " : "", sip_nat_mode(p),
  3896. ast_sockaddr_stringify(dst),
  3897. ast_str_buffer(req->data));
  3898. }
  3899. if (p->do_history) {
  3900. struct sip_request tmp = { .rlPart1 = 0, };
  3901. parse_copy(&tmp, req);
  3902. append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), get_header(&tmp, "CSeq"),
  3903. (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
  3904. deinit_req(&tmp);
  3905. }
  3906. /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
  3907. if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
  3908. 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"));
  3909. }
  3910. res = (reliable) ?
  3911. __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
  3912. __sip_xmit(p, req->data);
  3913. deinit_req(req);
  3914. if (res > 0) {
  3915. return 0;
  3916. }
  3917. return res;
  3918. }
  3919. /*!
  3920. * \internal
  3921. * \brief Send SIP Request to the other part of the dialogue
  3922. * \return see \ref __sip_xmit
  3923. */
  3924. static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
  3925. {
  3926. int res;
  3927. /* If we have an outbound proxy, reset peer address
  3928. Only do this once.
  3929. */
  3930. if (p->outboundproxy) {
  3931. p->sa = p->outboundproxy->ip;
  3932. }
  3933. finalize_content(req);
  3934. add_blank(req);
  3935. if (sip_debug_test_pvt(p)) {
  3936. if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
  3937. ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
  3938. } else {
  3939. ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
  3940. }
  3941. }
  3942. if (p->do_history) {
  3943. struct sip_request tmp = { .rlPart1 = 0, };
  3944. parse_copy(&tmp, req);
  3945. append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
  3946. deinit_req(&tmp);
  3947. }
  3948. res = (reliable) ?
  3949. __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
  3950. __sip_xmit(p, req->data);
  3951. deinit_req(req);
  3952. return res;
  3953. }
  3954. static void enable_dsp_detect(struct sip_pvt *p)
  3955. {
  3956. int features = 0;
  3957. if (p->dsp) {
  3958. return;
  3959. }
  3960. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  3961. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  3962. if (p->rtp) {
  3963. ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
  3964. }
  3965. features |= DSP_FEATURE_DIGIT_DETECT;
  3966. }
  3967. if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
  3968. features |= DSP_FEATURE_FAX_DETECT;
  3969. }
  3970. if (!features) {
  3971. return;
  3972. }
  3973. if (!(p->dsp = ast_dsp_new())) {
  3974. return;
  3975. }
  3976. ast_dsp_set_features(p->dsp, features);
  3977. if (global_relaxdtmf) {
  3978. ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
  3979. }
  3980. }
  3981. static void disable_dsp_detect(struct sip_pvt *p)
  3982. {
  3983. if (p->dsp) {
  3984. ast_dsp_free(p->dsp);
  3985. p->dsp = NULL;
  3986. }
  3987. }
  3988. /*! \brief Set an option on a SIP dialog */
  3989. static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
  3990. {
  3991. int res = -1;
  3992. struct sip_pvt *p = chan->tech_pvt;
  3993. if (!p) {
  3994. ast_log(LOG_ERROR, "Attempt to Ref a null pointer. sip private structure is gone!\n");
  3995. return -1;
  3996. }
  3997. sip_pvt_lock(p);
  3998. switch (option) {
  3999. case AST_OPTION_FORMAT_READ:
  4000. if (p->rtp) {
  4001. res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
  4002. }
  4003. break;
  4004. case AST_OPTION_FORMAT_WRITE:
  4005. if (p->rtp) {
  4006. res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
  4007. }
  4008. break;
  4009. case AST_OPTION_MAKE_COMPATIBLE:
  4010. if (p->rtp) {
  4011. res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
  4012. }
  4013. break;
  4014. case AST_OPTION_DIGIT_DETECT:
  4015. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  4016. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  4017. char *cp = (char *) data;
  4018. ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
  4019. if (*cp) {
  4020. enable_dsp_detect(p);
  4021. } else {
  4022. disable_dsp_detect(p);
  4023. }
  4024. res = 0;
  4025. }
  4026. break;
  4027. case AST_OPTION_SECURE_SIGNALING:
  4028. p->req_secure_signaling = *(unsigned int *) data;
  4029. res = 0;
  4030. break;
  4031. case AST_OPTION_SECURE_MEDIA:
  4032. ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
  4033. res = 0;
  4034. break;
  4035. default:
  4036. break;
  4037. }
  4038. sip_pvt_unlock(p);
  4039. return res;
  4040. }
  4041. /*! \brief Query an option on a SIP dialog */
  4042. static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
  4043. {
  4044. int res = -1;
  4045. enum ast_t38_state state = T38_STATE_UNAVAILABLE;
  4046. struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
  4047. char *cp;
  4048. sip_pvt_lock(p);
  4049. switch (option) {
  4050. case AST_OPTION_T38_STATE:
  4051. /* Make sure we got an ast_t38_state enum passed in */
  4052. if (*datalen != sizeof(enum ast_t38_state)) {
  4053. ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
  4054. break;
  4055. }
  4056. /* 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 */
  4057. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
  4058. switch (p->t38.state) {
  4059. case T38_LOCAL_REINVITE:
  4060. case T38_PEER_REINVITE:
  4061. state = T38_STATE_NEGOTIATING;
  4062. break;
  4063. case T38_ENABLED:
  4064. state = T38_STATE_NEGOTIATED;
  4065. break;
  4066. default:
  4067. state = T38_STATE_UNKNOWN;
  4068. }
  4069. }
  4070. *((enum ast_t38_state *) data) = state;
  4071. res = 0;
  4072. break;
  4073. case AST_OPTION_DIGIT_DETECT:
  4074. cp = (char *) data;
  4075. *cp = p->dsp ? 1 : 0;
  4076. ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
  4077. break;
  4078. case AST_OPTION_SECURE_SIGNALING:
  4079. *((unsigned int *) data) = p->req_secure_signaling;
  4080. res = 0;
  4081. break;
  4082. case AST_OPTION_SECURE_MEDIA:
  4083. *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
  4084. res = 0;
  4085. break;
  4086. case AST_OPTION_DEVICE_NAME:
  4087. if (p && p->outgoing_call) {
  4088. cp = (char *) data;
  4089. ast_copy_string(cp, p->dialstring, *datalen);
  4090. res = 0;
  4091. }
  4092. /* We purposely break with a return of -1 in the
  4093. * implied else case here
  4094. */
  4095. break;
  4096. default:
  4097. break;
  4098. }
  4099. sip_pvt_unlock(p);
  4100. return res;
  4101. }
  4102. /*! \brief Locate closing quote in a string, skipping escaped quotes.
  4103. * optionally with a limit on the search.
  4104. * start must be past the first quote.
  4105. */
  4106. const char *find_closing_quote(const char *start, const char *lim)
  4107. {
  4108. char last_char = '\0';
  4109. const char *s;
  4110. for (s = start; *s && s != lim; last_char = *s++) {
  4111. if (*s == '"' && last_char != '\\')
  4112. break;
  4113. }
  4114. return s;
  4115. }
  4116. /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
  4117. static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
  4118. {
  4119. struct sip_pvt *p = chan->tech_pvt;
  4120. if (subclass != AST_HTML_URL)
  4121. return -1;
  4122. ast_string_field_build(p, url, "<%s>;mode=active", data);
  4123. if (sip_debug_test_pvt(p))
  4124. ast_debug(1, "Send URL %s, state = %u!\n", data, chan->_state);
  4125. switch (chan->_state) {
  4126. case AST_STATE_RING:
  4127. transmit_response(p, "100 Trying", &p->initreq);
  4128. break;
  4129. case AST_STATE_RINGING:
  4130. transmit_response(p, "180 Ringing", &p->initreq);
  4131. break;
  4132. case AST_STATE_UP:
  4133. if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
  4134. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  4135. } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  4136. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  4137. }
  4138. break;
  4139. default:
  4140. ast_log(LOG_WARNING, "Don't know how to send URI when state is %u!\n", chan->_state);
  4141. }
  4142. return 0;
  4143. }
  4144. /*! \brief Deliver SIP call ID for the call */
  4145. static const char *sip_get_callid(struct ast_channel *chan)
  4146. {
  4147. return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
  4148. }
  4149. /*!
  4150. * \internal
  4151. * \brief Send SIP MESSAGE text within a call
  4152. * \note Called from PBX core sendtext() application
  4153. */
  4154. static int sip_sendtext(struct ast_channel *ast, const char *text)
  4155. {
  4156. struct sip_pvt *dialog = ast->tech_pvt;
  4157. int debug;
  4158. if (!dialog) {
  4159. return -1;
  4160. }
  4161. /* NOT ast_strlen_zero, because a zero-length message is specifically
  4162. * allowed by RFC 3428 (See section 10, Examples) */
  4163. if (!text) {
  4164. return 0;
  4165. }
  4166. if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
  4167. ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
  4168. return(0);
  4169. }
  4170. debug = sip_debug_test_pvt(dialog);
  4171. if (debug) {
  4172. ast_verbose("Sending text %s on %s\n", text, ast->name);
  4173. }
  4174. transmit_message_with_text(dialog, text);
  4175. return 0;
  4176. }
  4177. /*! \brief Update peer object in realtime storage
  4178. If the Asterisk system name is set in asterisk.conf, we will use
  4179. that name and store that in the "regserver" field in the sippeers
  4180. table to facilitate multi-server setups.
  4181. */
  4182. 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)
  4183. {
  4184. char port[10];
  4185. char ipaddr[INET6_ADDRSTRLEN];
  4186. char regseconds[20];
  4187. char *tablename = NULL;
  4188. char str_lastms[20];
  4189. const char *sysname = ast_config_AST_SYSTEM_NAME;
  4190. char *syslabel = NULL;
  4191. time_t nowtime = time(NULL) + expirey;
  4192. const char *fc = fullcontact ? "fullcontact" : NULL;
  4193. int realtimeregs = ast_check_realtime("sipregs");
  4194. tablename = realtimeregs ? "sipregs" : "sippeers";
  4195. snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
  4196. snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
  4197. ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
  4198. ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
  4199. if (ast_strlen_zero(sysname)) /* No system name, disable this */
  4200. sysname = NULL;
  4201. else if (sip_cfg.rtsave_sysname)
  4202. syslabel = "regserver";
  4203. /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
  4204. * must also add it to contrib/scripts/asterisk.ldap-schema,
  4205. * contrib/scripts/asterisk.ldif,
  4206. * and to configs/res_ldap.conf.sample as described in
  4207. * bugs 15156 and 15895
  4208. */
  4209. if (fc) {
  4210. ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
  4211. "port", port, "regseconds", regseconds,
  4212. deprecated_username ? "username" : "defaultuser", defaultuser,
  4213. "useragent", useragent, "lastms", str_lastms,
  4214. fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
  4215. } else {
  4216. ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
  4217. "port", port, "regseconds", regseconds,
  4218. "useragent", useragent, "lastms", str_lastms,
  4219. deprecated_username ? "username" : "defaultuser", defaultuser,
  4220. syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
  4221. }
  4222. }
  4223. /*! \brief Automatically add peer extension to dial plan */
  4224. static void register_peer_exten(struct sip_peer *peer, int onoff)
  4225. {
  4226. char multi[256];
  4227. char *stringp, *ext, *context;
  4228. struct pbx_find_info q = { .stacklen = 0 };
  4229. /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
  4230. * the name of the global regexten context, if not specified
  4231. * individually.
  4232. */
  4233. if (ast_strlen_zero(sip_cfg.regcontext))
  4234. return;
  4235. ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
  4236. stringp = multi;
  4237. while ((ext = strsep(&stringp, "&"))) {
  4238. if ((context = strchr(ext, '@'))) {
  4239. *context++ = '\0'; /* split ext@context */
  4240. if (!ast_context_find(context)) {
  4241. ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
  4242. continue;
  4243. }
  4244. } else {
  4245. context = sip_cfg.regcontext;
  4246. }
  4247. if (onoff) {
  4248. if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
  4249. ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
  4250. ast_strdup(peer->name), ast_free_ptr, "SIP");
  4251. }
  4252. } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
  4253. ast_context_remove_extension(context, ext, 1, NULL);
  4254. }
  4255. }
  4256. }
  4257. /*! Destroy mailbox subscriptions */
  4258. static void destroy_mailbox(struct sip_mailbox *mailbox)
  4259. {
  4260. if (mailbox->event_sub)
  4261. ast_event_unsubscribe(mailbox->event_sub);
  4262. ast_free(mailbox);
  4263. }
  4264. /*! Destroy all peer-related mailbox subscriptions */
  4265. static void clear_peer_mailboxes(struct sip_peer *peer)
  4266. {
  4267. struct sip_mailbox *mailbox;
  4268. while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
  4269. destroy_mailbox(mailbox);
  4270. }
  4271. static void sip_destroy_peer_fn(void *peer)
  4272. {
  4273. sip_destroy_peer(peer);
  4274. }
  4275. /*! \brief Destroy peer object from memory */
  4276. static void sip_destroy_peer(struct sip_peer *peer)
  4277. {
  4278. ast_debug(3, "Destroying SIP peer %s\n", peer->name);
  4279. /*
  4280. * Remove any mailbox event subscriptions for this peer before
  4281. * we destroy anything. An event subscription callback may be
  4282. * happening right now.
  4283. */
  4284. clear_peer_mailboxes(peer);
  4285. if (peer->outboundproxy) {
  4286. ao2_ref(peer->outboundproxy, -1);
  4287. peer->outboundproxy = NULL;
  4288. }
  4289. /* Delete it, it needs to disappear */
  4290. if (peer->call) {
  4291. dialog_unlink_all(peer->call);
  4292. peer->call = dialog_unref(peer->call, "peer->call is being unset");
  4293. }
  4294. if (peer->mwipvt) { /* We have an active subscription, delete it */
  4295. dialog_unlink_all(peer->mwipvt);
  4296. peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
  4297. }
  4298. if (peer->chanvars) {
  4299. ast_variables_destroy(peer->chanvars);
  4300. peer->chanvars = NULL;
  4301. }
  4302. register_peer_exten(peer, FALSE);
  4303. ast_free_ha(peer->ha);
  4304. ast_free_ha(peer->directmediaha);
  4305. if (peer->selfdestruct)
  4306. ast_atomic_fetchadd_int(&apeerobjs, -1);
  4307. else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
  4308. ast_atomic_fetchadd_int(&rpeerobjs, -1);
  4309. ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
  4310. } else
  4311. ast_atomic_fetchadd_int(&speerobjs, -1);
  4312. if (peer->auth) {
  4313. ao2_t_ref(peer->auth, -1, "Removing peer authentication");
  4314. peer->auth = NULL;
  4315. }
  4316. if (peer->socket.tcptls_session) {
  4317. ao2_ref(peer->socket.tcptls_session, -1);
  4318. peer->socket.tcptls_session = NULL;
  4319. }
  4320. ast_cc_config_params_destroy(peer->cc_params);
  4321. ast_string_field_free_memory(peer);
  4322. }
  4323. /*! \brief Update peer data in database (if used) */
  4324. static void update_peer(struct sip_peer *p, int expire)
  4325. {
  4326. int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
  4327. if (sip_cfg.peer_rtupdate &&
  4328. (p->is_realtime || rtcachefriends)) {
  4329. realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
  4330. }
  4331. }
  4332. static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
  4333. {
  4334. struct ast_variable *var = NULL;
  4335. struct ast_flags flags = {0};
  4336. char *cat = NULL;
  4337. const char *insecure;
  4338. while ((cat = ast_category_browse(cfg, cat))) {
  4339. insecure = ast_variable_retrieve(cfg, cat, "insecure");
  4340. set_insecure_flags(&flags, insecure, -1);
  4341. if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
  4342. var = ast_category_root(cfg, cat);
  4343. break;
  4344. }
  4345. }
  4346. return var;
  4347. }
  4348. static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
  4349. {
  4350. struct ast_config *peerlist;
  4351. struct ast_variable *var = NULL;
  4352. if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
  4353. if ((var = get_insecure_variable_from_config(peerlist))) {
  4354. /* Must clone, because var will get freed along with
  4355. * peerlist. */
  4356. var = ast_variables_dup(var);
  4357. }
  4358. ast_config_destroy(peerlist);
  4359. }
  4360. return var;
  4361. }
  4362. /* Yes.. the only column that makes sense to pass is "ipaddr", but for
  4363. * consistency's sake, we require the column name to be passed. As extra
  4364. * argument, we take a pointer to var. We already got the info, so we better
  4365. * return it and save the caller a query. If return value is nonzero, then *var
  4366. * is nonzero too (and the other way around). */
  4367. static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
  4368. {
  4369. struct ast_variable *varregs = NULL;
  4370. struct ast_config *regs, *peers;
  4371. char *regscat;
  4372. const char *regname;
  4373. if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
  4374. return NULL;
  4375. }
  4376. /* Load *all* peers that are probably insecure=port */
  4377. if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
  4378. ast_config_destroy(regs);
  4379. return NULL;
  4380. }
  4381. /* Loop over the sipregs that match IP address and attempt to find an
  4382. * insecure=port match to it in sippeers. */
  4383. regscat = NULL;
  4384. while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
  4385. char *peerscat;
  4386. const char *peername;
  4387. peerscat = NULL;
  4388. while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
  4389. if (!strcasecmp(regname, peername)) {
  4390. /* Ensure that it really is insecure=port and
  4391. * not something else. */
  4392. const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
  4393. struct ast_flags flags = {0};
  4394. set_insecure_flags(&flags, insecure, -1);
  4395. if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
  4396. /* ENOMEM checks till the bitter end. */
  4397. if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
  4398. if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
  4399. ast_variables_destroy(varregs);
  4400. varregs = NULL;
  4401. }
  4402. }
  4403. goto done;
  4404. }
  4405. }
  4406. }
  4407. }
  4408. done:
  4409. ast_config_destroy(regs);
  4410. ast_config_destroy(peers);
  4411. return varregs;
  4412. }
  4413. static const char *get_name_from_variable(const struct ast_variable *var)
  4414. {
  4415. /* Don't expect this to return non-NULL. Both NULL and empty
  4416. * values can cause the option to get removed from the variable
  4417. * list. This is called on ast_variables gotten from both
  4418. * ast_load_realtime and ast_load_realtime_multientry.
  4419. * - ast_load_realtime removes options with empty values
  4420. * - ast_load_realtime_multientry does not!
  4421. * For consistent behaviour, we check for the empty name and
  4422. * return NULL instead. */
  4423. const struct ast_variable *tmp;
  4424. for (tmp = var; tmp; tmp = tmp->next) {
  4425. if (!strcasecmp(tmp->name, "name")) {
  4426. if (!ast_strlen_zero(tmp->value)) {
  4427. return tmp->value;
  4428. }
  4429. break;
  4430. }
  4431. }
  4432. return NULL;
  4433. }
  4434. /* If varregs is NULL, we don't use sipregs.
  4435. * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
  4436. 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)
  4437. {
  4438. /* Peer by name and host=dynamic */
  4439. if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
  4440. ;
  4441. /* Peer by name and host=IP */
  4442. } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
  4443. ;
  4444. /* Peer by name and host=HOSTNAME */
  4445. } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
  4446. /*!\note
  4447. * If this one loaded something, then we need to ensure that the host
  4448. * field matched. The only reason why we can't have this as a criteria
  4449. * is because we only have the IP address and the host field might be
  4450. * set as a name (and the reverse PTR might not match).
  4451. */
  4452. if (addr) {
  4453. struct ast_variable *tmp;
  4454. for (tmp = *var; tmp; tmp = tmp->next) {
  4455. if (!strcasecmp(tmp->name, "host")) {
  4456. struct ast_sockaddr *addrs = NULL;
  4457. if (ast_sockaddr_resolve(&addrs,
  4458. tmp->value,
  4459. PARSE_PORT_FORBID,
  4460. get_address_family_filter(SIP_TRANSPORT_UDP)) <= 0 ||
  4461. ast_sockaddr_cmp(&addrs[0], addr)) {
  4462. /* No match */
  4463. ast_variables_destroy(*var);
  4464. *var = NULL;
  4465. }
  4466. ast_free(addrs);
  4467. break;
  4468. }
  4469. }
  4470. }
  4471. }
  4472. /* Did we find anything? */
  4473. if (*var) {
  4474. if (varregs) {
  4475. *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
  4476. }
  4477. return 1;
  4478. }
  4479. return 0;
  4480. }
  4481. /* Another little helper function for backwards compatibility: this
  4482. * checks/fetches the sippeer that belongs to the sipreg. If none is
  4483. * found, we free the sipreg and return false. This way we can do the
  4484. * check inside the if-condition below. In the old code, not finding
  4485. * the sippeer also had it continue look for another match, so we do
  4486. * the same. */
  4487. static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
  4488. struct ast_variable *var = NULL;
  4489. const char *old_name = *name;
  4490. *name = get_name_from_variable(*varregs);
  4491. if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
  4492. if (!*name) {
  4493. ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
  4494. }
  4495. ast_variables_destroy(*varregs);
  4496. *varregs = NULL;
  4497. *name = old_name;
  4498. }
  4499. return var;
  4500. }
  4501. /* If varregs is NULL, we don't use sipregs. If we return true, then *name is
  4502. * set. Using empty if-bodies instead of goto's while avoiding unnecessary
  4503. * indents. */
  4504. static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
  4505. {
  4506. char portstring[6]; /* up to 5 digits plus null terminator */
  4507. ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
  4508. /* We're not finding this peer by this name anymore. Reset it. */
  4509. *name = NULL;
  4510. /* First check for fixed IP hosts */
  4511. if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
  4512. ;
  4513. /* Check for registered hosts (in sipregs) */
  4514. } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
  4515. (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
  4516. ;
  4517. /* Check for registered hosts (in sippeers) */
  4518. } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
  4519. ;
  4520. /* We couldn't match on ipaddress and port, so we need to check if port is insecure */
  4521. } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
  4522. ;
  4523. /* Same as above, but try the IP address field (in sipregs)
  4524. * Observe that it fetches the name/var at the same time, without the
  4525. * realtime_peer_get_sippeer_helper. Also note that it is quite inefficient.
  4526. * Avoid sipregs if possible. */
  4527. } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
  4528. ;
  4529. /* Same as above, but try the IP address field (in sippeers) */
  4530. } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
  4531. ;
  4532. }
  4533. /* Nothing found? */
  4534. if (!*var) {
  4535. return 0;
  4536. }
  4537. /* Check peer name. It must not be empty. There may exist a
  4538. * different match that does have a name, but it's too late for
  4539. * that now. */
  4540. if (!*name && !(*name = get_name_from_variable(*var))) {
  4541. ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
  4542. ast_variables_destroy(*var);
  4543. *var = NULL;
  4544. if (varregs && *varregs) {
  4545. ast_variables_destroy(*varregs);
  4546. *varregs = NULL;
  4547. }
  4548. return 0;
  4549. }
  4550. /* Make sure varregs is populated if var is. The inverse,
  4551. * ensuring that var is set when varregs is, is taken
  4552. * care of by realtime_peer_get_sippeer_helper(). */
  4553. if (varregs && !*varregs) {
  4554. *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
  4555. }
  4556. return 1;
  4557. }
  4558. /*! \brief realtime_peer: Get peer from realtime storage
  4559. * Checks the "sippeers" realtime family from extconfig.conf
  4560. * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
  4561. * This returns a pointer to a peer and because we use build_peer, we can rest
  4562. * assured that the refcount is bumped.
  4563. *
  4564. * \note This is never called with both newpeername and addr at the same time.
  4565. * If you do, be prepared to get a peer with a different name than newpeername.
  4566. */
  4567. static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only, int which_objects)
  4568. {
  4569. struct sip_peer *peer = NULL;
  4570. struct ast_variable *var = NULL;
  4571. struct ast_variable *varregs = NULL;
  4572. char ipaddr[INET6_ADDRSTRLEN];
  4573. int realtimeregs = ast_check_realtime("sipregs");
  4574. if (addr) {
  4575. ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
  4576. } else {
  4577. ipaddr[0] = '\0';
  4578. }
  4579. if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
  4580. ;
  4581. } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
  4582. ;
  4583. } else {
  4584. return NULL;
  4585. }
  4586. /* If we're looking for users, don't return peers (although this check
  4587. * should probably be done in realtime_peer_by_* instead...) */
  4588. if (which_objects == FINDUSERS) {
  4589. struct ast_variable *tmp;
  4590. for (tmp = var; tmp; tmp = tmp->next) {
  4591. if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
  4592. goto cleanup;
  4593. }
  4594. }
  4595. }
  4596. /* Peer found in realtime, now build it in memory */
  4597. peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
  4598. if (!peer) {
  4599. goto cleanup;
  4600. }
  4601. /* Previous versions of Asterisk did not require the type field to be
  4602. * set for real time peers. This statement preserves that behavior. */
  4603. if (peer->type == 0) {
  4604. if (which_objects == FINDUSERS) {
  4605. peer->type = SIP_TYPE_USER;
  4606. } else if (which_objects == FINDPEERS) {
  4607. peer->type = SIP_TYPE_PEER;
  4608. } else {
  4609. peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
  4610. }
  4611. }
  4612. ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
  4613. if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
  4614. /* Cache peer */
  4615. ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
  4616. if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
  4617. AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
  4618. unref_peer(_data, "remove registration ref"),
  4619. unref_peer(peer, "remove registration ref"),
  4620. ref_peer(peer, "add registration ref"));
  4621. }
  4622. ao2_t_link(peers, peer, "link peer into peers table");
  4623. if (!ast_sockaddr_isnull(&peer->addr)) {
  4624. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  4625. }
  4626. }
  4627. peer->is_realtime = 1;
  4628. cleanup:
  4629. ast_variables_destroy(var);
  4630. ast_variables_destroy(varregs);
  4631. return peer;
  4632. }
  4633. /* Function to assist finding peers by name only */
  4634. static int find_by_name(void *obj, void *arg, void *data, int flags)
  4635. {
  4636. struct sip_peer *search = obj, *match = arg;
  4637. int *which_objects = data;
  4638. /* Usernames in SIP uri's are case sensitive. Domains are not */
  4639. if (strcmp(search->name, match->name)) {
  4640. return 0;
  4641. }
  4642. switch (*which_objects) {
  4643. case FINDUSERS:
  4644. if (!(search->type & SIP_TYPE_USER)) {
  4645. return 0;
  4646. }
  4647. break;
  4648. case FINDPEERS:
  4649. if (!(search->type & SIP_TYPE_PEER)) {
  4650. return 0;
  4651. }
  4652. break;
  4653. case FINDALLDEVICES:
  4654. break;
  4655. }
  4656. return CMP_MATCH | CMP_STOP;
  4657. }
  4658. /*!
  4659. * \brief Locate device by name or ip address
  4660. * \param peer, sin, realtime, devstate_only, transport
  4661. * \param which_objects Define which objects should be matched when doing a lookup
  4662. * by name. Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
  4663. * Note that this option is not used at all when doing a lookup by IP.
  4664. *
  4665. * This is used on find matching device on name or ip/port.
  4666. * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
  4667. *
  4668. * \note Avoid using this function in new functions if there is a way to avoid it,
  4669. * since it might cause a database lookup.
  4670. */
  4671. static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
  4672. {
  4673. struct sip_peer *p = NULL;
  4674. struct sip_peer tmp_peer;
  4675. if (peer) {
  4676. ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
  4677. p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
  4678. } else if (addr) { /* search by addr? */
  4679. ast_sockaddr_copy(&tmp_peer.addr, addr);
  4680. tmp_peer.flags[0].flags = 0;
  4681. tmp_peer.transports = transport;
  4682. p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table"); /* WAS: p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
  4683. if (!p) {
  4684. ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
  4685. p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2"); /* WAS: p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
  4686. if (p) {
  4687. return p;
  4688. }
  4689. }
  4690. }
  4691. if (!p && (realtime || devstate_only)) {
  4692. p = realtime_peer(peer, addr, devstate_only, which_objects);
  4693. if (p) {
  4694. switch (which_objects) {
  4695. case FINDUSERS:
  4696. if (!(p->type & SIP_TYPE_USER)) {
  4697. unref_peer(p, "Wrong type of realtime SIP endpoint");
  4698. return NULL;
  4699. }
  4700. break;
  4701. case FINDPEERS:
  4702. if (!(p->type & SIP_TYPE_PEER)) {
  4703. unref_peer(p, "Wrong type of realtime SIP endpoint");
  4704. return NULL;
  4705. }
  4706. break;
  4707. case FINDALLDEVICES:
  4708. break;
  4709. }
  4710. }
  4711. }
  4712. return p;
  4713. }
  4714. /*! \brief Set nat mode on the various data sockets */
  4715. static void do_setnat(struct sip_pvt *p)
  4716. {
  4717. const char *mode;
  4718. int natflags;
  4719. natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
  4720. mode = natflags ? "On" : "Off";
  4721. if (p->rtp) {
  4722. ast_debug(1, "Setting NAT on RTP to %s\n", mode);
  4723. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
  4724. }
  4725. if (p->vrtp) {
  4726. ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
  4727. ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
  4728. }
  4729. if (p->udptl) {
  4730. ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
  4731. ast_udptl_setnat(p->udptl, natflags);
  4732. }
  4733. if (p->trtp) {
  4734. ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
  4735. ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
  4736. }
  4737. }
  4738. /*! \brief Change the T38 state on a SIP dialog */
  4739. static void change_t38_state(struct sip_pvt *p, int state)
  4740. {
  4741. int old = p->t38.state;
  4742. struct ast_channel *chan = p->owner;
  4743. struct ast_control_t38_parameters parameters = { .request_response = 0 };
  4744. /* Don't bother changing if we are already in the state wanted */
  4745. if (old == state)
  4746. return;
  4747. p->t38.state = state;
  4748. ast_debug(2, "T38 state changed to %u on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
  4749. /* If no channel was provided we can't send off a control frame */
  4750. if (!chan)
  4751. return;
  4752. /* Given the state requested and old state determine what control frame we want to queue up */
  4753. switch (state) {
  4754. case T38_PEER_REINVITE:
  4755. parameters = p->t38.their_parms;
  4756. parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
  4757. parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
  4758. ast_udptl_set_tag(p->udptl, "%s", chan->name);
  4759. break;
  4760. case T38_ENABLED:
  4761. parameters = p->t38.their_parms;
  4762. parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
  4763. parameters.request_response = AST_T38_NEGOTIATED;
  4764. ast_udptl_set_tag(p->udptl, "%s", chan->name);
  4765. break;
  4766. case T38_DISABLED:
  4767. if (old == T38_ENABLED) {
  4768. parameters.request_response = AST_T38_TERMINATED;
  4769. } else if (old == T38_LOCAL_REINVITE) {
  4770. parameters.request_response = AST_T38_REFUSED;
  4771. }
  4772. break;
  4773. case T38_LOCAL_REINVITE:
  4774. /* wait until we get a peer response before responding to local reinvite */
  4775. break;
  4776. }
  4777. /* Woot we got a message, create a control frame and send it on! */
  4778. if (parameters.request_response)
  4779. ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
  4780. }
  4781. /*! \brief Set the global T38 capabilities on a SIP dialog structure */
  4782. static void set_t38_capabilities(struct sip_pvt *p)
  4783. {
  4784. if (p->udptl) {
  4785. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
  4786. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
  4787. } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
  4788. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
  4789. } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
  4790. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
  4791. }
  4792. }
  4793. }
  4794. static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
  4795. {
  4796. if (to_sock->tcptls_session) {
  4797. ao2_ref(to_sock->tcptls_session, -1);
  4798. to_sock->tcptls_session = NULL;
  4799. }
  4800. if (from_sock->tcptls_session) {
  4801. ao2_ref(from_sock->tcptls_session, +1);
  4802. }
  4803. *to_sock = *from_sock;
  4804. }
  4805. /*! \brief Initialize RTP portion of a dialog
  4806. * \return -1 on failure, 0 on success
  4807. */
  4808. static int dialog_initialize_rtp(struct sip_pvt *dialog)
  4809. {
  4810. struct ast_sockaddr bindaddr_tmp;
  4811. if (!sip_methods[dialog->method].need_rtp) {
  4812. return 0;
  4813. }
  4814. ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
  4815. if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
  4816. return -1;
  4817. }
  4818. if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
  4819. (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
  4820. if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
  4821. return -1;
  4822. }
  4823. ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
  4824. ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
  4825. ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
  4826. ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
  4827. ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
  4828. }
  4829. if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
  4830. if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
  4831. return -1;
  4832. }
  4833. /* Do not timeout text as its not constant*/
  4834. ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
  4835. ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
  4836. }
  4837. ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
  4838. ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
  4839. ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
  4840. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
  4841. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  4842. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  4843. ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
  4844. do_setnat(dialog);
  4845. return 0;
  4846. }
  4847. /*! \brief Create address structure from peer reference.
  4848. * This function copies data from peer to the dialog, so we don't have to look up the peer
  4849. * again from memory or database during the life time of the dialog.
  4850. *
  4851. * \return -1 on error, 0 on success.
  4852. *
  4853. */
  4854. static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
  4855. {
  4856. struct sip_auth_container *credentials;
  4857. /* this checks that the dialog is contacting the peer on a valid
  4858. * transport type based on the peers transport configuration,
  4859. * otherwise, this function bails out */
  4860. if (dialog->socket.type && check_request_transport(peer, dialog))
  4861. return -1;
  4862. copy_socket_data(&dialog->socket, &peer->socket);
  4863. if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
  4864. (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
  4865. dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
  4866. dialog->recv = dialog->sa;
  4867. } else
  4868. return -1;
  4869. /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
  4870. ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
  4871. ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  4872. ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  4873. dialog->capability = peer->capability;
  4874. dialog->prefs = peer->prefs;
  4875. dialog->amaflags = peer->amaflags;
  4876. ast_string_field_set(dialog, engine, peer->engine);
  4877. dialog->rtptimeout = peer->rtptimeout;
  4878. dialog->rtpholdtimeout = peer->rtpholdtimeout;
  4879. dialog->rtpkeepalive = peer->rtpkeepalive;
  4880. if (dialog_initialize_rtp(dialog)) {
  4881. return -1;
  4882. }
  4883. if (dialog->rtp) { /* Audio */
  4884. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  4885. ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  4886. /* Set Frame packetization */
  4887. ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
  4888. dialog->autoframing = peer->autoframing;
  4889. }
  4890. /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
  4891. ast_string_field_set(dialog, peername, peer->name);
  4892. ast_string_field_set(dialog, authname, peer->username);
  4893. ast_string_field_set(dialog, username, peer->username);
  4894. ast_string_field_set(dialog, peersecret, peer->secret);
  4895. ast_string_field_set(dialog, peermd5secret, peer->md5secret);
  4896. ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
  4897. ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
  4898. ast_string_field_set(dialog, tohost, peer->tohost);
  4899. ast_string_field_set(dialog, fullcontact, peer->fullcontact);
  4900. ast_string_field_set(dialog, accountcode, peer->accountcode);
  4901. ast_string_field_set(dialog, context, peer->context);
  4902. ast_string_field_set(dialog, cid_num, peer->cid_num);
  4903. ast_string_field_set(dialog, cid_name, peer->cid_name);
  4904. ast_string_field_set(dialog, cid_tag, peer->cid_tag);
  4905. ast_string_field_set(dialog, mwi_from, peer->mwi_from);
  4906. if (!ast_strlen_zero(peer->parkinglot)) {
  4907. ast_string_field_set(dialog, parkinglot, peer->parkinglot);
  4908. }
  4909. ast_string_field_set(dialog, engine, peer->engine);
  4910. ref_proxy(dialog, obproxy_get(dialog, peer));
  4911. dialog->callgroup = peer->callgroup;
  4912. dialog->pickupgroup = peer->pickupgroup;
  4913. dialog->allowtransfer = peer->allowtransfer;
  4914. dialog->jointnoncodeccapability = dialog->noncodeccapability;
  4915. /* Update dialog authorization credentials */
  4916. ao2_lock(peer);
  4917. credentials = peer->auth;
  4918. if (credentials) {
  4919. ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
  4920. }
  4921. ao2_unlock(peer);
  4922. ao2_lock(dialog);
  4923. if (dialog->peerauth) {
  4924. ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
  4925. }
  4926. dialog->peerauth = credentials;
  4927. ao2_unlock(dialog);
  4928. dialog->maxcallbitrate = peer->maxcallbitrate;
  4929. dialog->disallowed_methods = peer->disallowed_methods;
  4930. ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
  4931. if (ast_strlen_zero(dialog->tohost))
  4932. ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
  4933. if (!ast_strlen_zero(peer->fromdomain)) {
  4934. ast_string_field_set(dialog, fromdomain, peer->fromdomain);
  4935. if (!dialog->initreq.headers) {
  4936. char *new_callid;
  4937. char *tmpcall = ast_strdupa(dialog->callid);
  4938. /* this sure looks to me like we are going to change the callid on this dialog!! */
  4939. new_callid = strchr(tmpcall, '@');
  4940. if (new_callid) {
  4941. int callid_size;
  4942. *new_callid = '\0';
  4943. /* Change the dialog callid. */
  4944. callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
  4945. new_callid = ast_alloca(callid_size);
  4946. snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
  4947. change_callid_pvt(dialog, new_callid);
  4948. }
  4949. }
  4950. }
  4951. if (!ast_strlen_zero(peer->fromuser))
  4952. ast_string_field_set(dialog, fromuser, peer->fromuser);
  4953. if (!ast_strlen_zero(peer->language))
  4954. ast_string_field_set(dialog, language, peer->language);
  4955. /* Set timer T1 to RTT for this peer (if known by qualify=) */
  4956. /* Minimum is settable or default to 100 ms */
  4957. /* If there is a maxms and lastms from a qualify use that over a manual T1
  4958. value. Otherwise, use the peer's T1 value. */
  4959. if (peer->maxms && peer->lastms)
  4960. dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
  4961. else
  4962. dialog->timer_t1 = peer->timer_t1;
  4963. /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
  4964. the known timer */
  4965. if (peer->timer_b)
  4966. dialog->timer_b = peer->timer_b;
  4967. else
  4968. dialog->timer_b = 64 * dialog->timer_t1;
  4969. if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
  4970. (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
  4971. dialog->noncodeccapability |= AST_RTP_DTMF;
  4972. else
  4973. dialog->noncodeccapability &= ~AST_RTP_DTMF;
  4974. dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
  4975. if (peer->call_limit)
  4976. ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
  4977. if (!dialog->portinuri)
  4978. dialog->portinuri = peer->portinuri;
  4979. dialog->chanvars = copy_vars(peer->chanvars);
  4980. if (peer->fromdomainport)
  4981. dialog->fromdomainport = peer->fromdomainport;
  4982. dialog->callingpres = peer->callingpres;
  4983. return 0;
  4984. }
  4985. /*! \brief The default sip port for the given transport */
  4986. static inline int default_sip_port(enum sip_transport type)
  4987. {
  4988. return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
  4989. }
  4990. /*! \brief create address structure from device name
  4991. * Or, if peer not found, find it in the global DNS
  4992. * returns TRUE (-1) on failure, FALSE on success */
  4993. static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
  4994. {
  4995. struct sip_peer *peer;
  4996. char *peername, *peername2, *hostn;
  4997. char host[MAXHOSTNAMELEN];
  4998. char service[MAXHOSTNAMELEN];
  4999. int srv_ret = 0;
  5000. int tportno;
  5001. AST_DECLARE_APP_ARGS(hostport,
  5002. AST_APP_ARG(host);
  5003. AST_APP_ARG(port);
  5004. );
  5005. peername = ast_strdupa(opeer);
  5006. peername2 = ast_strdupa(opeer);
  5007. AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
  5008. if (hostport.port)
  5009. dialog->portinuri = 1;
  5010. dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
  5011. dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
  5012. peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
  5013. if (peer) {
  5014. int res;
  5015. if (newdialog) {
  5016. set_socket_transport(&dialog->socket, 0);
  5017. }
  5018. res = create_addr_from_peer(dialog, peer);
  5019. dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
  5020. unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
  5021. return res;
  5022. } else if (ast_check_digits(peername)) {
  5023. /* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
  5024. * it makes dialing SIP/${EXTEN} for a peer that isn't defined resolve to an IP that is
  5025. * almost certainly not intended. It is much better to just reject purely numeric hostnames */
  5026. ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
  5027. return -1;
  5028. } else {
  5029. dialog->rtptimeout = global_rtptimeout;
  5030. dialog->rtpholdtimeout = global_rtpholdtimeout;
  5031. dialog->rtpkeepalive = global_rtpkeepalive;
  5032. if (dialog_initialize_rtp(dialog)) {
  5033. return -1;
  5034. }
  5035. }
  5036. ast_string_field_set(dialog, tohost, hostport.host);
  5037. dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
  5038. /* Get the outbound proxy information */
  5039. ref_proxy(dialog, obproxy_get(dialog, NULL));
  5040. if (addr) {
  5041. /* This address should be updated using dnsmgr */
  5042. ast_sockaddr_copy(&dialog->sa, addr);
  5043. } else {
  5044. /* Let's see if we can find the host in DNS. First try DNS SRV records,
  5045. then hostname lookup */
  5046. /*! \todo Fix this function. When we ask for SRV, we should check all transports
  5047. In the future, we should first check NAPTR to find out transport preference
  5048. */
  5049. hostn = peername;
  5050. /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
  5051. * an A record lookup should be used instead of SRV.
  5052. */
  5053. if (!hostport.port && sip_cfg.srvlookup) {
  5054. snprintf(service, sizeof(service), "_%s._%s.%s",
  5055. get_srv_service(dialog->socket.type),
  5056. get_srv_protocol(dialog->socket.type), peername);
  5057. if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
  5058. service)) > 0) {
  5059. hostn = host;
  5060. }
  5061. }
  5062. if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : SIP_TRANSPORT_UDP)) {
  5063. ast_log(LOG_WARNING, "No such host: %s\n", peername);
  5064. return -1;
  5065. }
  5066. if (srv_ret > 0) {
  5067. ast_sockaddr_set_port(&dialog->sa, tportno);
  5068. }
  5069. }
  5070. if (!dialog->socket.type)
  5071. set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
  5072. if (!dialog->socket.port) {
  5073. dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
  5074. }
  5075. if (!ast_sockaddr_port(&dialog->sa)) {
  5076. ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
  5077. }
  5078. ast_sockaddr_copy(&dialog->recv, &dialog->sa);
  5079. return 0;
  5080. }
  5081. /*! \brief Scheduled congestion on a call.
  5082. * Only called by the scheduler, must return the reference when done.
  5083. */
  5084. static int auto_congest(const void *arg)
  5085. {
  5086. struct sip_pvt *p = (struct sip_pvt *)arg;
  5087. sip_pvt_lock(p);
  5088. p->initid = -1; /* event gone, will not be rescheduled */
  5089. if (p->owner) {
  5090. /* XXX fails on possible deadlock */
  5091. if (!ast_channel_trylock(p->owner)) {
  5092. append_history(p, "Cong", "Auto-congesting (timer)");
  5093. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  5094. ast_channel_unlock(p->owner);
  5095. }
  5096. /* Give the channel a chance to act before we proceed with destruction */
  5097. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  5098. }
  5099. sip_pvt_unlock(p);
  5100. dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
  5101. return 0;
  5102. }
  5103. /*! \brief Initiate SIP call from PBX
  5104. * used from the dial() application */
  5105. static int sip_call(struct ast_channel *ast, char *dest, int timeout)
  5106. {
  5107. int res;
  5108. struct sip_pvt *p = ast->tech_pvt; /* chan is locked, so the reference cannot go away */
  5109. struct varshead *headp;
  5110. struct ast_var_t *current;
  5111. const char *referer = NULL; /* SIP referrer */
  5112. int cc_core_id;
  5113. char uri[SIPBUFSIZE] = "";
  5114. if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
  5115. ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
  5116. return -1;
  5117. }
  5118. if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
  5119. char device_name[AST_CHANNEL_NAME];
  5120. struct ast_cc_monitor *recall_monitor;
  5121. struct sip_monitor_instance *monitor_instance;
  5122. ast_channel_get_device_name(ast, device_name, sizeof(device_name));
  5123. if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
  5124. monitor_instance = recall_monitor->private_data;
  5125. ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
  5126. ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
  5127. }
  5128. }
  5129. /* Check whether there is vxml_url, distinctive ring variables */
  5130. headp=&ast->varshead;
  5131. AST_LIST_TRAVERSE(headp, current, entries) {
  5132. /* Check whether there is a VXML_URL variable */
  5133. if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
  5134. p->options->vxml_url = ast_var_value(current);
  5135. } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
  5136. p->options->uri_options = ast_var_value(current);
  5137. } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
  5138. /* Check whether there is a variable with a name starting with SIPADDHEADER */
  5139. p->options->addsipheaders = 1;
  5140. } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
  5141. ast_string_field_set(p, fromdomain, ast_var_value(current));
  5142. } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
  5143. /* This is a transferred call */
  5144. p->options->transfer = 1;
  5145. } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
  5146. /* This is the referrer */
  5147. referer = ast_var_value(current);
  5148. } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
  5149. /* We're replacing a call. */
  5150. p->options->replaces = ast_var_value(current);
  5151. } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
  5152. if (sscanf(ast_var_value(current), "%d", &(p->maxforwards)) != 1) {
  5153. ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
  5154. }
  5155. }
  5156. }
  5157. /* Check to see if we should try to force encryption */
  5158. if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
  5159. ast_log(LOG_WARNING, "Encrypted signaling is required\n");
  5160. ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  5161. return -1;
  5162. }
  5163. if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
  5164. if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
  5165. ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
  5166. ast_clear_flag(&p->flags[0], SIP_REINVITE);
  5167. }
  5168. if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
  5169. ast_log(LOG_WARNING, "SRTP audio setup failed\n");
  5170. return -1;
  5171. }
  5172. if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
  5173. ast_log(LOG_WARNING, "SRTP video setup failed\n");
  5174. return -1;
  5175. }
  5176. if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
  5177. ast_log(LOG_WARNING, "SRTP text setup failed\n");
  5178. return -1;
  5179. }
  5180. }
  5181. res = 0;
  5182. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  5183. /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
  5184. * so ensure it is disabled.
  5185. */
  5186. ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
  5187. if (p->options->transfer) {
  5188. char buf[SIPBUFSIZE/2];
  5189. if (referer) {
  5190. if (sipdebug)
  5191. ast_debug(3, "Call for %s transferred by %s\n", p->username, referer);
  5192. snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
  5193. } else
  5194. snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
  5195. ast_string_field_set(p, cid_name, buf);
  5196. }
  5197. ast_debug(1, "Outgoing Call for %s\n", p->username);
  5198. res = update_call_counter(p, INC_CALL_RINGING);
  5199. if (res == -1) {
  5200. ast->hangupcause = AST_CAUSE_USER_BUSY;
  5201. return res;
  5202. }
  5203. p->callingpres = ast_party_id_presentation(&ast->caller.id);
  5204. p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
  5205. p->jointnoncodeccapability = p->noncodeccapability;
  5206. /* If there are no audio formats left to offer, punt */
  5207. if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
  5208. ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
  5209. res = -1;
  5210. } else {
  5211. int xmitres;
  5212. struct ast_party_connected_line connected;
  5213. struct ast_set_party_connected_line update_connected;
  5214. sip_pvt_lock(p);
  5215. /* Supply initial connected line information if available. */
  5216. memset(&update_connected, 0, sizeof(update_connected));
  5217. ast_party_connected_line_init(&connected);
  5218. if (!ast_strlen_zero(p->cid_num)
  5219. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  5220. update_connected.id.number = 1;
  5221. connected.id.number.valid = 1;
  5222. connected.id.number.str = (char *) p->cid_num;
  5223. connected.id.number.presentation = p->callingpres;
  5224. }
  5225. if (!ast_strlen_zero(p->cid_name)
  5226. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  5227. update_connected.id.name = 1;
  5228. connected.id.name.valid = 1;
  5229. connected.id.name.str = (char *) p->cid_name;
  5230. connected.id.name.presentation = p->callingpres;
  5231. }
  5232. if (update_connected.id.number || update_connected.id.name) {
  5233. connected.id.tag = (char *) p->cid_tag;
  5234. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  5235. ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
  5236. }
  5237. xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
  5238. if (xmitres == XMIT_ERROR) {
  5239. sip_pvt_unlock(p);
  5240. return -1;
  5241. }
  5242. p->invitestate = INV_CALLING;
  5243. /* Initialize auto-congest time */
  5244. AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
  5245. dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
  5246. dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
  5247. dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
  5248. sip_pvt_unlock(p);
  5249. }
  5250. return res;
  5251. }
  5252. /*! \brief Destroy registry object
  5253. Objects created with the register= statement in static configuration */
  5254. static void sip_registry_destroy(struct sip_registry *reg)
  5255. {
  5256. /* Really delete */
  5257. ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
  5258. if (reg->call) {
  5259. /* Clear registry before destroying to ensure
  5260. we don't get reentered trying to grab the registry lock */
  5261. reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
  5262. ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
  5263. dialog_unlink_all(reg->call);
  5264. reg->call = dialog_unref(reg->call, "unref reg->call");
  5265. /* reg->call = sip_destroy(reg->call); */
  5266. }
  5267. AST_SCHED_DEL(sched, reg->expire);
  5268. AST_SCHED_DEL(sched, reg->timeout);
  5269. ast_string_field_free_memory(reg);
  5270. ast_atomic_fetchadd_int(&regobjs, -1);
  5271. ast_free(reg);
  5272. }
  5273. /*! \brief Destroy MWI subscription object */
  5274. static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
  5275. {
  5276. if (mwi->call) {
  5277. mwi->call->mwi = NULL;
  5278. mwi->call = dialog_unref(mwi->call, "sip_subscription_mwi destruction");
  5279. }
  5280. AST_SCHED_DEL(sched, mwi->resub);
  5281. ast_string_field_free_memory(mwi);
  5282. ast_free(mwi);
  5283. }
  5284. /*! \brief Execute destruction of SIP dialog structure, release memory */
  5285. void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
  5286. {
  5287. struct sip_request *req;
  5288. /* Destroy Session-Timers if allocated */
  5289. if (p->stimer) {
  5290. p->stimer->quit_flag = 1;
  5291. stop_session_timer(p);
  5292. ast_free(p->stimer);
  5293. p->stimer = NULL;
  5294. }
  5295. if (sip_debug_test_pvt(p))
  5296. ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
  5297. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  5298. update_call_counter(p, DEC_CALL_LIMIT);
  5299. ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
  5300. }
  5301. /* Unlink us from the owner if we have one */
  5302. if (p->owner) {
  5303. if (lockowner)
  5304. ast_channel_lock(p->owner);
  5305. ast_debug(1, "Detaching from %s\n", p->owner->name);
  5306. p->owner->tech_pvt = NULL;
  5307. /* Make sure that the channel knows its backend is going away */
  5308. p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
  5309. if (lockowner)
  5310. ast_channel_unlock(p->owner);
  5311. /* Give the channel a chance to react before deallocation */
  5312. usleep(1);
  5313. }
  5314. /* Remove link from peer to subscription of MWI */
  5315. if (p->relatedpeer && p->relatedpeer->mwipvt == p)
  5316. p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
  5317. if (p->relatedpeer && p->relatedpeer->call == p)
  5318. p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
  5319. if (p->relatedpeer)
  5320. p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
  5321. if (p->registry) {
  5322. if (p->registry->call == p)
  5323. p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
  5324. p->registry = registry_unref(p->registry, "delete p->registry");
  5325. }
  5326. if (p->mwi) {
  5327. p->mwi->call = NULL;
  5328. p->mwi = NULL;
  5329. }
  5330. if (dumphistory)
  5331. sip_dump_history(p);
  5332. if (p->options) {
  5333. if (p->options->outboundproxy) {
  5334. ao2_ref(p->options->outboundproxy, -1);
  5335. }
  5336. ast_free(p->options);
  5337. p->options = NULL;
  5338. }
  5339. if (p->outboundproxy) {
  5340. ref_proxy(p, NULL);
  5341. }
  5342. if (p->notify) {
  5343. ast_variables_destroy(p->notify->headers);
  5344. ast_free(p->notify->content);
  5345. ast_free(p->notify);
  5346. p->notify = NULL;
  5347. }
  5348. if (p->rtp) {
  5349. ast_rtp_instance_destroy(p->rtp);
  5350. p->rtp = NULL;
  5351. }
  5352. if (p->vrtp) {
  5353. ast_rtp_instance_destroy(p->vrtp);
  5354. p->vrtp = NULL;
  5355. }
  5356. if (p->trtp) {
  5357. ast_rtp_instance_destroy(p->trtp);
  5358. p->trtp = NULL;
  5359. }
  5360. if (p->udptl) {
  5361. ast_udptl_destroy(p->udptl);
  5362. p->udptl = NULL;
  5363. }
  5364. if (p->refer) {
  5365. if (p->refer->refer_call) {
  5366. p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
  5367. }
  5368. ast_free(p->refer);
  5369. p->refer = NULL;
  5370. }
  5371. if (p->route) {
  5372. free_old_route(p->route);
  5373. p->route = NULL;
  5374. }
  5375. deinit_req(&p->initreq);
  5376. /* Clear history */
  5377. if (p->history) {
  5378. struct sip_history *hist;
  5379. while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
  5380. ast_free(hist);
  5381. p->history_entries--;
  5382. }
  5383. ast_free(p->history);
  5384. p->history = NULL;
  5385. }
  5386. while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
  5387. ast_free(req);
  5388. }
  5389. if (p->chanvars) {
  5390. ast_variables_destroy(p->chanvars);
  5391. p->chanvars = NULL;
  5392. }
  5393. if (p->srtp) {
  5394. sip_srtp_destroy(p->srtp);
  5395. p->srtp = NULL;
  5396. }
  5397. if (p->vsrtp) {
  5398. sip_srtp_destroy(p->vsrtp);
  5399. p->vsrtp = NULL;
  5400. }
  5401. if (p->tsrtp) {
  5402. sip_srtp_destroy(p->tsrtp);
  5403. p->tsrtp = NULL;
  5404. }
  5405. if (p->directmediaha) {
  5406. ast_free_ha(p->directmediaha);
  5407. p->directmediaha = NULL;
  5408. }
  5409. ast_string_field_free_memory(p);
  5410. ast_cc_config_params_destroy(p->cc_params);
  5411. p->cc_params = NULL;
  5412. if (p->epa_entry) {
  5413. ao2_ref(p->epa_entry, -1);
  5414. p->epa_entry = NULL;
  5415. }
  5416. if (p->socket.tcptls_session) {
  5417. ao2_ref(p->socket.tcptls_session, -1);
  5418. p->socket.tcptls_session = NULL;
  5419. }
  5420. if (p->peerauth) {
  5421. ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
  5422. p->peerauth = NULL;
  5423. }
  5424. }
  5425. /*! \brief update_call_counter: Handle call_limit for SIP devices
  5426. * Setting a call-limit will cause calls above the limit not to be accepted.
  5427. *
  5428. * Remember that for a type=friend, there's one limit for the user and
  5429. * another for the peer, not a combined call limit.
  5430. * This will cause unexpected behaviour in subscriptions, since a "friend"
  5431. * is *two* devices in Asterisk, not one.
  5432. *
  5433. * Thought: For realtime, we should probably update storage with inuse counter...
  5434. *
  5435. * \return 0 if call is ok (no call limit, below threshold)
  5436. * -1 on rejection of call
  5437. *
  5438. */
  5439. static int update_call_counter(struct sip_pvt *fup, int event)
  5440. {
  5441. char name[256];
  5442. int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
  5443. int outgoing = fup->outgoing_call;
  5444. struct sip_peer *p = NULL;
  5445. ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
  5446. /* Test if we need to check call limits, in order to avoid
  5447. realtime lookups if we do not need it */
  5448. if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
  5449. return 0;
  5450. ast_copy_string(name, fup->username, sizeof(name));
  5451. /* Check the list of devices */
  5452. if (fup->relatedpeer) {
  5453. p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
  5454. inuse = &p->inUse;
  5455. call_limit = &p->call_limit;
  5456. inringing = &p->inRinging;
  5457. ast_copy_string(name, fup->peername, sizeof(name));
  5458. }
  5459. if (!p) {
  5460. ast_debug(2, "%s is not a local device, no call limit\n", name);
  5461. return 0;
  5462. }
  5463. switch(event) {
  5464. /* incoming and outgoing affects the inUse counter */
  5465. case DEC_CALL_LIMIT:
  5466. /* Decrement inuse count if applicable */
  5467. if (inuse) {
  5468. sip_pvt_lock(fup);
  5469. ao2_lock(p);
  5470. if (*inuse > 0) {
  5471. if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
  5472. (*inuse)--;
  5473. ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
  5474. }
  5475. } else {
  5476. *inuse = 0;
  5477. }
  5478. ao2_unlock(p);
  5479. sip_pvt_unlock(fup);
  5480. }
  5481. /* Decrement ringing count if applicable */
  5482. if (inringing) {
  5483. sip_pvt_lock(fup);
  5484. ao2_lock(p);
  5485. if (*inringing > 0) {
  5486. if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
  5487. (*inringing)--;
  5488. ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
  5489. }
  5490. } else {
  5491. *inringing = 0;
  5492. }
  5493. ao2_unlock(p);
  5494. sip_pvt_unlock(fup);
  5495. }
  5496. /* Decrement onhold count if applicable */
  5497. sip_pvt_lock(fup);
  5498. ao2_lock(p);
  5499. if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
  5500. ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
  5501. ao2_unlock(p);
  5502. sip_pvt_unlock(fup);
  5503. sip_peer_hold(fup, FALSE);
  5504. } else {
  5505. ao2_unlock(p);
  5506. sip_pvt_unlock(fup);
  5507. }
  5508. if (sipdebug)
  5509. ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
  5510. break;
  5511. case INC_CALL_RINGING:
  5512. case INC_CALL_LIMIT:
  5513. /* If call limit is active and we have reached the limit, reject the call */
  5514. if (*call_limit > 0 ) {
  5515. if (*inuse >= *call_limit) {
  5516. ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
  5517. unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
  5518. return -1;
  5519. }
  5520. }
  5521. if (inringing && (event == INC_CALL_RINGING)) {
  5522. sip_pvt_lock(fup);
  5523. ao2_lock(p);
  5524. if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
  5525. (*inringing)++;
  5526. ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
  5527. }
  5528. ao2_unlock(p);
  5529. sip_pvt_unlock(fup);
  5530. }
  5531. if (inuse) {
  5532. sip_pvt_lock(fup);
  5533. ao2_lock(p);
  5534. if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
  5535. (*inuse)++;
  5536. ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
  5537. }
  5538. ao2_unlock(p);
  5539. sip_pvt_unlock(fup);
  5540. }
  5541. if (sipdebug) {
  5542. ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
  5543. }
  5544. break;
  5545. case DEC_CALL_RINGING:
  5546. if (inringing) {
  5547. sip_pvt_lock(fup);
  5548. ao2_lock(p);
  5549. if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
  5550. if (*inringing > 0) {
  5551. (*inringing)--;
  5552. }
  5553. ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
  5554. }
  5555. ao2_unlock(p);
  5556. sip_pvt_unlock(fup);
  5557. }
  5558. break;
  5559. default:
  5560. ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
  5561. }
  5562. if (p) {
  5563. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", p->name);
  5564. unref_peer(p, "update_call_counter: unref_peer from call counter");
  5565. }
  5566. return 0;
  5567. }
  5568. static void sip_destroy_fn(void *p)
  5569. {
  5570. sip_destroy(p);
  5571. }
  5572. /*! \brief Destroy SIP call structure.
  5573. * Make it return NULL so the caller can do things like
  5574. * foo = sip_destroy(foo);
  5575. * and reduce the chance of bugs due to dangling pointers.
  5576. */
  5577. struct sip_pvt *sip_destroy(struct sip_pvt *p)
  5578. {
  5579. ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
  5580. __sip_destroy(p, TRUE, TRUE);
  5581. return NULL;
  5582. }
  5583. /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
  5584. int hangup_sip2cause(int cause)
  5585. {
  5586. /* Possible values taken from causes.h */
  5587. switch(cause) {
  5588. case 401: /* Unauthorized */
  5589. return AST_CAUSE_CALL_REJECTED;
  5590. case 403: /* Not found */
  5591. return AST_CAUSE_CALL_REJECTED;
  5592. case 404: /* Not found */
  5593. return AST_CAUSE_UNALLOCATED;
  5594. case 405: /* Method not allowed */
  5595. return AST_CAUSE_INTERWORKING;
  5596. case 407: /* Proxy authentication required */
  5597. return AST_CAUSE_CALL_REJECTED;
  5598. case 408: /* No reaction */
  5599. return AST_CAUSE_NO_USER_RESPONSE;
  5600. case 409: /* Conflict */
  5601. return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
  5602. case 410: /* Gone */
  5603. return AST_CAUSE_NUMBER_CHANGED;
  5604. case 411: /* Length required */
  5605. return AST_CAUSE_INTERWORKING;
  5606. case 413: /* Request entity too large */
  5607. return AST_CAUSE_INTERWORKING;
  5608. case 414: /* Request URI too large */
  5609. return AST_CAUSE_INTERWORKING;
  5610. case 415: /* Unsupported media type */
  5611. return AST_CAUSE_INTERWORKING;
  5612. case 420: /* Bad extension */
  5613. return AST_CAUSE_NO_ROUTE_DESTINATION;
  5614. case 480: /* No answer */
  5615. return AST_CAUSE_NO_ANSWER;
  5616. case 481: /* No answer */
  5617. return AST_CAUSE_INTERWORKING;
  5618. case 482: /* Loop detected */
  5619. return AST_CAUSE_INTERWORKING;
  5620. case 483: /* Too many hops */
  5621. return AST_CAUSE_NO_ANSWER;
  5622. case 484: /* Address incomplete */
  5623. return AST_CAUSE_INVALID_NUMBER_FORMAT;
  5624. case 485: /* Ambiguous */
  5625. return AST_CAUSE_UNALLOCATED;
  5626. case 486: /* Busy everywhere */
  5627. return AST_CAUSE_BUSY;
  5628. case 487: /* Request terminated */
  5629. return AST_CAUSE_INTERWORKING;
  5630. case 488: /* No codecs approved */
  5631. return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  5632. case 491: /* Request pending */
  5633. return AST_CAUSE_INTERWORKING;
  5634. case 493: /* Undecipherable */
  5635. return AST_CAUSE_INTERWORKING;
  5636. case 500: /* Server internal failure */
  5637. return AST_CAUSE_FAILURE;
  5638. case 501: /* Call rejected */
  5639. return AST_CAUSE_FACILITY_REJECTED;
  5640. case 502:
  5641. return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
  5642. case 503: /* Service unavailable */
  5643. return AST_CAUSE_CONGESTION;
  5644. case 504: /* Gateway timeout */
  5645. return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
  5646. case 505: /* SIP version not supported */
  5647. return AST_CAUSE_INTERWORKING;
  5648. case 600: /* Busy everywhere */
  5649. return AST_CAUSE_USER_BUSY;
  5650. case 603: /* Decline */
  5651. return AST_CAUSE_CALL_REJECTED;
  5652. case 604: /* Does not exist anywhere */
  5653. return AST_CAUSE_UNALLOCATED;
  5654. case 606: /* Not acceptable */
  5655. return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  5656. default:
  5657. if (cause < 500 && cause >= 400) {
  5658. /* 4xx class error that is unknown - someting wrong with our request */
  5659. return AST_CAUSE_INTERWORKING;
  5660. } else if (cause < 600 && cause >= 500) {
  5661. /* 5xx class error - problem in the remote end */
  5662. return AST_CAUSE_CONGESTION;
  5663. } else if (cause < 700 && cause >= 600) {
  5664. /* 6xx - global errors in the 4xx class */
  5665. return AST_CAUSE_INTERWORKING;
  5666. }
  5667. return AST_CAUSE_NORMAL;
  5668. }
  5669. /* Never reached */
  5670. return 0;
  5671. }
  5672. /*! \brief Convert Asterisk hangup causes to SIP codes
  5673. \verbatim
  5674. Possible values from causes.h
  5675. AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
  5676. AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
  5677. In addition to these, a lot of PRI codes is defined in causes.h
  5678. ...should we take care of them too ?
  5679. Quote RFC 3398
  5680. ISUP Cause value SIP response
  5681. ---------------- ------------
  5682. 1 unallocated number 404 Not Found
  5683. 2 no route to network 404 Not found
  5684. 3 no route to destination 404 Not found
  5685. 16 normal call clearing --- (*)
  5686. 17 user busy 486 Busy here
  5687. 18 no user responding 408 Request Timeout
  5688. 19 no answer from the user 480 Temporarily unavailable
  5689. 20 subscriber absent 480 Temporarily unavailable
  5690. 21 call rejected 403 Forbidden (+)
  5691. 22 number changed (w/o diagnostic) 410 Gone
  5692. 22 number changed (w/ diagnostic) 301 Moved Permanently
  5693. 23 redirection to new destination 410 Gone
  5694. 26 non-selected user clearing 404 Not Found (=)
  5695. 27 destination out of order 502 Bad Gateway
  5696. 28 address incomplete 484 Address incomplete
  5697. 29 facility rejected 501 Not implemented
  5698. 31 normal unspecified 480 Temporarily unavailable
  5699. \endverbatim
  5700. */
  5701. const char *hangup_cause2sip(int cause)
  5702. {
  5703. switch (cause) {
  5704. case AST_CAUSE_UNALLOCATED: /* 1 */
  5705. case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
  5706. case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
  5707. return "404 Not Found";
  5708. case AST_CAUSE_CONGESTION: /* 34 */
  5709. case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
  5710. return "503 Service Unavailable";
  5711. case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
  5712. return "408 Request Timeout";
  5713. case AST_CAUSE_NO_ANSWER: /* 19 */
  5714. case AST_CAUSE_UNREGISTERED: /* 20 */
  5715. return "480 Temporarily unavailable";
  5716. case AST_CAUSE_CALL_REJECTED: /* 21 */
  5717. return "403 Forbidden";
  5718. case AST_CAUSE_NUMBER_CHANGED: /* 22 */
  5719. return "410 Gone";
  5720. case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
  5721. return "480 Temporarily unavailable";
  5722. case AST_CAUSE_INVALID_NUMBER_FORMAT:
  5723. return "484 Address incomplete";
  5724. case AST_CAUSE_USER_BUSY:
  5725. return "486 Busy here";
  5726. case AST_CAUSE_FAILURE:
  5727. return "500 Server internal failure";
  5728. case AST_CAUSE_FACILITY_REJECTED: /* 29 */
  5729. return "501 Not Implemented";
  5730. case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
  5731. return "503 Service Unavailable";
  5732. /* Used in chan_iax2 */
  5733. case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
  5734. return "502 Bad Gateway";
  5735. case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
  5736. return "488 Not Acceptable Here";
  5737. case AST_CAUSE_NOTDEFINED:
  5738. default:
  5739. ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
  5740. return NULL;
  5741. }
  5742. /* Never reached */
  5743. return 0;
  5744. }
  5745. static int reinvite_timeout(const void *data)
  5746. {
  5747. struct sip_pvt *dialog = (struct sip_pvt *) data;
  5748. struct ast_channel *owner = sip_pvt_lock_full(dialog);
  5749. dialog->reinviteid = -1;
  5750. check_pendings(dialog);
  5751. if (owner) {
  5752. ast_channel_unlock(owner);
  5753. ast_channel_unref(owner);
  5754. }
  5755. ao2_unlock(dialog);
  5756. dialog_unref(dialog, "unref for reinvite timeout");
  5757. return 0;
  5758. }
  5759. /*! \brief sip_hangup: Hangup SIP call
  5760. * Part of PBX interface, called from ast_hangup */
  5761. static int sip_hangup(struct ast_channel *ast)
  5762. {
  5763. struct sip_pvt *p = ast->tech_pvt;
  5764. int needcancel = FALSE;
  5765. int needdestroy = 0;
  5766. struct ast_channel *oldowner = ast;
  5767. if (!p) {
  5768. ast_debug(1, "Asked to hangup channel that was not connected\n");
  5769. return 0;
  5770. }
  5771. if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
  5772. ast_debug(1, "This call was answered elsewhere\n");
  5773. if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
  5774. ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
  5775. }
  5776. append_history(p, "Cancel", "Call answered elsewhere");
  5777. p->answered_elsewhere = TRUE;
  5778. }
  5779. /* Store hangupcause locally in PVT so we still have it before disconnect */
  5780. if (p->owner)
  5781. p->hangupcause = p->owner->hangupcause;
  5782. if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
  5783. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  5784. if (sipdebug)
  5785. ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
  5786. update_call_counter(p, DEC_CALL_LIMIT);
  5787. }
  5788. ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
  5789. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  5790. ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
  5791. p->needdestroy = 0;
  5792. if (p->owner) {
  5793. p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
  5794. sip_pvt_lock(p);
  5795. p->owner = NULL; /* Owner will be gone after we return, so take it away */
  5796. sip_pvt_unlock(p);
  5797. }
  5798. ast_module_unref(ast_module_info->self);
  5799. return 0;
  5800. }
  5801. ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
  5802. sip_pvt_lock(p);
  5803. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  5804. if (sipdebug)
  5805. ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
  5806. update_call_counter(p, DEC_CALL_LIMIT);
  5807. }
  5808. /* Determine how to disconnect */
  5809. if (p->owner != ast) {
  5810. ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
  5811. sip_pvt_unlock(p);
  5812. return 0;
  5813. }
  5814. /* If the call is not UP, we need to send CANCEL instead of BYE */
  5815. /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
  5816. if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
  5817. needcancel = TRUE;
  5818. ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
  5819. }
  5820. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  5821. append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", ast_cause2str(p->hangupcause));
  5822. /* Disconnect */
  5823. disable_dsp_detect(p);
  5824. p->owner = NULL;
  5825. ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
  5826. ast_module_unref(ast_module_info->self);
  5827. /* Do not destroy this pvt until we have timeout or
  5828. get an answer to the BYE or INVITE/CANCEL
  5829. If we get no answer during retransmit period, drop the call anyway.
  5830. (Sorry, mother-in-law, you can't deny a hangup by sending
  5831. 603 declined to BYE...)
  5832. */
  5833. if (p->alreadygone)
  5834. needdestroy = 1; /* Set destroy flag at end of this function */
  5835. else if (p->invitestate != INV_CALLING)
  5836. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  5837. /* Start the process if it's not already started */
  5838. if (!p->alreadygone && p->initreq.data && ast_str_strlen(p->initreq.data)) {
  5839. if (needcancel) { /* Outgoing call, not up */
  5840. if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  5841. /* if we can't send right now, mark it pending */
  5842. if (p->invitestate == INV_CALLING) {
  5843. /* We can't send anything in CALLING state */
  5844. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  5845. /* 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. */
  5846. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  5847. append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
  5848. } else {
  5849. struct sip_pkt *cur;
  5850. for (cur = p->packets; cur; cur = cur->next) {
  5851. __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(ast_str_buffer(cur->data)));
  5852. }
  5853. p->invitestate = INV_CANCELLED;
  5854. /* Send a new request: CANCEL */
  5855. transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
  5856. /* Actually don't destroy us yet, wait for the 487 on our original
  5857. INVITE, but do set an autodestruct just in case we never get it. */
  5858. needdestroy = 0;
  5859. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  5860. }
  5861. } else { /* Incoming call, not up */
  5862. const char *res;
  5863. 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"));
  5864. if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
  5865. transmit_response_reliable(p, res, &p->initreq);
  5866. else
  5867. transmit_response_reliable(p, "603 Declined", &p->initreq);
  5868. p->invitestate = INV_TERMINATED;
  5869. }
  5870. } else { /* Call is in UP state, send BYE */
  5871. if (p->stimer->st_active == TRUE) {
  5872. stop_session_timer(p);
  5873. }
  5874. if (!p->pendinginvite) {
  5875. struct ast_channel *bridge = ast_bridged_channel(oldowner);
  5876. char quality_buf[AST_MAX_USER_FIELD], *quality;
  5877. /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
  5878. * to lock the bridge. This may get hairy...
  5879. */
  5880. while (bridge && ast_channel_trylock(bridge)) {
  5881. sip_pvt_unlock(p);
  5882. do {
  5883. CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
  5884. } while (sip_pvt_trylock(p));
  5885. bridge = ast_bridged_channel(oldowner);
  5886. }
  5887. if (p->rtp) {
  5888. ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
  5889. }
  5890. if (bridge) {
  5891. struct sip_pvt *q = bridge->tech_pvt;
  5892. if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
  5893. ast_rtp_instance_set_stats_vars(bridge, q->rtp);
  5894. }
  5895. ast_channel_unlock(bridge);
  5896. }
  5897. /*
  5898. * The channel variables are set below just to get the AMI
  5899. * VarSet event because the channel is being hungup.
  5900. */
  5901. if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  5902. if (p->do_history) {
  5903. append_history(p, "RTCPaudio", "Quality:%s", quality);
  5904. }
  5905. pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
  5906. }
  5907. if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  5908. if (p->do_history) {
  5909. append_history(p, "RTCPvideo", "Quality:%s", quality);
  5910. }
  5911. pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
  5912. }
  5913. if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  5914. if (p->do_history) {
  5915. append_history(p, "RTCPtext", "Quality:%s", quality);
  5916. }
  5917. pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
  5918. }
  5919. /* Send a hangup */
  5920. if (oldowner->_state == AST_STATE_UP) {
  5921. transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
  5922. }
  5923. } else {
  5924. /* Note we will need a BYE when this all settles out
  5925. but we can't send one while we have "INVITE" outstanding. */
  5926. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  5927. ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
  5928. 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"));
  5929. if (sip_cancel_destroy(p)) {
  5930. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  5931. }
  5932. /* If we have an ongoing reinvite, there is a chance that we have gotten a provisional
  5933. * response, but something weird has happened and we will never receive a final response.
  5934. * So, just in case, check for pending actions after a bit of time to trigger the pending
  5935. * bye that we are setting above */
  5936. if (p->ongoing_reinvite && p->reinviteid < 0) {
  5937. p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));
  5938. }
  5939. }
  5940. }
  5941. }
  5942. if (needdestroy) {
  5943. pvt_set_needdestroy(p, "hangup");
  5944. }
  5945. sip_pvt_unlock(p);
  5946. return 0;
  5947. }
  5948. /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
  5949. static void try_suggested_sip_codec(struct sip_pvt *p)
  5950. {
  5951. format_t fmt;
  5952. const char *codec;
  5953. if (p->outgoing_call) {
  5954. codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
  5955. } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
  5956. codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
  5957. }
  5958. if (!codec)
  5959. return;
  5960. fmt = ast_getformatbyname(codec);
  5961. if (fmt) {
  5962. ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
  5963. if (p->jointcapability & fmt) {
  5964. p->jointcapability &= fmt;
  5965. p->capability &= fmt;
  5966. } else
  5967. ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
  5968. } else
  5969. ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
  5970. return;
  5971. }
  5972. /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
  5973. * Part of PBX interface */
  5974. static int sip_answer(struct ast_channel *ast)
  5975. {
  5976. int res = 0;
  5977. struct sip_pvt *p = ast->tech_pvt;
  5978. int oldsdp = FALSE;
  5979. if (!p) {
  5980. ast_debug(1, "Asked to answer channel %s without tech pvt; ignoring\n",
  5981. ast->name);
  5982. return res;
  5983. }
  5984. sip_pvt_lock(p);
  5985. if (ast->_state != AST_STATE_UP) {
  5986. try_suggested_sip_codec(p);
  5987. if (ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
  5988. oldsdp = TRUE;
  5989. }
  5990. ast_setstate(ast, AST_STATE_UP);
  5991. ast_debug(1, "SIP answering channel: %s\n", ast->name);
  5992. ast_rtp_instance_update_source(p->rtp);
  5993. res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, oldsdp, TRUE);
  5994. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  5995. /* RFC says the session timer starts counting on 200,
  5996. * not on INVITE. */
  5997. if (p->stimer->st_active == TRUE) {
  5998. start_session_timer(p);
  5999. }
  6000. }
  6001. sip_pvt_unlock(p);
  6002. return res;
  6003. }
  6004. /*! \brief Send frame to media channel (rtp) */
  6005. static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
  6006. {
  6007. struct sip_pvt *p = ast->tech_pvt;
  6008. int res = 0;
  6009. switch (frame->frametype) {
  6010. case AST_FRAME_VOICE:
  6011. if (!(frame->subclass.codec & ast->nativeformats)) {
  6012. char s1[512], s2[512], s3[512];
  6013. ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
  6014. ast_getformatname(frame->subclass.codec),
  6015. ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK),
  6016. ast_getformatname_multiple(s2, sizeof(s2), ast->readformat),
  6017. ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat));
  6018. return 0;
  6019. }
  6020. if (p) {
  6021. sip_pvt_lock(p);
  6022. if (p->t38.state == T38_ENABLED) {
  6023. /* drop frame, can't sent VOICE frames while in T.38 mode */
  6024. sip_pvt_unlock(p);
  6025. break;
  6026. } else if (p->rtp) {
  6027. /* If channel is not up, activate early media session */
  6028. if ((ast->_state != AST_STATE_UP) &&
  6029. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6030. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6031. ast_rtp_instance_update_source(p->rtp);
  6032. if (!global_prematuremediafilter) {
  6033. p->invitestate = INV_EARLY_MEDIA;
  6034. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6035. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6036. }
  6037. }
  6038. p->lastrtptx = time(NULL);
  6039. res = ast_rtp_instance_write(p->rtp, frame);
  6040. }
  6041. sip_pvt_unlock(p);
  6042. }
  6043. break;
  6044. case AST_FRAME_VIDEO:
  6045. if (p) {
  6046. sip_pvt_lock(p);
  6047. if (p->vrtp) {
  6048. /* Activate video early media */
  6049. if ((ast->_state != AST_STATE_UP) &&
  6050. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6051. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6052. p->invitestate = INV_EARLY_MEDIA;
  6053. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6054. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6055. }
  6056. p->lastrtptx = time(NULL);
  6057. res = ast_rtp_instance_write(p->vrtp, frame);
  6058. }
  6059. sip_pvt_unlock(p);
  6060. }
  6061. break;
  6062. case AST_FRAME_TEXT:
  6063. if (p) {
  6064. sip_pvt_lock(p);
  6065. if (p->red) {
  6066. ast_rtp_red_buffer(p->trtp, frame);
  6067. } else {
  6068. if (p->trtp) {
  6069. /* Activate text early media */
  6070. if ((ast->_state != AST_STATE_UP) &&
  6071. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6072. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6073. p->invitestate = INV_EARLY_MEDIA;
  6074. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6075. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6076. }
  6077. p->lastrtptx = time(NULL);
  6078. res = ast_rtp_instance_write(p->trtp, frame);
  6079. }
  6080. }
  6081. sip_pvt_unlock(p);
  6082. }
  6083. break;
  6084. case AST_FRAME_IMAGE:
  6085. return 0;
  6086. break;
  6087. case AST_FRAME_MODEM:
  6088. if (p) {
  6089. sip_pvt_lock(p);
  6090. /* UDPTL requires two-way communication, so early media is not needed here.
  6091. we simply forget the frames if we get modem frames before the bridge is up.
  6092. Fax will re-transmit.
  6093. */
  6094. if ((ast->_state == AST_STATE_UP) &&
  6095. p->udptl &&
  6096. (p->t38.state == T38_ENABLED)) {
  6097. res = ast_udptl_write(p->udptl, frame);
  6098. }
  6099. sip_pvt_unlock(p);
  6100. }
  6101. break;
  6102. default:
  6103. ast_log(LOG_WARNING, "Can't send %u type frames with SIP write\n", frame->frametype);
  6104. return 0;
  6105. }
  6106. return res;
  6107. }
  6108. /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
  6109. Basically update any ->owner links */
  6110. static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
  6111. {
  6112. int ret = -1;
  6113. struct sip_pvt *p;
  6114. if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
  6115. ast_debug(1, "New channel is zombie\n");
  6116. if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
  6117. ast_debug(1, "Old channel is zombie\n");
  6118. if (!newchan || !newchan->tech_pvt) {
  6119. if (!newchan)
  6120. ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
  6121. else
  6122. ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
  6123. return -1;
  6124. }
  6125. p = newchan->tech_pvt;
  6126. sip_pvt_lock(p);
  6127. append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
  6128. append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
  6129. if (p->owner != oldchan)
  6130. ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
  6131. else {
  6132. p->owner = newchan;
  6133. /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
  6134. RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
  6135. able to do this if the masquerade happens before the bridge breaks (e.g., AMI
  6136. redirect of both channels). Note that a channel can not be masqueraded *into*
  6137. a native bridge. So there is no danger that this breaks a native bridge that
  6138. should stay up. */
  6139. sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
  6140. ret = 0;
  6141. }
  6142. ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
  6143. sip_pvt_unlock(p);
  6144. return ret;
  6145. }
  6146. static int sip_senddigit_begin(struct ast_channel *ast, char digit)
  6147. {
  6148. struct sip_pvt *p = ast->tech_pvt;
  6149. int res = 0;
  6150. if (!p) {
  6151. ast_debug(1, "Asked to begin DTMF digit on channel %s with no pvt; ignoring\n",
  6152. ast->name);
  6153. return res;
  6154. }
  6155. sip_pvt_lock(p);
  6156. switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
  6157. case SIP_DTMF_INBAND:
  6158. res = -1; /* Tell Asterisk to generate inband indications */
  6159. break;
  6160. case SIP_DTMF_RFC2833:
  6161. if (p->rtp)
  6162. ast_rtp_instance_dtmf_begin(p->rtp, digit);
  6163. break;
  6164. default:
  6165. break;
  6166. }
  6167. sip_pvt_unlock(p);
  6168. return res;
  6169. }
  6170. /*! \brief Send DTMF character on SIP channel
  6171. within one call, we're able to transmit in many methods simultaneously */
  6172. static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
  6173. {
  6174. struct sip_pvt *p = ast->tech_pvt;
  6175. int res = 0;
  6176. if (!p) {
  6177. ast_debug(1, "Asked to end DTMF digit on channel %s with no pvt; ignoring\n",
  6178. ast->name);
  6179. return res;
  6180. }
  6181. sip_pvt_lock(p);
  6182. switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
  6183. case SIP_DTMF_INFO:
  6184. case SIP_DTMF_SHORTINFO:
  6185. transmit_info_with_digit(p, digit, duration);
  6186. break;
  6187. case SIP_DTMF_RFC2833:
  6188. if (p->rtp)
  6189. ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
  6190. break;
  6191. case SIP_DTMF_INBAND:
  6192. res = -1; /* Tell Asterisk to stop inband indications */
  6193. break;
  6194. }
  6195. sip_pvt_unlock(p);
  6196. return res;
  6197. }
  6198. /*! \brief Transfer SIP call */
  6199. static int sip_transfer(struct ast_channel *ast, const char *dest)
  6200. {
  6201. struct sip_pvt *p = ast->tech_pvt;
  6202. int res;
  6203. if (!p) {
  6204. ast_debug(1, "Asked to transfer channel %s with no pvt; ignoring\n",
  6205. ast->name);
  6206. return -1;
  6207. }
  6208. if (dest == NULL) /* functions below do not take a NULL */
  6209. dest = "";
  6210. sip_pvt_lock(p);
  6211. if (ast->_state == AST_STATE_RING)
  6212. res = sip_sipredirect(p, dest);
  6213. else
  6214. res = transmit_refer(p, dest);
  6215. sip_pvt_unlock(p);
  6216. return res;
  6217. }
  6218. /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
  6219. static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
  6220. {
  6221. int res = 0;
  6222. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
  6223. return -1;
  6224. }
  6225. switch (parameters->request_response) {
  6226. case AST_T38_NEGOTIATED:
  6227. case AST_T38_REQUEST_NEGOTIATE: /* Request T38 */
  6228. /* Negotiation can not take place without a valid max_ifp value. */
  6229. if (!parameters->max_ifp) {
  6230. change_t38_state(p, T38_DISABLED);
  6231. if (p->t38.state == T38_PEER_REINVITE) {
  6232. 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"));
  6233. transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
  6234. }
  6235. break;
  6236. } else if (p->t38.state == T38_PEER_REINVITE) {
  6237. 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"));
  6238. p->t38.our_parms = *parameters;
  6239. /* modify our parameters to conform to the peer's parameters,
  6240. * based on the rules in the ITU T.38 recommendation
  6241. */
  6242. if (!p->t38.their_parms.fill_bit_removal) {
  6243. p->t38.our_parms.fill_bit_removal = FALSE;
  6244. }
  6245. if (!p->t38.their_parms.transcoding_mmr) {
  6246. p->t38.our_parms.transcoding_mmr = FALSE;
  6247. }
  6248. if (!p->t38.their_parms.transcoding_jbig) {
  6249. p->t38.our_parms.transcoding_jbig = FALSE;
  6250. }
  6251. p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
  6252. p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
  6253. ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
  6254. change_t38_state(p, T38_ENABLED);
  6255. transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
  6256. } else if (p->t38.state != T38_ENABLED) {
  6257. p->t38.our_parms = *parameters;
  6258. ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
  6259. change_t38_state(p, T38_LOCAL_REINVITE);
  6260. if (!p->pendinginvite) {
  6261. transmit_reinvite_with_sdp(p, TRUE, FALSE);
  6262. } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  6263. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  6264. }
  6265. }
  6266. break;
  6267. case AST_T38_TERMINATED:
  6268. case AST_T38_REFUSED:
  6269. case AST_T38_REQUEST_TERMINATE: /* Shutdown T38 */
  6270. if (p->t38.state == T38_PEER_REINVITE) {
  6271. 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"));
  6272. change_t38_state(p, T38_DISABLED);
  6273. transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
  6274. } else if (p->t38.state == T38_ENABLED)
  6275. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  6276. break;
  6277. case AST_T38_REQUEST_PARMS: { /* Application wants remote's parameters re-sent */
  6278. struct ast_control_t38_parameters parameters = p->t38.their_parms;
  6279. if (p->t38.state == T38_PEER_REINVITE) {
  6280. 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"));
  6281. parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
  6282. parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
  6283. if (p->owner) {
  6284. ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
  6285. }
  6286. /* we need to return a positive value here, so that applications that
  6287. * send this request can determine conclusively whether it was accepted or not...
  6288. * older versions of chan_sip would just silently accept it and return zero.
  6289. */
  6290. res = AST_T38_REQUEST_PARMS;
  6291. }
  6292. break;
  6293. }
  6294. default:
  6295. res = -1;
  6296. break;
  6297. }
  6298. return res;
  6299. }
  6300. /*! \internal \brief Create and initialize UDPTL for the specified dialog
  6301. * \param p SIP private structure to create UDPTL object for
  6302. * \pre p is locked
  6303. * \pre p->owner is locked
  6304. *
  6305. * \note In the case of failure, SIP_PAGE2_T38SUPPORT is cleared on p
  6306. *
  6307. * \return 0 on success, any other value on failure
  6308. */
  6309. static int initialize_udptl(struct sip_pvt *p)
  6310. {
  6311. int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
  6312. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
  6313. return 1;
  6314. }
  6315. /* If we've already initialized T38, don't take any further action */
  6316. if (p->udptl) {
  6317. return 0;
  6318. }
  6319. /* T38 can be supported by this dialog, create it and set the derived properties */
  6320. if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
  6321. if (p->owner) {
  6322. ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
  6323. }
  6324. ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
  6325. p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
  6326. set_t38_capabilities(p);
  6327. ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
  6328. ast_udptl_setnat(p->udptl, natflags);
  6329. } else {
  6330. ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
  6331. ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
  6332. return 1;
  6333. }
  6334. return 0;
  6335. }
  6336. /*! \brief Play indication to user
  6337. * With SIP a lot of indications is sent as messages, letting the device play
  6338. the indication - busy signal, congestion etc
  6339. \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
  6340. */
  6341. static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
  6342. {
  6343. struct sip_pvt *p = ast->tech_pvt;
  6344. int res = 0;
  6345. if (!p) {
  6346. ast_debug(1, "Asked to indicate condition on channel %s with no pvt; ignoring\n",
  6347. ast->name);
  6348. return res;
  6349. }
  6350. sip_pvt_lock(p);
  6351. switch(condition) {
  6352. case AST_CONTROL_RINGING:
  6353. if (ast->_state == AST_STATE_RING) {
  6354. p->invitestate = INV_EARLY_MEDIA;
  6355. if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
  6356. (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
  6357. /* Send 180 ringing if out-of-band seems reasonable */
  6358. transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
  6359. ast_set_flag(&p->flags[0], SIP_RINGING);
  6360. if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
  6361. break;
  6362. } else {
  6363. /* Well, if it's not reasonable, just send in-band */
  6364. }
  6365. }
  6366. res = -1;
  6367. break;
  6368. case AST_CONTROL_BUSY:
  6369. if (ast->_state != AST_STATE_UP) {
  6370. transmit_response_reliable(p, "486 Busy Here", &p->initreq);
  6371. p->invitestate = INV_COMPLETED;
  6372. sip_alreadygone(p);
  6373. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6374. break;
  6375. }
  6376. res = -1;
  6377. break;
  6378. case AST_CONTROL_CONGESTION:
  6379. if (ast->_state != AST_STATE_UP) {
  6380. transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
  6381. p->invitestate = INV_COMPLETED;
  6382. sip_alreadygone(p);
  6383. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6384. break;
  6385. }
  6386. res = -1;
  6387. break;
  6388. case AST_CONTROL_INCOMPLETE:
  6389. if (ast->_state != AST_STATE_UP) {
  6390. switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
  6391. case SIP_PAGE2_ALLOWOVERLAP_YES:
  6392. transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
  6393. p->invitestate = INV_COMPLETED;
  6394. sip_alreadygone(p);
  6395. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6396. break;
  6397. case SIP_PAGE2_ALLOWOVERLAP_DTMF:
  6398. /* Just wait for inband DTMF digits */
  6399. break;
  6400. default:
  6401. /* it actually means no support for overlap */
  6402. transmit_response_reliable(p, "404 Not Found", &p->initreq);
  6403. p->invitestate = INV_COMPLETED;
  6404. sip_alreadygone(p);
  6405. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  6406. break;
  6407. }
  6408. }
  6409. break;
  6410. case AST_CONTROL_PROCEEDING:
  6411. if ((ast->_state != AST_STATE_UP) &&
  6412. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6413. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6414. transmit_response(p, "100 Trying", &p->initreq);
  6415. p->invitestate = INV_PROCEEDING;
  6416. break;
  6417. }
  6418. res = -1;
  6419. break;
  6420. case AST_CONTROL_PROGRESS:
  6421. if ((ast->_state != AST_STATE_UP) &&
  6422. !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
  6423. !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  6424. p->invitestate = INV_EARLY_MEDIA;
  6425. transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
  6426. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  6427. break;
  6428. }
  6429. res = -1;
  6430. break;
  6431. case AST_CONTROL_HOLD:
  6432. ast_rtp_instance_update_source(p->rtp);
  6433. ast_moh_start(ast, data, p->mohinterpret);
  6434. break;
  6435. case AST_CONTROL_UNHOLD:
  6436. ast_rtp_instance_update_source(p->rtp);
  6437. ast_moh_stop(ast);
  6438. break;
  6439. case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
  6440. if (p->vrtp && !p->novideo) {
  6441. transmit_info_with_vidupdate(p);
  6442. /* ast_rtcp_send_h261fur(p->vrtp); */
  6443. } else
  6444. res = -1;
  6445. break;
  6446. case AST_CONTROL_T38_PARAMETERS:
  6447. res = -1;
  6448. if (datalen != sizeof(struct ast_control_t38_parameters)) {
  6449. 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);
  6450. } else {
  6451. const struct ast_control_t38_parameters *parameters = data;
  6452. if (!initialize_udptl(p)) {
  6453. res = interpret_t38_parameters(p, parameters);
  6454. }
  6455. }
  6456. break;
  6457. case AST_CONTROL_SRCUPDATE:
  6458. ast_rtp_instance_update_source(p->rtp);
  6459. break;
  6460. case AST_CONTROL_SRCCHANGE:
  6461. ast_rtp_instance_change_source(p->rtp);
  6462. break;
  6463. case AST_CONTROL_CONNECTED_LINE:
  6464. update_connectedline(p, data, datalen);
  6465. break;
  6466. case AST_CONTROL_REDIRECTING:
  6467. update_redirecting(p, data, datalen);
  6468. break;
  6469. case AST_CONTROL_AOC:
  6470. {
  6471. struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
  6472. if (!decoded) {
  6473. ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
  6474. res = -1;
  6475. break;
  6476. }
  6477. switch (ast_aoc_get_msg_type(decoded)) {
  6478. case AST_AOC_REQUEST:
  6479. if (ast_aoc_get_termination_request(decoded)) {
  6480. /* TODO, once there is a way to get AOC-E on hangup, attempt that here
  6481. * before hanging up the channel.*/
  6482. /* The other side has already initiated the hangup. This frame
  6483. * just says they are waiting to get AOC-E before completely tearing
  6484. * the call down. Since SIP does not support this at the moment go
  6485. * ahead and terminate the call here to avoid an unnecessary timeout. */
  6486. ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);
  6487. ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
  6488. }
  6489. break;
  6490. case AST_AOC_D:
  6491. case AST_AOC_E:
  6492. if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
  6493. transmit_info_with_aoc(p, decoded);
  6494. }
  6495. break;
  6496. case AST_AOC_S: /* S not supported yet */
  6497. default:
  6498. break;
  6499. }
  6500. ast_aoc_destroy_decoded(decoded);
  6501. }
  6502. break;
  6503. case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
  6504. break;
  6505. 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. */
  6506. res = -1;
  6507. break;
  6508. case -1:
  6509. res = -1;
  6510. break;
  6511. default:
  6512. ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
  6513. res = -1;
  6514. break;
  6515. }
  6516. sip_pvt_unlock(p);
  6517. return res;
  6518. }
  6519. /*!
  6520. * \brief Initiate a call in the SIP channel
  6521. *
  6522. * \note called from sip_request_call (calls from the pbx ) for
  6523. * outbound channels and from handle_request_invite for inbound
  6524. * channels
  6525. *
  6526. * \pre i is locked
  6527. *
  6528. * \return New ast_channel locked.
  6529. */
  6530. static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
  6531. {
  6532. struct ast_channel *tmp;
  6533. struct ast_variable *v = NULL;
  6534. format_t fmt;
  6535. format_t what;
  6536. format_t video;
  6537. format_t text;
  6538. format_t needvideo = 0;
  6539. int needtext = 0;
  6540. char buf[SIPBUFSIZE];
  6541. char *exten;
  6542. {
  6543. const char *my_name; /* pick a good name */
  6544. if (title) {
  6545. my_name = title;
  6546. } else {
  6547. my_name = ast_strdupa(i->fromdomain);
  6548. }
  6549. sip_pvt_unlock(i);
  6550. /* Don't hold a sip pvt lock while we allocate a channel */
  6551. tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "SIP/%s-%08x", my_name, (unsigned)ast_atomic_fetchadd_int((int *)&chan_idx, +1));
  6552. }
  6553. if (!tmp) {
  6554. ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
  6555. sip_pvt_lock(i);
  6556. return NULL;
  6557. }
  6558. ast_channel_lock(tmp);
  6559. sip_pvt_lock(i);
  6560. ast_channel_cc_params_init(tmp, i->cc_params);
  6561. tmp->caller.id.tag = ast_strdup(i->cid_tag);
  6562. tmp->tech = ( 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;
  6563. /* Select our native format based on codec preference until we receive
  6564. something from another device to the contrary. */
  6565. if (i->jointcapability) { /* The joint capabilities of us and peer */
  6566. what = i->jointcapability;
  6567. video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
  6568. text = i->jointcapability & AST_FORMAT_TEXT_MASK;
  6569. } else if (i->capability) { /* Our configured capability for this peer */
  6570. what = i->capability;
  6571. video = i->capability & AST_FORMAT_VIDEO_MASK;
  6572. text = i->capability & AST_FORMAT_TEXT_MASK;
  6573. } else {
  6574. what = sip_cfg.capability; /* Global codec support */
  6575. video = sip_cfg.capability & AST_FORMAT_VIDEO_MASK;
  6576. text = sip_cfg.capability & AST_FORMAT_TEXT_MASK;
  6577. }
  6578. /* Set the native formats for audio and merge in video */
  6579. tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
  6580. ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
  6581. ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
  6582. ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
  6583. ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
  6584. if (i->prefcodec)
  6585. ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
  6586. /* XXX Why are we choosing a codec from the native formats?? */
  6587. fmt = ast_best_codec(tmp->nativeformats);
  6588. /* If we have a prefcodec setting, we have an inbound channel that set a
  6589. preferred format for this call. Otherwise, we check the jointcapability
  6590. We also check for vrtp. If it's not there, we are not allowed do any video anyway.
  6591. */
  6592. if (i->vrtp) {
  6593. if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
  6594. needvideo = AST_FORMAT_VIDEO_MASK;
  6595. else if (i->prefcodec)
  6596. needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
  6597. else
  6598. needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
  6599. }
  6600. if (i->trtp) {
  6601. if (i->prefcodec)
  6602. needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
  6603. else
  6604. needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
  6605. }
  6606. if (needvideo)
  6607. ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
  6608. else
  6609. ast_debug(3, "This channel will not be able to handle video.\n");
  6610. enable_dsp_detect(i);
  6611. if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  6612. (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  6613. if (i->rtp) {
  6614. ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
  6615. }
  6616. } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
  6617. if (i->rtp) {
  6618. ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
  6619. }
  6620. }
  6621. /* Set file descriptors for audio, video, and realtime text. Since
  6622. * UDPTL is created as needed in the lifetime of a dialog, its file
  6623. * descriptor is set in initialize_udptl */
  6624. if (i->rtp) {
  6625. ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
  6626. ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
  6627. ast_rtp_instance_set_write_format(i->rtp, fmt);
  6628. ast_rtp_instance_set_read_format(i->rtp, fmt);
  6629. }
  6630. if (needvideo && i->vrtp) {
  6631. ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
  6632. ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
  6633. }
  6634. if (needtext && i->trtp) {
  6635. ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
  6636. }
  6637. if (i->udptl) {
  6638. ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
  6639. }
  6640. if (state == AST_STATE_RING)
  6641. tmp->rings = 1;
  6642. tmp->adsicpe = AST_ADSI_UNAVAILABLE;
  6643. tmp->writeformat = fmt;
  6644. tmp->rawwriteformat = fmt;
  6645. tmp->readformat = fmt;
  6646. tmp->rawreadformat = fmt;
  6647. tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
  6648. tmp->callgroup = i->callgroup;
  6649. tmp->pickupgroup = i->pickupgroup;
  6650. tmp->caller.id.name.presentation = i->callingpres;
  6651. tmp->caller.id.number.presentation = i->callingpres;
  6652. if (!ast_strlen_zero(i->parkinglot))
  6653. ast_string_field_set(tmp, parkinglot, i->parkinglot);
  6654. if (!ast_strlen_zero(i->accountcode))
  6655. ast_string_field_set(tmp, accountcode, i->accountcode);
  6656. if (i->amaflags)
  6657. tmp->amaflags = i->amaflags;
  6658. if (!ast_strlen_zero(i->language))
  6659. ast_string_field_set(tmp, language, i->language);
  6660. i->owner = tmp;
  6661. ast_module_ref(ast_module_info->self);
  6662. ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
  6663. /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
  6664. * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
  6665. * structure so that there aren't issues when forming URI's
  6666. */
  6667. exten = ast_strdupa(i->exten);
  6668. sip_pvt_unlock(i);
  6669. ast_channel_unlock(tmp);
  6670. if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
  6671. ast_uri_decode(exten);
  6672. }
  6673. ast_channel_lock(tmp);
  6674. sip_pvt_lock(i);
  6675. ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
  6676. /* Don't use ast_set_callerid() here because it will
  6677. * generate an unnecessary NewCallerID event */
  6678. if (!ast_strlen_zero(i->cid_num)) {
  6679. tmp->caller.ani.number.valid = 1;
  6680. tmp->caller.ani.number.str = ast_strdup(i->cid_num);
  6681. }
  6682. if (!ast_strlen_zero(i->rdnis)) {
  6683. tmp->redirecting.from.number.valid = 1;
  6684. tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
  6685. }
  6686. if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
  6687. tmp->dialed.number.str = ast_strdup(i->exten);
  6688. }
  6689. tmp->priority = 1;
  6690. if (!ast_strlen_zero(i->uri))
  6691. pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
  6692. if (!ast_strlen_zero(i->domain))
  6693. pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
  6694. if (!ast_strlen_zero(i->callid))
  6695. pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
  6696. if (i->rtp)
  6697. ast_jb_configure(tmp, &global_jbconf);
  6698. if (!i->relatedpeer) {
  6699. tmp->flags |= AST_FLAG_DISABLE_DEVSTATE_CACHE;
  6700. }
  6701. /* Set channel variables for this call from configuration */
  6702. for (v = i->chanvars ; v ; v = v->next) {
  6703. char valuebuf[1024];
  6704. pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
  6705. }
  6706. if (i->do_history)
  6707. append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
  6708. /* Inform manager user about new channel and their SIP call ID */
  6709. if (sip_cfg.callevents)
  6710. manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
  6711. "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
  6712. tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
  6713. return tmp;
  6714. }
  6715. /*! \brief Reads one line of SIP message body */
  6716. static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
  6717. {
  6718. if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
  6719. return ast_skip_blanks(line + nameLen + 1);
  6720. return "";
  6721. }
  6722. /*! \brief Lookup 'name' in the SDP starting
  6723. * at the 'start' line. Returns the matching line, and 'start'
  6724. * is updated with the next line number.
  6725. */
  6726. static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
  6727. {
  6728. int len = strlen(name);
  6729. while (*start < (req->sdp_start + req->sdp_count)) {
  6730. const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
  6731. if (r[0] != '\0')
  6732. return r;
  6733. }
  6734. /* if the line was not found, ensure that *start points past the SDP */
  6735. (*start)++;
  6736. return "";
  6737. }
  6738. /*! \brief Fetches the next valid SDP line between the 'start' line
  6739. * (inclusive) and the 'stop' line (exclusive). Returns the type
  6740. * ('a', 'c', ...) and matching line in reference 'start' is updated
  6741. * with the next line number.
  6742. */
  6743. static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
  6744. {
  6745. char type = '\0';
  6746. const char *line = NULL;
  6747. if (stop > (req->sdp_start + req->sdp_count)) {
  6748. stop = req->sdp_start + req->sdp_count;
  6749. }
  6750. while (*start < stop) {
  6751. line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
  6752. if (line[1] == '=') {
  6753. type = line[0];
  6754. *value = ast_skip_blanks(line + 2);
  6755. break;
  6756. }
  6757. }
  6758. return type;
  6759. }
  6760. /*! \brief Get a specific line from the message body */
  6761. static char *get_body(struct sip_request *req, char *name, char delimiter)
  6762. {
  6763. int x;
  6764. int len = strlen(name);
  6765. char *r;
  6766. for (x = 0; x < req->lines; x++) {
  6767. r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
  6768. if (r[0] != '\0')
  6769. return r;
  6770. }
  6771. return "";
  6772. }
  6773. /*! \brief Find compressed SIP alias */
  6774. static const char *find_alias(const char *name, const char *_default)
  6775. {
  6776. /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
  6777. static const struct cfalias {
  6778. char * const fullname;
  6779. char * const shortname;
  6780. } aliases[] = {
  6781. { "Content-Type", "c" },
  6782. { "Content-Encoding", "e" },
  6783. { "From", "f" },
  6784. { "Call-ID", "i" },
  6785. { "Contact", "m" },
  6786. { "Content-Length", "l" },
  6787. { "Subject", "s" },
  6788. { "To", "t" },
  6789. { "Supported", "k" },
  6790. { "Refer-To", "r" },
  6791. { "Referred-By", "b" },
  6792. { "Allow-Events", "u" },
  6793. { "Event", "o" },
  6794. { "Via", "v" },
  6795. { "Accept-Contact", "a" },
  6796. { "Reject-Contact", "j" },
  6797. { "Request-Disposition", "d" },
  6798. { "Session-Expires", "x" },
  6799. { "Identity", "y" },
  6800. { "Identity-Info", "n" },
  6801. };
  6802. int x;
  6803. for (x = 0; x < ARRAY_LEN(aliases); x++) {
  6804. if (!strcasecmp(aliases[x].fullname, name))
  6805. return aliases[x].shortname;
  6806. }
  6807. return _default;
  6808. }
  6809. static const char *__get_header(const struct sip_request *req, const char *name, int *start)
  6810. {
  6811. /*
  6812. * Technically you can place arbitrary whitespace both before and after the ':' in
  6813. * a header, although RFC3261 clearly says you shouldn't before, and place just
  6814. * one afterwards. If you shouldn't do it, what absolute idiot decided it was
  6815. * a good idea to say you can do it, and if you can do it, why in the hell would.
  6816. * you say you shouldn't.
  6817. * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
  6818. * and we always allow spaces after that for compatibility.
  6819. */
  6820. const char *sname = find_alias(name, NULL);
  6821. int x, len = strlen(name), slen = (sname ? 1 : 0);
  6822. for (x = *start; x < req->headers; x++) {
  6823. const char *header = REQ_OFFSET_TO_STR(req, header[x]);
  6824. int smatch = 0, match = !strncasecmp(header, name, len);
  6825. if (slen) {
  6826. smatch = !strncasecmp(header, sname, slen);
  6827. }
  6828. if (match || smatch) {
  6829. /* skip name */
  6830. const char *r = header + (match ? len : slen );
  6831. if (sip_cfg.pedanticsipchecking) {
  6832. r = ast_skip_blanks(r);
  6833. }
  6834. if (*r == ':') {
  6835. *start = x+1;
  6836. return ast_skip_blanks(r+1);
  6837. }
  6838. }
  6839. }
  6840. /* Don't return NULL, so get_header is always a valid pointer */
  6841. return "";
  6842. }
  6843. /*! \brief Get header from SIP request
  6844. \return Always return something, so don't check for NULL because it won't happen :-)
  6845. */
  6846. static const char *get_header(const struct sip_request *req, const char *name)
  6847. {
  6848. int start = 0;
  6849. return __get_header(req, name, &start);
  6850. }
  6851. /*! \brief Read RTP from network */
  6852. static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
  6853. {
  6854. /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
  6855. struct ast_frame *f;
  6856. if (!p->rtp) {
  6857. /* We have no RTP allocated for this channel */
  6858. return &ast_null_frame;
  6859. }
  6860. switch(ast->fdno) {
  6861. case 0:
  6862. f = ast_rtp_instance_read(p->rtp, 0); /* RTP Audio */
  6863. break;
  6864. case 1:
  6865. f = ast_rtp_instance_read(p->rtp, 1); /* RTCP Control Channel */
  6866. break;
  6867. case 2:
  6868. f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
  6869. break;
  6870. case 3:
  6871. f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
  6872. break;
  6873. case 4:
  6874. f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
  6875. if (sipdebug_text) {
  6876. int i;
  6877. unsigned char* arr = f->data.ptr;
  6878. for (i=0; i < f->datalen; i++)
  6879. ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
  6880. ast_verbose(" -> ");
  6881. for (i=0; i < f->datalen; i++)
  6882. ast_verbose("%02X ", (unsigned)arr[i]);
  6883. ast_verbose("\n");
  6884. }
  6885. break;
  6886. case 5:
  6887. f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
  6888. break;
  6889. default:
  6890. f = &ast_null_frame;
  6891. }
  6892. /* Don't forward RFC2833 if we're not supposed to */
  6893. if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
  6894. (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
  6895. ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
  6896. ast_frfree(f);
  6897. return &ast_null_frame;
  6898. }
  6899. /* We already hold the channel lock */
  6900. if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
  6901. return f;
  6902. if (f && f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
  6903. if (!(f->subclass.codec & p->jointcapability)) {
  6904. ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
  6905. ast_getformatname(f->subclass.codec), p->owner->name);
  6906. ast_frfree(f);
  6907. return &ast_null_frame;
  6908. }
  6909. ast_debug(1, "Oooh, format changed to %s\n",
  6910. ast_getformatname(f->subclass.codec));
  6911. p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass.codec;
  6912. ast_set_read_format(p->owner, p->owner->readformat);
  6913. ast_set_write_format(p->owner, p->owner->writeformat);
  6914. }
  6915. if (f && p->dsp) {
  6916. f = ast_dsp_process(p->owner, p->dsp, f);
  6917. if (f && f->frametype == AST_FRAME_DTMF) {
  6918. if (f->subclass.integer == 'f') {
  6919. ast_debug(1, "Fax CNG detected on %s\n", ast->name);
  6920. *faxdetect = 1;
  6921. /* If we only needed this DSP for fax detection purposes we can just drop it now */
  6922. if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
  6923. ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
  6924. } else {
  6925. ast_dsp_free(p->dsp);
  6926. p->dsp = NULL;
  6927. }
  6928. } else {
  6929. ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
  6930. }
  6931. }
  6932. }
  6933. return f;
  6934. }
  6935. /*! \brief Read SIP RTP from channel */
  6936. static struct ast_frame *sip_read(struct ast_channel *ast)
  6937. {
  6938. struct ast_frame *fr;
  6939. struct sip_pvt *p = ast->tech_pvt;
  6940. int faxdetected = FALSE;
  6941. sip_pvt_lock(p);
  6942. fr = sip_rtp_read(ast, p, &faxdetected);
  6943. p->lastrtprx = time(NULL);
  6944. /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
  6945. if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
  6946. if (strcmp(ast->exten, "fax")) {
  6947. const char *target_context = S_OR(ast->macrocontext, ast->context);
  6948. /* We need to unlock 'ast' here because
  6949. * ast_exists_extension has the potential to start and
  6950. * stop an autoservice on the channel. Such action is
  6951. * prone to deadlock if the channel is locked.
  6952. */
  6953. sip_pvt_unlock(p);
  6954. ast_channel_unlock(ast);
  6955. if (ast_exists_extension(ast, target_context, "fax", 1,
  6956. S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
  6957. ast_channel_lock(ast);
  6958. sip_pvt_lock(p);
  6959. ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
  6960. pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
  6961. if (ast_async_goto(ast, target_context, "fax", 1)) {
  6962. ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
  6963. }
  6964. ast_frfree(fr);
  6965. fr = &ast_null_frame;
  6966. } else {
  6967. ast_channel_lock(ast);
  6968. sip_pvt_lock(p);
  6969. ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
  6970. }
  6971. }
  6972. }
  6973. /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
  6974. if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
  6975. ast_frfree(fr);
  6976. fr = &ast_null_frame;
  6977. }
  6978. sip_pvt_unlock(p);
  6979. return fr;
  6980. }
  6981. /*! \brief Generate 32 byte random string for callid's etc */
  6982. static char *generate_random_string(char *buf, size_t size)
  6983. {
  6984. long val[4];
  6985. int x;
  6986. for (x=0; x<4; x++)
  6987. val[x] = ast_random();
  6988. snprintf(buf, size, "%08lx%08lx%08lx%08lx", (unsigned long)val[0], (unsigned long)val[1], (unsigned long)val[2], (unsigned long)val[3]);
  6989. return buf;
  6990. }
  6991. static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
  6992. {
  6993. struct ast_str *uri = ast_str_alloca(size);
  6994. ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
  6995. /* Here would be a great place to generate a UUID, but for now we'll
  6996. * use the handy random string generation function we already have
  6997. */
  6998. ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
  6999. ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
  7000. ast_copy_string(buf, ast_str_buffer(uri), size);
  7001. return buf;
  7002. }
  7003. /*!
  7004. * \brief Build SIP Call-ID value for a non-REGISTER transaction
  7005. *
  7006. * \note The passed in pvt must not be in a dialogs container
  7007. * since this function changes the hash key used by the
  7008. * container.
  7009. */
  7010. static void build_callid_pvt(struct sip_pvt *pvt)
  7011. {
  7012. char buf[33];
  7013. const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
  7014. ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
  7015. }
  7016. /*! \brief Unlink the given object from the container and return TRUE if it was in the container. */
  7017. #define CONTAINER_UNLINK(container, obj, tag) \
  7018. ({ \
  7019. int found = 0; \
  7020. typeof((obj)) __removed_obj; \
  7021. __removed_obj = ao2_t_callback((container), \
  7022. OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag)); \
  7023. if (__removed_obj) { \
  7024. ao2_ref(__removed_obj, -1); \
  7025. found = 1; \
  7026. } \
  7027. found; \
  7028. })
  7029. /*!
  7030. * \internal
  7031. * \brief Safely change the callid of the given SIP dialog.
  7032. *
  7033. * \param pvt SIP private structure to change callid
  7034. * \param callid Specified new callid to use. NULL if generate new callid.
  7035. *
  7036. * \return Nothing
  7037. */
  7038. static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
  7039. {
  7040. int in_dialog_container;
  7041. char *oldid = ast_strdupa(pvt->callid);
  7042. ao2_lock(dialogs);
  7043. in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
  7044. "About to change the callid -- remove the old name");
  7045. if (callid) {
  7046. ast_string_field_set(pvt, callid, callid);
  7047. } else {
  7048. build_callid_pvt(pvt);
  7049. }
  7050. if (in_dialog_container) {
  7051. ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
  7052. }
  7053. ao2_unlock(dialogs);
  7054. if (strcmp(oldid, pvt->callid)) {
  7055. ast_debug(1, "SIP call-id changed from '%s' to '%s'\n", oldid, pvt->callid);
  7056. }
  7057. }
  7058. /*! \brief Build SIP Call-ID value for a REGISTER transaction */
  7059. static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
  7060. {
  7061. char buf[33];
  7062. const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
  7063. ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
  7064. }
  7065. /*! \brief Build SIP From tag value for REGISTER */
  7066. static void build_localtag_registry(struct sip_registry *reg)
  7067. {
  7068. ast_string_field_build(reg, localtag, "as%08lx", (unsigned long)ast_random());
  7069. }
  7070. /*! \brief Make our SIP dialog tag */
  7071. static void make_our_tag(struct sip_pvt *pvt)
  7072. {
  7073. ast_string_field_build(pvt, tag, "as%08lx", (unsigned long)ast_random());
  7074. }
  7075. /*! \brief Allocate Session-Timers struct w/in dialog */
  7076. static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
  7077. {
  7078. struct sip_st_dlg *stp;
  7079. if (p->stimer) {
  7080. ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
  7081. return p->stimer;
  7082. }
  7083. if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
  7084. return NULL;
  7085. p->stimer = stp;
  7086. stp->st_schedid = -1; /* Session-Timers ast_sched scheduler id */
  7087. return p->stimer;
  7088. }
  7089. /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
  7090. * Returns a reference to the object so whoever uses it later must
  7091. * remember to release the reference.
  7092. */
  7093. struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
  7094. int useglobal_nat, const int intended_method, struct sip_request *req)
  7095. {
  7096. struct sip_pvt *p;
  7097. if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
  7098. return NULL;
  7099. if (ast_string_field_init(p, 512)) {
  7100. ao2_t_ref(p, -1, "failed to string_field_init, drop p");
  7101. return NULL;
  7102. }
  7103. if (!(p->cc_params = ast_cc_config_params_init())) {
  7104. ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
  7105. return NULL;
  7106. }
  7107. /* If this dialog is created as the result of an incoming Request. Lets store
  7108. * some information about that request */
  7109. if (req) {
  7110. struct sip_via *via;
  7111. const char *cseq = get_header(req, "Cseq");
  7112. uint32_t seqno;
  7113. /* get branch parameter from initial Request that started this dialog */
  7114. via = parse_via(get_header(req, "Via"));
  7115. if (via) {
  7116. /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
  7117. * it is not useful to us to have it */
  7118. if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
  7119. ast_string_field_set(p, initviabranch, via->branch);
  7120. ast_string_field_set(p, initviasentby, via->sent_by);
  7121. }
  7122. free_via(via);
  7123. }
  7124. /* Store initial incoming cseq. An error in sscanf here is ignored. There is no approperiate
  7125. * except not storing the number. CSeq validation must take place before dialog creation in find_call */
  7126. if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
  7127. p->init_icseq = seqno;
  7128. }
  7129. /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
  7130. set_socket_transport(&p->socket, req->socket.type);
  7131. } else {
  7132. set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
  7133. }
  7134. p->socket.fd = -1;
  7135. p->method = intended_method;
  7136. p->initid = -1;
  7137. p->waitid = -1;
  7138. p->reinviteid = -1;
  7139. p->autokillid = -1;
  7140. p->request_queue_sched_id = -1;
  7141. p->provisional_keepalive_sched_id = -1;
  7142. p->t38id = -1;
  7143. p->subscribed = NONE;
  7144. p->stateid = -1;
  7145. p->sessionversion_remote = -1;
  7146. p->session_modify = TRUE;
  7147. p->stimer = NULL;
  7148. p->prefs = default_prefs; /* Set default codecs for this call */
  7149. p->maxforwards = sip_cfg.default_max_forwards;
  7150. if (intended_method != SIP_OPTIONS) { /* Peerpoke has it's own system */
  7151. p->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
  7152. p->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
  7153. }
  7154. if (!addr) {
  7155. p->ourip = internip;
  7156. } else {
  7157. ast_sockaddr_copy(&p->sa, addr);
  7158. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  7159. }
  7160. /* Copy global flags to this PVT at setup. */
  7161. ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
  7162. ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  7163. ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  7164. p->do_history = recordhistory;
  7165. p->branch = ast_random();
  7166. make_our_tag(p);
  7167. p->ocseq = INITIAL_CSEQ;
  7168. p->allowed_methods = UINT_MAX;
  7169. if (sip_methods[intended_method].need_rtp) {
  7170. p->maxcallbitrate = default_maxcallbitrate;
  7171. p->autoframing = global_autoframing;
  7172. }
  7173. if (useglobal_nat && addr) {
  7174. /* Setup NAT structure according to global settings if we have an address */
  7175. ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
  7176. ast_sockaddr_copy(&p->recv, addr);
  7177. do_setnat(p);
  7178. }
  7179. if (p->method != SIP_REGISTER) {
  7180. ast_string_field_set(p, fromdomain, default_fromdomain);
  7181. p->fromdomainport = default_fromdomainport;
  7182. }
  7183. build_via(p);
  7184. if (!callid)
  7185. build_callid_pvt(p);
  7186. else
  7187. ast_string_field_set(p, callid, callid);
  7188. /* Assign default music on hold class */
  7189. ast_string_field_set(p, mohinterpret, default_mohinterpret);
  7190. ast_string_field_set(p, mohsuggest, default_mohsuggest);
  7191. p->capability = sip_cfg.capability;
  7192. p->allowtransfer = sip_cfg.allowtransfer;
  7193. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
  7194. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  7195. p->noncodeccapability |= AST_RTP_DTMF;
  7196. }
  7197. ast_string_field_set(p, context, sip_cfg.default_context);
  7198. ast_string_field_set(p, parkinglot, default_parkinglot);
  7199. ast_string_field_set(p, engine, default_engine);
  7200. AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
  7201. /* Add to active dialog list */
  7202. ao2_t_link(dialogs, p, "link pvt into dialogs table");
  7203. 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");
  7204. return p;
  7205. }
  7206. /*!
  7207. * \brief Check if an ip is an multicast IP.
  7208. * \parm addr the address to check
  7209. *
  7210. * This function checks if an address is in the 224.0.0.0/4 network block.
  7211. * \return non-zero if this is a multicast address
  7212. */
  7213. static int addr_is_multicast(const struct ast_sockaddr *addr)
  7214. {
  7215. return ((ast_sockaddr_ipv4(addr) & 0xf0000000) == 0xe0000000);
  7216. }
  7217. /*!
  7218. * \brief Process the Via header according to RFC 3261 section 18.2.2.
  7219. * \param p a sip_pvt structure that will be modified according to the received
  7220. * header
  7221. * \param req a sip request with a Via header to process
  7222. *
  7223. * This function will update the destination of the response according to the
  7224. * Via header in the request and RFC 3261 section 18.2.2. We do not have a
  7225. * transport layer so we ignore certain values like the 'received' param (we
  7226. * set the destination address to the addres the request came from in the
  7227. * respprep() function).
  7228. *
  7229. * \retval -1 error
  7230. * \retval 0 success
  7231. */
  7232. static int process_via(struct sip_pvt *p, const struct sip_request *req)
  7233. {
  7234. struct sip_via *via = parse_via(get_header(req, "Via"));
  7235. if (!via) {
  7236. ast_log(LOG_ERROR, "error processing via header\n");
  7237. return -1;
  7238. }
  7239. if (via->maddr) {
  7240. if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
  7241. ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
  7242. ast_log(LOG_ERROR, "error processing via header\n");
  7243. free_via(via);
  7244. return -1;
  7245. }
  7246. if (addr_is_multicast(&p->sa)) {
  7247. setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
  7248. }
  7249. }
  7250. ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
  7251. free_via(via);
  7252. return 0;
  7253. }
  7254. /* \brief arguments used for Request/Response to matching */
  7255. struct match_req_args {
  7256. int method;
  7257. const char *callid;
  7258. const char *totag;
  7259. const char *fromtag;
  7260. uint32_t seqno;
  7261. /* Set if the method is a Request */
  7262. const char *ruri;
  7263. const char *viabranch;
  7264. const char *viasentby;
  7265. /* Set this if the Authentication header is present in the Request. */
  7266. int authentication_present;
  7267. };
  7268. enum match_req_res {
  7269. SIP_REQ_MATCH,
  7270. SIP_REQ_NOT_MATCH,
  7271. SIP_REQ_LOOP_DETECTED,
  7272. };
  7273. /*
  7274. * \brief Match a incoming Request/Response to a dialog
  7275. *
  7276. * \retval enum match_req_res indicating if the dialog matches the arg
  7277. */
  7278. static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
  7279. {
  7280. const char *init_ruri = NULL;
  7281. if (sip_pvt_ptr->initreq.headers) {
  7282. init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
  7283. }
  7284. /*
  7285. * Match Tags and call-id to Dialog
  7286. */
  7287. if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
  7288. /* call-id does not match. */
  7289. return SIP_REQ_NOT_MATCH;
  7290. }
  7291. if (arg->method == SIP_RESPONSE) {
  7292. /* Verify totag if we have one stored for this dialog, but never be strict about this for
  7293. * a response until the dialog is established */
  7294. if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  7295. if (ast_strlen_zero(arg->totag)) {
  7296. /* missing totag when they already gave us one earlier */
  7297. return SIP_REQ_NOT_MATCH;
  7298. }
  7299. if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
  7300. /* The totag of the response does not match the one we have stored */
  7301. return SIP_REQ_NOT_MATCH;
  7302. }
  7303. }
  7304. /* Verify fromtag of response matches the tag we gave them. */
  7305. if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
  7306. /* fromtag from response does not match our tag */
  7307. return SIP_REQ_NOT_MATCH;
  7308. }
  7309. } else {
  7310. /* Verify the fromtag of Request matches the tag they provided earlier.
  7311. * If this is a Request with authentication credentials, forget their old
  7312. * tag as it is not valid after the 401 or 407 response. */
  7313. if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
  7314. /* their tag does not match the one was have stored for them */
  7315. return SIP_REQ_NOT_MATCH;
  7316. }
  7317. /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
  7318. if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
  7319. /* totag from Request does not match our tag */
  7320. return SIP_REQ_NOT_MATCH;
  7321. }
  7322. }
  7323. /*
  7324. * Compare incoming request against initial transaction.
  7325. *
  7326. * This is a best effort attempt at distinguishing forked requests from
  7327. * our initial transaction. If all the elements are NOT in place to evaluate
  7328. * this, this block is ignored and the dialog match is made regardless.
  7329. * Once the totag is established after the dialog is confirmed, this is not necessary.
  7330. *
  7331. * CRITERIA required for initial transaction matching.
  7332. *
  7333. * 1. Is a Request
  7334. * 2. Callid and theirtag match (this is done in the dialog matching block)
  7335. * 3. totag is NOT present
  7336. * 4. CSeq matchs our initial transaction's cseq number
  7337. * 5. pvt has init via branch parameter stored
  7338. */
  7339. if ((arg->method != SIP_RESPONSE) && /* must be a Request */
  7340. ast_strlen_zero(arg->totag) && /* must not have a totag */
  7341. (sip_pvt_ptr->init_icseq == arg->seqno) && /* the cseq must be the same as this dialogs initial cseq */
  7342. !ast_strlen_zero(sip_pvt_ptr->initviabranch) && /* The dialog must have started with a RFC3261 compliant branch tag */
  7343. init_ruri) { /* the dialog must have an initial request uri associated with it */
  7344. /* This Request matches all the criteria required for Loop/Merge detection.
  7345. * Now we must go down the path of comparing VIA's and RURIs. */
  7346. if (ast_strlen_zero(arg->viabranch) ||
  7347. strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
  7348. ast_strlen_zero(arg->viasentby) ||
  7349. strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
  7350. /* At this point, this request does not match this Dialog.*/
  7351. /* if methods are different this is just a mismatch */
  7352. if ((sip_pvt_ptr->method != arg->method)) {
  7353. return SIP_REQ_NOT_MATCH;
  7354. }
  7355. /* If RUIs are different, this is a forked request to a separate URI.
  7356. * Returning a mismatch allows this Request to be processed separately. */
  7357. if (sip_uri_cmp(init_ruri, arg->ruri)) {
  7358. /* not a match, request uris are different */
  7359. return SIP_REQ_NOT_MATCH;
  7360. }
  7361. /* Loop/Merge Detected
  7362. *
  7363. * ---Current Matches to Initial Request---
  7364. * request uri
  7365. * Call-id
  7366. * their-tag
  7367. * no totag present
  7368. * method
  7369. * cseq
  7370. *
  7371. * --- Does not Match Initial Request ---
  7372. * Top Via
  7373. *
  7374. * Without the same Via, this can not match our initial transaction for this dialog,
  7375. * but given that this Request matches everything else associated with that initial
  7376. * Request this is most certainly a Forked request in which we have already received
  7377. * part of the fork.
  7378. */
  7379. return SIP_REQ_LOOP_DETECTED;
  7380. }
  7381. } /* end of Request Via check */
  7382. /* Match Authentication Request.
  7383. *
  7384. * A Request with an Authentication header must come back with the
  7385. * same Request URI. Otherwise it is not a match.
  7386. */
  7387. if ((arg->method != SIP_RESPONSE) && /* Must be a Request type to even begin checking this */
  7388. ast_strlen_zero(arg->totag) && /* no totag is present to match */
  7389. arg->authentication_present && /* Authentication header is present in Request */
  7390. sip_uri_cmp(init_ruri, arg->ruri)) { /* Compare the Request URI of both the last Request and this new one */
  7391. /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
  7392. return SIP_REQ_NOT_MATCH;
  7393. }
  7394. return SIP_REQ_MATCH;
  7395. }
  7396. /*! \internal
  7397. *
  7398. * \brief Locks both pvt and pvt owner if owner is present.
  7399. *
  7400. * \note This function gives a ref to pvt->owner if it is present and locked.
  7401. * This reference must be decremented after pvt->owner is unlocked.
  7402. *
  7403. * \note This function will never give you up,
  7404. * \note This function will never let you down.
  7405. * \note This function will run around and desert you.
  7406. *
  7407. * \pre pvt is not locked
  7408. * \post pvt is locked
  7409. * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
  7410. *
  7411. * \returns a pointer to the locked and reffed pvt->owner channel if it exists.
  7412. */
  7413. static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
  7414. {
  7415. struct ast_channel *chan;
  7416. /* Locking is simple when it is done right. If you see a deadlock resulting
  7417. * in this function, it is not this function's fault, Your problem exists elsewhere.
  7418. * This function is perfect... seriously. */
  7419. for (;;) {
  7420. /* First, get the channel and grab a reference to it */
  7421. sip_pvt_lock(pvt);
  7422. chan = pvt->owner;
  7423. if (chan) {
  7424. /* The channel can not go away while we hold the pvt lock.
  7425. * Give the channel a ref so it will not go away after we let
  7426. * the pvt lock go. */
  7427. ast_channel_ref(chan);
  7428. } else {
  7429. /* no channel, return pvt locked */
  7430. return NULL;
  7431. }
  7432. /* We had to hold the pvt lock while getting a ref to the owner channel
  7433. * but now we have to let this lock go in order to preserve proper
  7434. * locking order when grabbing the channel lock */
  7435. sip_pvt_unlock(pvt);
  7436. /* Look, no deadlock avoidance, hooray! */
  7437. ast_channel_lock(chan);
  7438. sip_pvt_lock(pvt);
  7439. if (pvt->owner == chan) {
  7440. /* done */
  7441. break;
  7442. }
  7443. /* If the owner changed while everything was unlocked, no problem,
  7444. * just start over and everthing will work. This is rare, do not be
  7445. * confused by this loop and think this it is an expensive operation.
  7446. * The majority of the calls to this function will never involve multiple
  7447. * executions of this loop. */
  7448. ast_channel_unlock(chan);
  7449. ast_channel_unref(chan);
  7450. sip_pvt_unlock(pvt);
  7451. }
  7452. /* If owner exists, it is locked and reffed */
  7453. return pvt->owner;
  7454. }
  7455. /*! \brief find or create a dialog structure for an incoming SIP message.
  7456. * Connect incoming SIP message to current dialog or create new dialog structure
  7457. * Returns a reference to the sip_pvt object, remember to give it back once done.
  7458. * Called by handle_request_do
  7459. */
  7460. static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
  7461. {
  7462. char totag[128];
  7463. char fromtag[128];
  7464. const char *callid = get_header(req, "Call-ID");
  7465. const char *from = get_header(req, "From");
  7466. const char *to = get_header(req, "To");
  7467. const char *cseq = get_header(req, "Cseq");
  7468. struct sip_pvt *sip_pvt_ptr;
  7469. uint32_t seqno;
  7470. /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
  7471. /* get_header always returns non-NULL so we must use ast_strlen_zero() */
  7472. if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
  7473. ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
  7474. (sscanf(cseq, "%30u", &seqno) != 1)) {
  7475. /* RFC 3261 section 24.4.1. Send a 400 Bad Request if the request is malformed. */
  7476. if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
  7477. transmit_response_using_temp(callid, addr, 1, intended_method,
  7478. req, "400 Bad Request");
  7479. }
  7480. return NULL; /* Invalid packet */
  7481. }
  7482. if (sip_cfg.pedanticsipchecking) {
  7483. /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
  7484. we need more to identify a branch - so we have to check branch, from
  7485. and to tags to identify a call leg.
  7486. For Asterisk to behave correctly, you need to turn on pedanticsipchecking
  7487. in sip.conf
  7488. */
  7489. if (gettag(req, "To", totag, sizeof(totag)))
  7490. req->has_to_tag = 1; /* Used in handle_request/response */
  7491. gettag(req, "From", fromtag, sizeof(fromtag));
  7492. 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);
  7493. /* All messages must always have From: tag */
  7494. if (ast_strlen_zero(fromtag)) {
  7495. ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
  7496. return NULL;
  7497. }
  7498. /* reject requests that must always have a To: tag */
  7499. if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
  7500. ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
  7501. return NULL;
  7502. }
  7503. }
  7504. if (!sip_cfg.pedanticsipchecking) {
  7505. struct sip_pvt tmp_dialog = {
  7506. .callid = callid,
  7507. };
  7508. sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
  7509. if (sip_pvt_ptr) { /* well, if we don't find it-- what IS in there? */
  7510. /* Found the call */
  7511. return sip_pvt_ptr;
  7512. }
  7513. } else { /* in pedantic mode! -- do the fancy search */
  7514. struct sip_pvt tmp_dialog = {
  7515. .callid = callid,
  7516. };
  7517. struct match_req_args args = { 0, };
  7518. int found;
  7519. struct ao2_iterator *iterator = ao2_t_callback(dialogs,
  7520. OBJ_POINTER | OBJ_MULTIPLE,
  7521. dialog_find_multiple,
  7522. &tmp_dialog,
  7523. "pedantic ao2_find in dialogs");
  7524. struct sip_via *via = NULL;
  7525. args.method = req->method;
  7526. args.callid = NULL; /* we already matched this. */
  7527. args.totag = totag;
  7528. args.fromtag = fromtag;
  7529. args.seqno = seqno;
  7530. /* If this is a Request, set the Via and Authorization header arguments */
  7531. if (req->method != SIP_RESPONSE) {
  7532. args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
  7533. via = parse_via(get_header(req, "Via"));
  7534. if (via) {
  7535. args.viasentby = via->sent_by;
  7536. args.viabranch = via->branch;
  7537. }
  7538. if (!ast_strlen_zero(get_header(req, "Authorization")) ||
  7539. !ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
  7540. args.authentication_present = 1;
  7541. }
  7542. }
  7543. /* Iterate a list of dialogs already matched by Call-id */
  7544. while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
  7545. sip_pvt_lock(sip_pvt_ptr);
  7546. found = match_req_to_dialog(sip_pvt_ptr, &args);
  7547. sip_pvt_unlock(sip_pvt_ptr);
  7548. switch (found) {
  7549. case SIP_REQ_MATCH:
  7550. ao2_iterator_destroy(iterator);
  7551. free_via(via);
  7552. return sip_pvt_ptr; /* return pvt with ref */
  7553. case SIP_REQ_LOOP_DETECTED:
  7554. /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
  7555. * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
  7556. transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
  7557. dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
  7558. ao2_iterator_destroy(iterator);
  7559. free_via(via);
  7560. return NULL;
  7561. case SIP_REQ_NOT_MATCH:
  7562. default:
  7563. dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
  7564. break;
  7565. }
  7566. }
  7567. if (iterator) {
  7568. ao2_iterator_destroy(iterator);
  7569. }
  7570. free_via(via);
  7571. } /* end of pedantic mode Request/Reponse to Dialog matching */
  7572. /* See if the method is capable of creating a dialog */
  7573. if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
  7574. struct sip_pvt *p = NULL;
  7575. if (intended_method == SIP_REFER) {
  7576. /* We do support REFER, but not outside of a dialog yet */
  7577. transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
  7578. /* Ok, time to create a new SIP dialog object, a pvt */
  7579. } else if (!(p = sip_alloc(callid, addr, 1, intended_method, req))) {
  7580. /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
  7581. getting a dialog from sip_alloc.
  7582. Without a dialog we can't retransmit and handle ACKs and all that, but at least
  7583. send an error message.
  7584. Sorry, we apologize for the inconvienience
  7585. */
  7586. transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
  7587. ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
  7588. }
  7589. return p; /* can be NULL */
  7590. } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
  7591. /* A method we do not support, let's take it on the volley */
  7592. transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
  7593. ast_debug(2, "Got a request with unsupported SIP method.\n");
  7594. } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
  7595. /* This is a request outside of a dialog that we don't know about */
  7596. transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
  7597. ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
  7598. }
  7599. /* We do not respond to responses for dialogs that we don't know about, we just drop
  7600. the session quickly */
  7601. if (intended_method == SIP_RESPONSE)
  7602. ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
  7603. return NULL;
  7604. }
  7605. /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
  7606. static int sip_register(const char *value, int lineno)
  7607. {
  7608. struct sip_registry *reg;
  7609. if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
  7610. ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
  7611. return -1;
  7612. }
  7613. ast_atomic_fetchadd_int(&regobjs, 1);
  7614. ASTOBJ_INIT(reg);
  7615. if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
  7616. registry_unref(reg, "failure to parse, unref the reg pointer");
  7617. return -1;
  7618. }
  7619. /* set default expiry if necessary */
  7620. if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
  7621. reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
  7622. }
  7623. /* Add the new registry entry to the list */
  7624. ASTOBJ_CONTAINER_LINK(&regl, reg);
  7625. /* release the reference given by ASTOBJ_INIT. The container has another reference */
  7626. registry_unref(reg, "unref the reg pointer");
  7627. return 0;
  7628. }
  7629. /*! \brief Parse mwi=> line in sip.conf and add to list */
  7630. static int sip_subscribe_mwi(const char *value, int lineno)
  7631. {
  7632. struct sip_subscription_mwi *mwi;
  7633. int portnum = 0;
  7634. enum sip_transport transport = SIP_TRANSPORT_UDP;
  7635. char buf[256] = "";
  7636. char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
  7637. if (!value) {
  7638. return -1;
  7639. }
  7640. ast_copy_string(buf, value, sizeof(buf));
  7641. username = buf;
  7642. if ((hostname = strrchr(buf, '@'))) {
  7643. *hostname++ = '\0';
  7644. } else {
  7645. return -1;
  7646. }
  7647. if ((secret = strchr(username, ':'))) {
  7648. *secret++ = '\0';
  7649. if ((authuser = strchr(secret, ':'))) {
  7650. *authuser++ = '\0';
  7651. }
  7652. }
  7653. if ((mailbox = strchr(hostname, '/'))) {
  7654. *mailbox++ = '\0';
  7655. }
  7656. if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
  7657. ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
  7658. return -1;
  7659. }
  7660. if ((porta = strchr(hostname, ':'))) {
  7661. *porta++ = '\0';
  7662. if (!(portnum = atoi(porta))) {
  7663. ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
  7664. return -1;
  7665. }
  7666. }
  7667. if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
  7668. return -1;
  7669. }
  7670. ASTOBJ_INIT(mwi);
  7671. ast_string_field_set(mwi, username, username);
  7672. if (secret) {
  7673. ast_string_field_set(mwi, secret, secret);
  7674. }
  7675. if (authuser) {
  7676. ast_string_field_set(mwi, authuser, authuser);
  7677. }
  7678. ast_string_field_set(mwi, hostname, hostname);
  7679. ast_string_field_set(mwi, mailbox, mailbox);
  7680. mwi->resub = -1;
  7681. mwi->portno = portnum;
  7682. mwi->transport = transport;
  7683. ASTOBJ_CONTAINER_LINK(&submwil, mwi);
  7684. ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
  7685. return 0;
  7686. }
  7687. static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
  7688. {
  7689. (*allowed_methods) |= (1 << method);
  7690. }
  7691. static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
  7692. {
  7693. (*allowed_methods) &= ~(1 << method);
  7694. }
  7695. /*! \brief Check if method is allowed for a device or a dialog */
  7696. static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
  7697. {
  7698. return ((*allowed_methods) >> method) & 1;
  7699. }
  7700. static void mark_parsed_methods(unsigned int *methods, char *methods_str)
  7701. {
  7702. char *method;
  7703. for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
  7704. int id = find_sip_method(ast_skip_blanks(method));
  7705. if (id == SIP_UNKNOWN) {
  7706. continue;
  7707. }
  7708. mark_method_allowed(methods, id);
  7709. }
  7710. }
  7711. /*!
  7712. * \brief parse the Allow header to see what methods the endpoint we
  7713. * are communicating with allows.
  7714. *
  7715. * We parse the allow header on incoming Registrations and save the
  7716. * result to the SIP peer that is registering. When the registration
  7717. * expires, we clear what we know about the peer's allowed methods.
  7718. * When the peer re-registers, we once again parse to see if the
  7719. * list of allowed methods has changed.
  7720. *
  7721. * For peers that do not register, we parse the first message we receive
  7722. * during a call to see what is allowed, and save the information
  7723. * for the duration of the call.
  7724. * \param req The SIP request we are parsing
  7725. * \retval The methods allowed
  7726. */
  7727. static unsigned int parse_allowed_methods(struct sip_request *req)
  7728. {
  7729. char *allow = ast_strdupa(get_header(req, "Allow"));
  7730. unsigned int allowed_methods = SIP_UNKNOWN;
  7731. if (ast_strlen_zero(allow)) {
  7732. /* I have witnessed that REGISTER requests from Polycom phones do not
  7733. * place the phone's allowed methods in an Allow header. Instead, they place the
  7734. * allowed methods in a methods= parameter in the Contact header.
  7735. */
  7736. char *contact = ast_strdupa(get_header(req, "Contact"));
  7737. char *methods = strstr(contact, ";methods=");
  7738. if (ast_strlen_zero(methods)) {
  7739. /* RFC 3261 states:
  7740. *
  7741. * "The absence of an Allow header field MUST NOT be
  7742. * interpreted to mean that the UA sending the message supports no
  7743. * methods. Rather, it implies that the UA is not providing any
  7744. * information on what methods it supports."
  7745. *
  7746. * For simplicity, we'll assume that the peer allows all known
  7747. * SIP methods if they have no Allow header. We can then clear out the necessary
  7748. * bits if the peer lets us know that we have sent an unsupported method.
  7749. */
  7750. return UINT_MAX;
  7751. }
  7752. allow = ast_strip_quoted(methods + 9, "\"", "\"");
  7753. }
  7754. mark_parsed_methods(&allowed_methods, allow);
  7755. return allowed_methods;
  7756. }
  7757. /*! A wrapper for parse_allowed_methods geared toward sip_pvts
  7758. *
  7759. * This function, in addition to setting the allowed methods for a sip_pvt
  7760. * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
  7761. *
  7762. * \param pvt The sip_pvt we are setting the allowed_methods for
  7763. * \param req The request which we are parsing
  7764. * \retval The methods alloweded by the sip_pvt
  7765. */
  7766. static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
  7767. {
  7768. pvt->allowed_methods = parse_allowed_methods(req);
  7769. if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
  7770. mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
  7771. }
  7772. pvt->allowed_methods &= ~(pvt->disallowed_methods);
  7773. return pvt->allowed_methods;
  7774. }
  7775. /*! \brief Parse multiline SIP headers into one header
  7776. This is enabled if pedanticsipchecking is enabled */
  7777. static void lws2sws(struct ast_str *data)
  7778. {
  7779. char *msgbuf = data->str;
  7780. int len = ast_str_strlen(data);
  7781. int h = 0, t = 0;
  7782. int lws = 0;
  7783. for (; h < len;) {
  7784. /* Eliminate all CRs */
  7785. if (msgbuf[h] == '\r') {
  7786. h++;
  7787. continue;
  7788. }
  7789. /* Check for end-of-line */
  7790. if (msgbuf[h] == '\n') {
  7791. /* Check for end-of-message */
  7792. if (h + 1 == len)
  7793. break;
  7794. /* Check for a continuation line */
  7795. if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
  7796. /* Merge continuation line */
  7797. h++;
  7798. continue;
  7799. }
  7800. /* Propagate LF and start new line */
  7801. msgbuf[t++] = msgbuf[h++];
  7802. lws = 0;
  7803. continue;
  7804. }
  7805. if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
  7806. if (lws) {
  7807. h++;
  7808. continue;
  7809. }
  7810. msgbuf[t++] = msgbuf[h++];
  7811. lws = 1;
  7812. continue;
  7813. }
  7814. msgbuf[t++] = msgbuf[h++];
  7815. if (lws)
  7816. lws = 0;
  7817. }
  7818. msgbuf[t] = '\0';
  7819. data->used = t;
  7820. }
  7821. /*! \brief Parse a SIP message
  7822. \note this function is used both on incoming and outgoing packets
  7823. */
  7824. static int parse_request(struct sip_request *req)
  7825. {
  7826. char *c = req->data->str;
  7827. ptrdiff_t *dst = req->header;
  7828. int i = 0, lim = SIP_MAX_HEADERS - 1;
  7829. unsigned int skipping_headers = 0;
  7830. ptrdiff_t current_header_offset = 0;
  7831. char *previous_header = "";
  7832. req->header[0] = 0;
  7833. req->headers = -1; /* mark that we are working on the header */
  7834. for (; *c; c++) {
  7835. if (*c == '\r') { /* remove \r */
  7836. *c = '\0';
  7837. } else if (*c == '\n') { /* end of this line */
  7838. *c = '\0';
  7839. current_header_offset = (c + 1) - ast_str_buffer(req->data);
  7840. previous_header = ast_str_buffer(req->data) + dst[i];
  7841. if (skipping_headers) {
  7842. /* check to see if this line is blank; if so, turn off
  7843. the skipping flag, so the next line will be processed
  7844. as a body line */
  7845. if (ast_strlen_zero(previous_header)) {
  7846. skipping_headers = 0;
  7847. }
  7848. dst[i] = current_header_offset; /* record start of next line */
  7849. continue;
  7850. }
  7851. if (sipdebug) {
  7852. ast_debug(4, "%7s %2d [%3d]: %s\n",
  7853. req->headers < 0 ? "Header" : "Body",
  7854. i, (int) strlen(previous_header), previous_header);
  7855. }
  7856. if (ast_strlen_zero(previous_header) && req->headers < 0) {
  7857. req->headers = i; /* record number of header lines */
  7858. dst = req->line; /* start working on the body */
  7859. i = 0;
  7860. lim = SIP_MAX_LINES - 1;
  7861. } else { /* move to next line, check for overflows */
  7862. if (i++ == lim) {
  7863. /* if we're processing headers, then skip any remaining
  7864. headers and move on to processing the body, otherwise
  7865. we're done */
  7866. if (req->headers != -1) {
  7867. break;
  7868. } else {
  7869. req->headers = i;
  7870. dst = req->line;
  7871. i = 0;
  7872. lim = SIP_MAX_LINES - 1;
  7873. skipping_headers = 1;
  7874. }
  7875. }
  7876. }
  7877. dst[i] = current_header_offset; /* record start of next line */
  7878. }
  7879. }
  7880. /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
  7881. but since some devices send without, we'll be generous in what we accept. However,
  7882. if we've already reached the maximum number of lines for portion of the message
  7883. we were parsing, we can't accept any more, so just ignore it.
  7884. */
  7885. previous_header = ast_str_buffer(req->data) + dst[i];
  7886. if ((i < lim) && !ast_strlen_zero(previous_header)) {
  7887. if (sipdebug) {
  7888. ast_debug(4, "%7s %2d [%3d]: %s\n",
  7889. req->headers < 0 ? "Header" : "Body",
  7890. i, (int) strlen(previous_header), previous_header );
  7891. }
  7892. i++;
  7893. }
  7894. /* update count of header or body lines */
  7895. if (req->headers >= 0) { /* we are in the body */
  7896. req->lines = i;
  7897. } else { /* no body */
  7898. req->headers = i;
  7899. req->lines = 0;
  7900. /* req->data->used will be a NULL byte */
  7901. req->line[0] = ast_str_strlen(req->data);
  7902. }
  7903. if (*c) {
  7904. ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
  7905. }
  7906. /* Split up the first line parts */
  7907. return determine_firstline_parts(req);
  7908. }
  7909. /*!
  7910. \brief Determine whether a SIP message contains an SDP in its body
  7911. \param req the SIP request to process
  7912. \return 1 if SDP found, 0 if not found
  7913. Also updates req->sdp_start and req->sdp_count to indicate where the SDP
  7914. lives in the message body.
  7915. */
  7916. static int find_sdp(struct sip_request *req)
  7917. {
  7918. const char *content_type;
  7919. const char *content_length;
  7920. const char *search;
  7921. char *boundary;
  7922. unsigned int x;
  7923. int boundaryisquoted = FALSE;
  7924. int found_application_sdp = FALSE;
  7925. int found_end_of_headers = FALSE;
  7926. content_length = get_header(req, "Content-Length");
  7927. if (!ast_strlen_zero(content_length)) {
  7928. if (sscanf(content_length, "%30u", &x) != 1) {
  7929. ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
  7930. return 0;
  7931. }
  7932. /* Content-Length of zero means there can't possibly be an
  7933. SDP here, even if the Content-Type says there is */
  7934. if (x == 0)
  7935. return 0;
  7936. }
  7937. content_type = get_header(req, "Content-Type");
  7938. /* if the body contains only SDP, this is easy */
  7939. if (!strncasecmp(content_type, "application/sdp", 15)) {
  7940. req->sdp_start = 0;
  7941. req->sdp_count = req->lines;
  7942. return req->lines ? 1 : 0;
  7943. }
  7944. /* if it's not multipart/mixed, there cannot be an SDP */
  7945. if (strncasecmp(content_type, "multipart/mixed", 15))
  7946. return 0;
  7947. /* if there is no boundary marker, it's invalid */
  7948. if ((search = strcasestr(content_type, ";boundary=")))
  7949. search += 10;
  7950. else if ((search = strcasestr(content_type, "; boundary=")))
  7951. search += 11;
  7952. else
  7953. return 0;
  7954. if (ast_strlen_zero(search))
  7955. return 0;
  7956. /* If the boundary is quoted with ", remove quote */
  7957. if (*search == '\"') {
  7958. search++;
  7959. boundaryisquoted = TRUE;
  7960. }
  7961. /* make a duplicate of the string, with two extra characters
  7962. at the beginning */
  7963. boundary = ast_strdupa(search - 2);
  7964. boundary[0] = boundary[1] = '-';
  7965. /* Remove final quote */
  7966. if (boundaryisquoted)
  7967. boundary[strlen(boundary) - 1] = '\0';
  7968. /* search for the boundary marker, the empty line delimiting headers from
  7969. sdp part and the end boundry if it exists */
  7970. for (x = 0; x < (req->lines); x++) {
  7971. const char *line = REQ_OFFSET_TO_STR(req, line[x]);
  7972. if (!strncasecmp(line, boundary, strlen(boundary))){
  7973. if (found_application_sdp && found_end_of_headers) {
  7974. req->sdp_count = (x - 1) - req->sdp_start;
  7975. return 1;
  7976. }
  7977. found_application_sdp = FALSE;
  7978. }
  7979. if (!strcasecmp(line, "Content-Type: application/sdp"))
  7980. found_application_sdp = TRUE;
  7981. if (ast_strlen_zero(line)) {
  7982. if (found_application_sdp && !found_end_of_headers){
  7983. req->sdp_start = x;
  7984. found_end_of_headers = TRUE;
  7985. }
  7986. }
  7987. }
  7988. if (found_application_sdp && found_end_of_headers) {
  7989. req->sdp_count = x - req->sdp_start;
  7990. return TRUE;
  7991. }
  7992. return FALSE;
  7993. }
  7994. /*! \brief Change hold state for a call */
  7995. static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
  7996. {
  7997. if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
  7998. sip_peer_hold(dialog, holdstate);
  7999. if (sip_cfg.callevents)
  8000. manager_event(EVENT_FLAG_CALL, "Hold",
  8001. "Status: %s\r\n"
  8002. "Channel: %s\r\n"
  8003. "Uniqueid: %s\r\n",
  8004. holdstate ? "On" : "Off",
  8005. dialog->owner->name,
  8006. dialog->owner->uniqueid);
  8007. append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", ast_str_buffer(req->data));
  8008. if (!holdstate) { /* Put off remote hold */
  8009. ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
  8010. return;
  8011. }
  8012. /* No address for RTP, we're on hold */
  8013. /* Ensure hold flags are cleared so that overlapping flags do not conflict */
  8014. ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
  8015. if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
  8016. ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
  8017. else if (sendonly == 2) /* Inactive stream */
  8018. ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
  8019. else
  8020. ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
  8021. return;
  8022. }
  8023. static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
  8024. {
  8025. const char *m;
  8026. const char *c;
  8027. int miterator = req->sdp_start;
  8028. int citerator = req->sdp_start;
  8029. unsigned int x = 0;
  8030. unsigned int numberofports;
  8031. int len;
  8032. int af;
  8033. char proto[4], host[258] = ""; /*Initialize to empty so we will know if we have any input */
  8034. c = get_sdp_iterate(&citerator, req, "c");
  8035. if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
  8036. ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
  8037. /* Continue since there may be a valid host in a c= line specific to the audio stream */
  8038. }
  8039. /* We only want the m and c lines for audio */
  8040. for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
  8041. if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
  8042. (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
  8043. (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
  8044. (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
  8045. /* See if there's a c= line for this media stream.
  8046. * XXX There is no guarantee that we'll be grabbing the c= line for this
  8047. * particular media stream here. However, this is the same logic used in process_sdp.
  8048. */
  8049. c = get_sdp_iterate(&citerator, req, "c");
  8050. if (!ast_strlen_zero(c)) {
  8051. sscanf(c, "IN %3s %256s", proto, host);
  8052. }
  8053. break;
  8054. }
  8055. }
  8056. if (!strcmp("IP4", proto)) {
  8057. af = AF_INET;
  8058. } else if (!strcmp("IP6", proto)) {
  8059. af = AF_INET6;
  8060. } else {
  8061. ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
  8062. return -1;
  8063. }
  8064. if (ast_strlen_zero(host) || x == 0) {
  8065. ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
  8066. return -1;
  8067. }
  8068. if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
  8069. ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
  8070. return -1;
  8071. }
  8072. return 0;
  8073. }
  8074. /*! \internal
  8075. * \brief Returns whether or not the address is null or ANY / unspecified (0.0.0.0 or ::)
  8076. * \retval TRUE if the address is null or any
  8077. * \retval FALSE if the address it not null or any
  8078. * \note In some circumstances, calls should be placed on hold if either of these conditions exist.
  8079. */
  8080. static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
  8081. {
  8082. return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
  8083. }
  8084. /*! \brief Process SIP SDP offer, select formats and activate media channels
  8085. If offer is rejected, we will not change any properties of the call
  8086. Return 0 on success, a negative value on errors.
  8087. Must be called after find_sdp().
  8088. */
  8089. static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
  8090. {
  8091. /* Iterators for SDP parsing */
  8092. int start = req->sdp_start;
  8093. int next = start;
  8094. int iterator = start;
  8095. /* Temporary vars for SDP parsing */
  8096. char type = '\0';
  8097. const char *value = NULL;
  8098. const char *m = NULL; /* SDP media offer */
  8099. const char *nextm = NULL;
  8100. int len = -1;
  8101. /* Host information */
  8102. struct ast_sockaddr sessionsa;
  8103. struct ast_sockaddr audiosa;
  8104. struct ast_sockaddr videosa;
  8105. struct ast_sockaddr textsa;
  8106. struct ast_sockaddr imagesa;
  8107. struct ast_sockaddr *sa = NULL; /*!< RTP audio destination IP address */
  8108. struct ast_sockaddr *vsa = NULL; /*!< RTP video destination IP address */
  8109. struct ast_sockaddr *tsa = NULL; /*!< RTP text destination IP address */
  8110. struct ast_sockaddr *isa = NULL; /*!< UDPTL image destination IP address */
  8111. int portno = -1; /*!< RTP audio destination port number */
  8112. int vportno = -1; /*!< RTP video destination port number */
  8113. int tportno = -1; /*!< RTP text destination port number */
  8114. int udptlportno = -1; /*!< UDPTL image destination port number */
  8115. /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
  8116. format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
  8117. int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
  8118. struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
  8119. format_t newjointcapability; /* Negotiated capability */
  8120. format_t newpeercapability;
  8121. int newnoncodeccapability;
  8122. const char *codecs;
  8123. unsigned int codec;
  8124. /* SRTP */
  8125. int secure_audio = FALSE;
  8126. int secure_video = FALSE;
  8127. /* Others */
  8128. int sendonly = -1;
  8129. unsigned int numberofports;
  8130. int numberofmediastreams = 0;
  8131. int last_rtpmap_codec = 0;
  8132. int red_data_pt[10]; /* For T.140 RED */
  8133. int red_num_gen = 0; /* For T.140 RED */
  8134. char red_fmtp[100] = "empty"; /* For T.140 RED */
  8135. int debug = sip_debug_test_pvt(p);
  8136. /* START UNKNOWN */
  8137. char buf[SIPBUFSIZE];
  8138. /* END UNKNOWN */
  8139. /* Initial check */
  8140. if (!p->rtp) {
  8141. ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
  8142. return -1;
  8143. }
  8144. /* Make sure that the codec structures are all cleared out */
  8145. ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
  8146. ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
  8147. ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
  8148. /* Update our last rtprx when we receive an SDP, too */
  8149. p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
  8150. memset(p->offered_media, 0, sizeof(p->offered_media));
  8151. /* default: novideo and notext set */
  8152. p->novideo = TRUE;
  8153. p->notext = TRUE;
  8154. /* Scan for the first media stream (m=) line to limit scanning of globals */
  8155. nextm = get_sdp_iterate(&next, req, "m");
  8156. if (ast_strlen_zero(nextm)) {
  8157. ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
  8158. return -1;
  8159. }
  8160. /* Scan session level SDP parameters (lines before first media stream) */
  8161. while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
  8162. int processed = FALSE;
  8163. switch (type) {
  8164. case 'o':
  8165. /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
  8166. * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
  8167. */
  8168. if (!process_sdp_o(value, p)) {
  8169. return (p->session_modify == FALSE) ? 0 : -1;
  8170. }
  8171. processed = TRUE;
  8172. break;
  8173. case 'c':
  8174. if (process_sdp_c(value, &sessionsa)) {
  8175. processed = TRUE;
  8176. sa = &sessionsa;
  8177. vsa = sa;
  8178. tsa = sa;
  8179. isa = sa;
  8180. }
  8181. break;
  8182. case 'a':
  8183. if (process_sdp_a_sendonly(value, &sendonly)) {
  8184. processed = TRUE;
  8185. }
  8186. else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
  8187. processed = TRUE;
  8188. else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
  8189. processed = TRUE;
  8190. else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
  8191. processed = TRUE;
  8192. else if (process_sdp_a_image(value, p))
  8193. processed = TRUE;
  8194. break;
  8195. }
  8196. ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
  8197. }
  8198. /* Scan media stream (m=) specific parameters loop */
  8199. while (!ast_strlen_zero(nextm)) {
  8200. int audio = FALSE;
  8201. int video = FALSE;
  8202. int image = FALSE;
  8203. int text = FALSE;
  8204. int processed_crypto = FALSE;
  8205. char protocol[18] = {0,};
  8206. unsigned int x;
  8207. numberofports = 0;
  8208. len = -1;
  8209. start = next;
  8210. m = nextm;
  8211. iterator = next;
  8212. nextm = get_sdp_iterate(&next, req, "m");
  8213. /* Check for 'audio' media offer */
  8214. if (strncmp(m, "audio ", 6) == 0) {
  8215. if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
  8216. (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
  8217. if (x == 0) {
  8218. ast_log(LOG_WARNING, "Ignoring audio media offer because port number is zero\n");
  8219. continue;
  8220. }
  8221. /* Check number of ports offered for stream */
  8222. if (numberofports > 1) {
  8223. ast_log(LOG_WARNING, "%u ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
  8224. }
  8225. if (!strcmp(protocol, "SAVP")) {
  8226. secure_audio = 1;
  8227. } else if (strcmp(protocol, "AVP")) {
  8228. ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
  8229. continue;
  8230. }
  8231. if (p->offered_media[SDP_AUDIO].order_offered) {
  8232. ast_log(LOG_WARNING, "Rejecting non-primary audio stream: %s\n", m);
  8233. return -1;
  8234. }
  8235. audio = TRUE;
  8236. p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
  8237. portno = x;
  8238. /* Scan through the RTP payload types specified in a "m=" line: */
  8239. codecs = m + len;
  8240. ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
  8241. for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
  8242. if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
  8243. ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
  8244. return -1;
  8245. }
  8246. if (debug) {
  8247. ast_verbose("Found RTP audio format %u\n", codec);
  8248. }
  8249. ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
  8250. }
  8251. } else {
  8252. ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
  8253. return -1;
  8254. }
  8255. }
  8256. /* Check for 'video' media offer */
  8257. else if (strncmp(m, "video ", 6) == 0) {
  8258. if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
  8259. (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
  8260. if (x == 0) {
  8261. ast_log(LOG_WARNING, "Ignoring video media offer because port number is zero\n");
  8262. continue;
  8263. }
  8264. /* Check number of ports offered for stream */
  8265. if (numberofports > 1) {
  8266. ast_log(LOG_WARNING, "%u ports offered for video media, not supported by Asterisk. Will try anyway...\n", numberofports);
  8267. }
  8268. if (!strcmp(protocol, "SAVP")) {
  8269. secure_video = 1;
  8270. } else if (strcmp(protocol, "AVP")) {
  8271. ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
  8272. continue;
  8273. }
  8274. if (p->offered_media[SDP_VIDEO].order_offered) {
  8275. ast_log(LOG_WARNING, "Rejecting non-primary video stream: %s\n", m);
  8276. return -1;
  8277. }
  8278. video = TRUE;
  8279. p->novideo = FALSE;
  8280. p->offered_media[SDP_VIDEO].order_offered = ++numberofmediastreams;
  8281. vportno = x;
  8282. /* Scan through the RTP payload types specified in a "m=" line: */
  8283. codecs = m + len;
  8284. ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
  8285. for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
  8286. if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
  8287. ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
  8288. return -1;
  8289. }
  8290. if (debug) {
  8291. ast_verbose("Found RTP video format %u\n", codec);
  8292. }
  8293. ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
  8294. }
  8295. } else {
  8296. ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
  8297. return -1;
  8298. }
  8299. }
  8300. /* Check for 'text' media offer */
  8301. else if (strncmp(m, "text ", 5) == 0) {
  8302. if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
  8303. (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
  8304. if (x == 0) {
  8305. ast_log(LOG_WARNING, "Ignoring text media offer because port number is zero\n");
  8306. continue;
  8307. }
  8308. /* Check number of ports offered for stream */
  8309. if (numberofports > 1) {
  8310. ast_log(LOG_WARNING, "%u ports offered for text media, not supported by Asterisk. Will try anyway...\n", numberofports);
  8311. }
  8312. if (p->offered_media[SDP_TEXT].order_offered) {
  8313. ast_log(LOG_WARNING, "Rejecting non-primary text stream: %s\n", m);
  8314. return -1;
  8315. }
  8316. text = TRUE;
  8317. p->notext = FALSE;
  8318. p->offered_media[SDP_TEXT].order_offered = ++numberofmediastreams;
  8319. tportno = x;
  8320. /* Scan through the RTP payload types specified in a "m=" line: */
  8321. codecs = m + len;
  8322. ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
  8323. for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
  8324. if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
  8325. ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
  8326. return -1;
  8327. }
  8328. if (debug) {
  8329. ast_verbose("Found RTP text format %u\n", codec);
  8330. }
  8331. ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
  8332. }
  8333. } else {
  8334. ast_log(LOG_WARNING, "Rejecting text media offer due to invalid or unsupported syntax: %s\n", m);
  8335. return -1;
  8336. }
  8337. }
  8338. /* Check for 'image' media offer */
  8339. else if (strncmp(m, "image ", 6) == 0) {
  8340. if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
  8341. (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
  8342. if (x == 0) {
  8343. ast_log(LOG_WARNING, "Ignoring image media offer because port number is zero\n");
  8344. continue;
  8345. }
  8346. if (initialize_udptl(p)) {
  8347. ast_log(LOG_WARNING, "Rejecting offer with image stream due to UDPTL initialization failure\n");
  8348. return -1;
  8349. }
  8350. if (p->offered_media[SDP_IMAGE].order_offered) {
  8351. ast_log(LOG_WARNING, "Rejecting non-primary image stream: %s\n", m);
  8352. return -1;
  8353. }
  8354. image = TRUE;
  8355. if (debug) {
  8356. ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
  8357. }
  8358. p->offered_media[SDP_IMAGE].order_offered = ++numberofmediastreams;
  8359. udptlportno = x;
  8360. if (p->t38.state != T38_ENABLED) {
  8361. memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
  8362. /* default EC to none, the remote end should
  8363. * respond with the EC they want to use */
  8364. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
  8365. }
  8366. } else if (sscanf(m, "image %30u %17s t38%n", &x, protocol, &len) == 2 && len > 0) {
  8367. ast_log(LOG_WARNING, "Declining image stream due to unsupported transport: %s\n", m);
  8368. continue;
  8369. } else {
  8370. ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
  8371. return -1;
  8372. }
  8373. } else {
  8374. ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
  8375. continue;
  8376. }
  8377. /* Media stream specific parameters */
  8378. while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
  8379. int processed = FALSE;
  8380. switch (type) {
  8381. case 'c':
  8382. if (audio) {
  8383. if (process_sdp_c(value, &audiosa)) {
  8384. processed = TRUE;
  8385. sa = &audiosa;
  8386. }
  8387. } else if (video) {
  8388. if (process_sdp_c(value, &videosa)) {
  8389. processed = TRUE;
  8390. vsa = &videosa;
  8391. }
  8392. } else if (text) {
  8393. if (process_sdp_c(value, &textsa)) {
  8394. processed = TRUE;
  8395. tsa = &textsa;
  8396. }
  8397. } else if (image) {
  8398. if (process_sdp_c(value, &imagesa)) {
  8399. processed = TRUE;
  8400. isa = &imagesa;
  8401. }
  8402. }
  8403. break;
  8404. case 'a':
  8405. /* Audio specific scanning */
  8406. if (audio) {
  8407. if (process_sdp_a_sendonly(value, &sendonly)) {
  8408. processed = TRUE;
  8409. } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
  8410. processed_crypto = TRUE;
  8411. processed = TRUE;
  8412. } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
  8413. processed = TRUE;
  8414. }
  8415. }
  8416. /* Video specific scanning */
  8417. else if (video) {
  8418. if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
  8419. processed_crypto = TRUE;
  8420. processed = TRUE;
  8421. } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
  8422. processed = TRUE;
  8423. }
  8424. }
  8425. /* Text (T.140) specific scanning */
  8426. else if (text) {
  8427. if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
  8428. processed = TRUE;
  8429. } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
  8430. processed_crypto = TRUE;
  8431. processed = TRUE;
  8432. }
  8433. }
  8434. /* Image (T.38 FAX) specific scanning */
  8435. else if (image) {
  8436. if (process_sdp_a_image(value, p))
  8437. processed = TRUE;
  8438. }
  8439. break;
  8440. }
  8441. ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
  8442. (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
  8443. type, value,
  8444. (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
  8445. }
  8446. /* Ensure crypto lines are provided where necessary */
  8447. if (audio && secure_audio && !processed_crypto) {
  8448. ast_log(LOG_WARNING, "Rejecting secure audio stream without encryption details: %s\n", m);
  8449. return -1;
  8450. } else if (video && secure_video && !processed_crypto) {
  8451. ast_log(LOG_WARNING, "Rejecting secure video stream without encryption details: %s\n", m);
  8452. return -1;
  8453. }
  8454. }
  8455. /* Sanity checks */
  8456. if (!sa && !vsa && !tsa && !isa) {
  8457. ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
  8458. return -1;
  8459. }
  8460. if ((portno == -1) &&
  8461. (vportno == -1) &&
  8462. (tportno == -1) &&
  8463. (udptlportno == -1)) {
  8464. ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
  8465. return -1;
  8466. }
  8467. if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
  8468. ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
  8469. return -1;
  8470. }
  8471. if (!secure_audio && p->srtp) {
  8472. ast_log(LOG_WARNING, "We are requesting SRTP for audio, but they responded without it!\n");
  8473. return -1;
  8474. }
  8475. if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
  8476. ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
  8477. return -1;
  8478. }
  8479. if (!p->novideo && !secure_video && p->vsrtp) {
  8480. ast_log(LOG_WARNING, "We are requesting SRTP for video, but they responded without it!\n");
  8481. return -1;
  8482. }
  8483. if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
  8484. ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
  8485. return -1;
  8486. }
  8487. if (udptlportno == -1) {
  8488. change_t38_state(p, T38_DISABLED);
  8489. }
  8490. /* Now gather all of the codecs that we are asked for: */
  8491. ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
  8492. ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
  8493. ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
  8494. newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
  8495. newpeercapability = (peercapability | vpeercapability | tpeercapability);
  8496. newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
  8497. if (debug) {
  8498. /* shame on whoever coded this.... */
  8499. char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
  8500. ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
  8501. ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
  8502. ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
  8503. ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
  8504. ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
  8505. ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
  8506. }
  8507. if (debug) {
  8508. struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
  8509. struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
  8510. struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
  8511. ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
  8512. ast_rtp_lookup_mime_multiple2(s1, p->noncodeccapability, 0, 0),
  8513. ast_rtp_lookup_mime_multiple2(s2, peernoncodeccapability, 0, 0),
  8514. ast_rtp_lookup_mime_multiple2(s3, newnoncodeccapability, 0, 0));
  8515. }
  8516. if (!newjointcapability && udptlportno == -1) {
  8517. ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
  8518. /* Do NOT Change current setting */
  8519. return -1;
  8520. }
  8521. if (portno != -1 || vportno != -1 || tportno != -1) {
  8522. /* We are now ready to change the sip session and RTP structures with the offered codecs, since
  8523. they are acceptable */
  8524. p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
  8525. p->peercapability = newpeercapability; /* The other side's capability in latest offer */
  8526. p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
  8527. /* respond with single most preferred joint codec, limiting the other side's choice */
  8528. if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
  8529. p->jointcapability = ast_codec_choose(&p->prefs, p->jointcapability, 1);
  8530. }
  8531. }
  8532. /* Setup audio address and port */
  8533. if (p->rtp) {
  8534. if (sa && portno > 0) {
  8535. ast_sockaddr_set_port(sa, portno);
  8536. ast_rtp_instance_set_remote_address(p->rtp, sa);
  8537. if (debug) {
  8538. ast_verbose("Peer audio RTP is at port %s\n",
  8539. ast_sockaddr_stringify(sa));
  8540. }
  8541. ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
  8542. /* Ensure RTCP is enabled since it may be inactive
  8543. if we're coming back from a T.38 session */
  8544. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
  8545. /* Ensure audio RTCP reads are enabled */
  8546. if (p->owner) {
  8547. ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
  8548. }
  8549. if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
  8550. ast_clear_flag(&p->flags[0], SIP_DTMF);
  8551. if (newnoncodeccapability & AST_RTP_DTMF) {
  8552. /* XXX Would it be reasonable to drop the DSP at this point? XXX */
  8553. ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
  8554. /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
  8555. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
  8556. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  8557. } else {
  8558. ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
  8559. }
  8560. }
  8561. } else if (udptlportno > 0) {
  8562. if (debug)
  8563. ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
  8564. /* Prevent audio RTCP reads */
  8565. if (p->owner) {
  8566. ast_channel_set_fd(p->owner, 1, -1);
  8567. }
  8568. /* Silence RTCP while audio RTP is inactive */
  8569. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
  8570. } else {
  8571. ast_rtp_instance_stop(p->rtp);
  8572. if (debug)
  8573. ast_verbose("Peer doesn't provide audio\n");
  8574. }
  8575. }
  8576. /* Setup video address and port */
  8577. if (p->vrtp) {
  8578. if (vsa && vportno > 0) {
  8579. ast_sockaddr_set_port(vsa, vportno);
  8580. ast_rtp_instance_set_remote_address(p->vrtp, vsa);
  8581. if (debug) {
  8582. ast_verbose("Peer video RTP is at port %s\n",
  8583. ast_sockaddr_stringify(vsa));
  8584. }
  8585. ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
  8586. } else {
  8587. ast_rtp_instance_stop(p->vrtp);
  8588. if (debug)
  8589. ast_verbose("Peer doesn't provide video\n");
  8590. }
  8591. }
  8592. /* Setup text address and port */
  8593. if (p->trtp) {
  8594. if (tsa && tportno > 0) {
  8595. ast_sockaddr_set_port(tsa, tportno);
  8596. ast_rtp_instance_set_remote_address(p->trtp, tsa);
  8597. if (debug) {
  8598. ast_verbose("Peer T.140 RTP is at port %s\n",
  8599. ast_sockaddr_stringify(tsa));
  8600. }
  8601. if ((p->jointcapability & AST_FORMAT_T140RED)) {
  8602. p->red = 1;
  8603. ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
  8604. } else {
  8605. p->red = 0;
  8606. }
  8607. ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
  8608. } else {
  8609. ast_rtp_instance_stop(p->trtp);
  8610. if (debug)
  8611. ast_verbose("Peer doesn't provide T.140\n");
  8612. }
  8613. }
  8614. /* Setup image address and port */
  8615. if (p->udptl) {
  8616. if (isa && udptlportno > 0) {
  8617. if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
  8618. ast_rtp_instance_get_remote_address(p->rtp, isa);
  8619. if (!ast_sockaddr_isnull(isa) && debug) {
  8620. ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
  8621. }
  8622. }
  8623. ast_sockaddr_set_port(isa, udptlportno);
  8624. ast_udptl_set_peer(p->udptl, isa);
  8625. if (debug)
  8626. ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
  8627. /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
  8628. if (!ast_udptl_get_far_max_datagram(p->udptl)) {
  8629. /* setting to zero will force a default if none was provided by the SDP */
  8630. ast_udptl_set_far_max_datagram(p->udptl, 0);
  8631. }
  8632. /* Remote party offers T38, we need to update state */
  8633. if ((t38action == SDP_T38_ACCEPT) &&
  8634. (p->t38.state == T38_LOCAL_REINVITE)) {
  8635. change_t38_state(p, T38_ENABLED);
  8636. } else if ((t38action == SDP_T38_INITIATE) &&
  8637. p->owner && p->lastinvite) {
  8638. change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
  8639. /* If fax detection is enabled then send us off to the fax extension */
  8640. if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
  8641. ast_channel_lock(p->owner);
  8642. if (strcmp(p->owner->exten, "fax")) {
  8643. const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
  8644. ast_channel_unlock(p->owner);
  8645. if (ast_exists_extension(p->owner, target_context, "fax", 1,
  8646. S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
  8647. ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
  8648. pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
  8649. if (ast_async_goto(p->owner, target_context, "fax", 1)) {
  8650. ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
  8651. }
  8652. } else {
  8653. ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
  8654. }
  8655. } else {
  8656. ast_channel_unlock(p->owner);
  8657. }
  8658. }
  8659. }
  8660. } else {
  8661. change_t38_state(p, T38_DISABLED);
  8662. ast_udptl_stop(p->udptl);
  8663. if (debug)
  8664. ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
  8665. }
  8666. }
  8667. if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
  8668. ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
  8669. return 0;
  8670. }
  8671. /* Ok, we're going with this offer */
  8672. ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
  8673. if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
  8674. return 0;
  8675. ast_debug(4, "We have an owner, now see if we need to change this call\n");
  8676. if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
  8677. if (debug) {
  8678. char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
  8679. ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
  8680. ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
  8681. ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
  8682. }
  8683. p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
  8684. ast_set_read_format(p->owner, p->owner->readformat);
  8685. ast_set_write_format(p->owner, p->owner->writeformat);
  8686. }
  8687. 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)) {
  8688. ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
  8689. /* Activate a re-invite */
  8690. ast_queue_frame(p->owner, &ast_null_frame);
  8691. change_hold_state(p, req, FALSE, sendonly);
  8692. } 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)) {
  8693. ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
  8694. S_OR(p->mohsuggest, NULL),
  8695. !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
  8696. if (sendonly)
  8697. ast_rtp_instance_stop(p->rtp);
  8698. /* RTCP needs to go ahead, even if we're on hold!!! */
  8699. /* Activate a re-invite */
  8700. ast_queue_frame(p->owner, &ast_null_frame);
  8701. change_hold_state(p, req, TRUE, sendonly);
  8702. }
  8703. return 0;
  8704. }
  8705. static int process_sdp_o(const char *o, struct sip_pvt *p)
  8706. {
  8707. char *o_copy;
  8708. char *token;
  8709. int64_t rua_version;
  8710. /* Store the SDP version number of remote UA. This will allow us to
  8711. distinguish between session modifications and session refreshes. If
  8712. the remote UA does not send an incremented SDP version number in a
  8713. subsequent RE-INVITE then that means its not changing media session.
  8714. The RE-INVITE may have been sent to update connected party, remote
  8715. target or to refresh the session (Session-Timers). Asterisk must not
  8716. change media session and increment its own version number in answer
  8717. SDP in this case. */
  8718. p->session_modify = TRUE;
  8719. if (ast_strlen_zero(o)) {
  8720. ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
  8721. return FALSE;
  8722. }
  8723. o_copy = ast_strdupa(o);
  8724. token = strsep(&o_copy, " "); /* Skip username */
  8725. if (!o_copy) {
  8726. ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
  8727. return FALSE;
  8728. }
  8729. token = strsep(&o_copy, " "); /* Skip session-id */
  8730. if (!o_copy) {
  8731. ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
  8732. return FALSE;
  8733. }
  8734. token = strsep(&o_copy, " "); /* Version */
  8735. if (!o_copy) {
  8736. ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
  8737. return FALSE;
  8738. }
  8739. if (!sscanf(token, "%30" SCNd64, &rua_version)) {
  8740. ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
  8741. return FALSE;
  8742. }
  8743. /* we need to check the SDP version number the other end sent us;
  8744. * our rules for deciding what to accept are a bit complex.
  8745. *
  8746. * 1) if 'ignoresdpversion' has been set for this dialog, then
  8747. * we will just accept whatever they sent and assume it is
  8748. * a modification of the session, even if it is not
  8749. * 2) otherwise, if this is the first SDP we've seen from them
  8750. * we accept it
  8751. * 3) otherwise, if the new SDP version number is higher than the
  8752. * old one, we accept it
  8753. * 4) otherwise, if this SDP is in response to us requesting a switch
  8754. * to T.38, we accept the SDP, but also generate a warning message
  8755. * that this peer should have the 'ignoresdpversion' option set,
  8756. * because it is not following the SDP offer/answer RFC; if we did
  8757. * not request a switch to T.38, then we stop parsing the SDP, as it
  8758. * has not changed from the previous version
  8759. */
  8760. if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
  8761. (p->sessionversion_remote < 0) ||
  8762. (p->sessionversion_remote < rua_version)) {
  8763. p->sessionversion_remote = rua_version;
  8764. } else {
  8765. if (p->t38.state == T38_LOCAL_REINVITE) {
  8766. p->sessionversion_remote = rua_version;
  8767. 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);
  8768. } else {
  8769. p->session_modify = FALSE;
  8770. ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
  8771. return FALSE;
  8772. }
  8773. }
  8774. return TRUE;
  8775. }
  8776. static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
  8777. {
  8778. char proto[4], host[258];
  8779. int af;
  8780. /* Check for Media-description-level-address */
  8781. if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
  8782. if (!strcmp("IP4", proto)) {
  8783. af = AF_INET;
  8784. } else if (!strcmp("IP6", proto)) {
  8785. af = AF_INET6;
  8786. } else {
  8787. ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
  8788. return FALSE;
  8789. }
  8790. if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
  8791. ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
  8792. return FALSE;
  8793. }
  8794. return TRUE;
  8795. } else {
  8796. ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
  8797. return FALSE;
  8798. }
  8799. return FALSE;
  8800. }
  8801. static int process_sdp_a_sendonly(const char *a, int *sendonly)
  8802. {
  8803. int found = FALSE;
  8804. if (!strcasecmp(a, "sendonly")) {
  8805. if (*sendonly == -1)
  8806. *sendonly = 1;
  8807. found = TRUE;
  8808. } else if (!strcasecmp(a, "inactive")) {
  8809. if (*sendonly == -1)
  8810. *sendonly = 2;
  8811. found = TRUE;
  8812. } else if (!strcasecmp(a, "sendrecv")) {
  8813. if (*sendonly == -1)
  8814. *sendonly = 0;
  8815. found = TRUE;
  8816. }
  8817. return found;
  8818. }
  8819. static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
  8820. {
  8821. int found = FALSE;
  8822. unsigned int codec;
  8823. char mimeSubtype[128];
  8824. char fmtp_string[64];
  8825. unsigned int sample_rate;
  8826. int debug = sip_debug_test_pvt(p);
  8827. if (!strncasecmp(a, "ptime", 5)) {
  8828. char *tmp = strrchr(a, ':');
  8829. long int framing = 0;
  8830. if (tmp) {
  8831. tmp++;
  8832. framing = strtol(tmp, NULL, 10);
  8833. if (framing == LONG_MIN || framing == LONG_MAX) {
  8834. framing = 0;
  8835. ast_debug(1, "Can't read framing from SDP: %s\n", a);
  8836. }
  8837. }
  8838. if (framing && p->autoframing) {
  8839. struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
  8840. int codec_n;
  8841. for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
  8842. struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
  8843. if (!format.asterisk_format || !format.code) /* non-codec or not found */
  8844. continue;
  8845. ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(format.code), framing);
  8846. ast_codec_pref_setsize(pref, format.code, framing);
  8847. }
  8848. ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
  8849. }
  8850. found = TRUE;
  8851. } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
  8852. /* We have a rtpmap to handle */
  8853. if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
  8854. if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
  8855. ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
  8856. if (debug)
  8857. ast_verbose("Found audio description format %s for ID %u\n", mimeSubtype, codec);
  8858. //found_rtpmap_codecs[last_rtpmap_codec] = codec;
  8859. (*last_rtpmap_codec)++;
  8860. found = TRUE;
  8861. } else {
  8862. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  8863. if (debug)
  8864. ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
  8865. }
  8866. } else {
  8867. if (debug)
  8868. ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
  8869. }
  8870. } else if (sscanf(a, "fmtp: %30u %63[^\t\n]", &codec, fmtp_string) == 2) {
  8871. struct ast_rtp_payload_type payload;
  8872. payload = ast_rtp_codecs_payload_lookup(newaudiortp, codec);
  8873. if (payload.code && payload.asterisk_format) {
  8874. unsigned int bit_rate;
  8875. switch (payload.code) {
  8876. case AST_FORMAT_SIREN7:
  8877. if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
  8878. if (bit_rate != 32000) {
  8879. ast_log(LOG_WARNING, "Got Siren7 offer at %u bps, but only 32000 bps supported; ignoring.\n", bit_rate);
  8880. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  8881. } else {
  8882. found = TRUE;
  8883. }
  8884. }
  8885. break;
  8886. case AST_FORMAT_SIREN14:
  8887. if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
  8888. if (bit_rate != 48000) {
  8889. ast_log(LOG_WARNING, "Got Siren14 offer at %u bps, but only 48000 bps supported; ignoring.\n", bit_rate);
  8890. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  8891. } else {
  8892. found = TRUE;
  8893. }
  8894. }
  8895. break;
  8896. case AST_FORMAT_G719:
  8897. if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
  8898. if (bit_rate != 64000) {
  8899. ast_log(LOG_WARNING, "Got G.719 offer at %u bps, but only 64000 bps supported; ignoring.\n", bit_rate);
  8900. ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
  8901. } else {
  8902. found = TRUE;
  8903. }
  8904. }
  8905. }
  8906. }
  8907. }
  8908. return found;
  8909. }
  8910. static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
  8911. {
  8912. int found = FALSE;
  8913. unsigned int codec;
  8914. char mimeSubtype[128];
  8915. unsigned int sample_rate;
  8916. int debug = sip_debug_test_pvt(p);
  8917. if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
  8918. /* We have a rtpmap to handle */
  8919. if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
  8920. /* Note: should really look at the '#chans' params too */
  8921. if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
  8922. if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
  8923. if (debug)
  8924. ast_verbose("Found video description format %s for ID %u\n", mimeSubtype, codec);
  8925. //found_rtpmap_codecs[last_rtpmap_codec] = codec;
  8926. (*last_rtpmap_codec)++;
  8927. found = TRUE;
  8928. } else {
  8929. ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
  8930. if (debug)
  8931. ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
  8932. }
  8933. }
  8934. } else {
  8935. if (debug)
  8936. ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
  8937. }
  8938. }
  8939. return found;
  8940. }
  8941. 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)
  8942. {
  8943. int found = FALSE;
  8944. unsigned int codec;
  8945. char mimeSubtype[128];
  8946. unsigned int sample_rate;
  8947. char *red_cp;
  8948. int debug = sip_debug_test_pvt(p);
  8949. if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
  8950. /* We have a rtpmap to handle */
  8951. if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
  8952. if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
  8953. if (p->trtp) {
  8954. /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
  8955. ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
  8956. found = TRUE;
  8957. }
  8958. } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
  8959. if (p->trtp) {
  8960. ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
  8961. sprintf(red_fmtp, "fmtp:%u ", codec);
  8962. if (debug)
  8963. ast_verbose("RED submimetype has payload type: %u\n", codec);
  8964. found = TRUE;
  8965. }
  8966. }
  8967. } else {
  8968. if (debug)
  8969. ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
  8970. }
  8971. } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
  8972. /* count numbers of generations in fmtp */
  8973. red_cp = &red_fmtp[strlen(red_fmtp)];
  8974. strncpy(red_fmtp, a, 100);
  8975. sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
  8976. red_cp = strtok(red_cp, "/");
  8977. while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
  8978. sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
  8979. red_cp = strtok(NULL, "/");
  8980. }
  8981. red_cp = red_fmtp;
  8982. found = TRUE;
  8983. }
  8984. return found;
  8985. }
  8986. static int process_sdp_a_image(const char *a, struct sip_pvt *p)
  8987. {
  8988. int found = FALSE;
  8989. char s[256];
  8990. unsigned int x;
  8991. char *attrib = ast_strdupa(a);
  8992. char *pos;
  8993. if (initialize_udptl(p)) {
  8994. return found;
  8995. }
  8996. /* Due to a typo in an IANA registration of one of the T.38 attributes,
  8997. * RFC5347 section 2.5.2 recommends that all T.38 attributes be parsed in
  8998. * a case insensitive manner. Hence, the importance of proof reading (and
  8999. * code reviews).
  9000. */
  9001. for (pos = attrib; *pos; ++pos) {
  9002. *pos = tolower(*pos);
  9003. }
  9004. if ((sscanf(attrib, "t38faxmaxbuffer:%30u", &x) == 1)) {
  9005. ast_debug(3, "MaxBufferSize:%u\n", x);
  9006. found = TRUE;
  9007. } else if ((sscanf(attrib, "t38maxbitrate:%30u", &x) == 1) || (sscanf(attrib, "t38faxmaxrate:%30u", &x) == 1)) {
  9008. ast_debug(3, "T38MaxBitRate: %u\n", x);
  9009. switch (x) {
  9010. case 14400:
  9011. p->t38.their_parms.rate = AST_T38_RATE_14400;
  9012. break;
  9013. case 12000:
  9014. p->t38.their_parms.rate = AST_T38_RATE_12000;
  9015. break;
  9016. case 9600:
  9017. p->t38.their_parms.rate = AST_T38_RATE_9600;
  9018. break;
  9019. case 7200:
  9020. p->t38.their_parms.rate = AST_T38_RATE_7200;
  9021. break;
  9022. case 4800:
  9023. p->t38.their_parms.rate = AST_T38_RATE_4800;
  9024. break;
  9025. case 2400:
  9026. p->t38.their_parms.rate = AST_T38_RATE_2400;
  9027. break;
  9028. }
  9029. found = TRUE;
  9030. } else if ((sscanf(attrib, "t38faxversion:%30u", &x) == 1)) {
  9031. ast_debug(3, "FaxVersion: %u\n", x);
  9032. p->t38.their_parms.version = x;
  9033. found = TRUE;
  9034. } else if ((sscanf(attrib, "t38faxmaxdatagram:%30u", &x) == 1) || (sscanf(attrib, "t38maxdatagram:%30u", &x) == 1)) {
  9035. /* override the supplied value if the configuration requests it */
  9036. if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
  9037. ast_debug(1, "Overriding T38FaxMaxDatagram '%u' with '%u'\n", x, p->t38_maxdatagram);
  9038. x = p->t38_maxdatagram;
  9039. }
  9040. ast_debug(3, "FaxMaxDatagram: %u\n", x);
  9041. ast_udptl_set_far_max_datagram(p->udptl, x);
  9042. found = TRUE;
  9043. } else if ((strncmp(attrib, "t38faxfillbitremoval", 20) == 0)) {
  9044. if (sscanf(attrib, "t38faxfillbitremoval:%30u", &x) == 1) {
  9045. ast_debug(3, "FillBitRemoval: %u\n", x);
  9046. if (x == 1) {
  9047. p->t38.their_parms.fill_bit_removal = TRUE;
  9048. }
  9049. } else {
  9050. ast_debug(3, "FillBitRemoval\n");
  9051. p->t38.their_parms.fill_bit_removal = TRUE;
  9052. }
  9053. found = TRUE;
  9054. } else if ((strncmp(attrib, "t38faxtranscodingmmr", 20) == 0)) {
  9055. if (sscanf(attrib, "t38faxtranscodingmmr:%30u", &x) == 1) {
  9056. ast_debug(3, "Transcoding MMR: %u\n", x);
  9057. if (x == 1) {
  9058. p->t38.their_parms.transcoding_mmr = TRUE;
  9059. }
  9060. } else {
  9061. ast_debug(3, "Transcoding MMR\n");
  9062. p->t38.their_parms.transcoding_mmr = TRUE;
  9063. }
  9064. found = TRUE;
  9065. } else if ((strncmp(attrib, "t38faxtranscodingjbig", 21) == 0)) {
  9066. if (sscanf(attrib, "t38faxtranscodingjbig:%30u", &x) == 1) {
  9067. ast_debug(3, "Transcoding JBIG: %u\n", x);
  9068. if (x == 1) {
  9069. p->t38.their_parms.transcoding_jbig = TRUE;
  9070. }
  9071. } else {
  9072. ast_debug(3, "Transcoding JBIG\n");
  9073. p->t38.their_parms.transcoding_jbig = TRUE;
  9074. }
  9075. found = TRUE;
  9076. } else if ((sscanf(attrib, "t38faxratemanagement:%255s", s) == 1)) {
  9077. ast_debug(3, "RateManagement: %s\n", s);
  9078. if (!strcasecmp(s, "localTCF"))
  9079. p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
  9080. else if (!strcasecmp(s, "transferredTCF"))
  9081. p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
  9082. found = TRUE;
  9083. } else if ((sscanf(attrib, "t38faxudpec:%255s", s) == 1)) {
  9084. ast_debug(3, "UDP EC: %s\n", s);
  9085. if (!strcasecmp(s, "t38UDPRedundancy")) {
  9086. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
  9087. } else if (!strcasecmp(s, "t38UDPFEC")) {
  9088. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
  9089. } else {
  9090. ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
  9091. }
  9092. found = TRUE;
  9093. }
  9094. return found;
  9095. }
  9096. /*! \brief Add "Supported" header to sip message. Since some options may
  9097. * be disabled in the config, the sip_pvt must be inspected to determine what
  9098. * is supported for this dialog. */
  9099. static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
  9100. {
  9101. int res;
  9102. if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
  9103. res = add_header(req, "Supported", "replaces, timer");
  9104. } else {
  9105. res = add_header(req, "Supported", "replaces");
  9106. }
  9107. return res;
  9108. }
  9109. /*! \brief Add header to SIP message */
  9110. static int add_header(struct sip_request *req, const char *var, const char *value)
  9111. {
  9112. if (req->headers == SIP_MAX_HEADERS) {
  9113. ast_log(LOG_WARNING, "Out of SIP header space\n");
  9114. return -1;
  9115. }
  9116. if (req->lines) {
  9117. ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
  9118. return -1;
  9119. }
  9120. if (sip_cfg.compactheaders) {
  9121. var = find_alias(var, var);
  9122. }
  9123. ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
  9124. req->header[req->headers] = ast_str_strlen(req->data);
  9125. req->headers++;
  9126. return 0;
  9127. }
  9128. /*!
  9129. * \pre dialog is assumed to be locked while calling this function
  9130. * \brief Add 'Max-Forwards' header to SIP message
  9131. */
  9132. static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
  9133. {
  9134. char clen[10];
  9135. snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
  9136. return add_header(req, "Max-Forwards", clen);
  9137. }
  9138. /*! \brief Add 'Content-Length' header and content to SIP message */
  9139. static int finalize_content(struct sip_request *req)
  9140. {
  9141. char clen[10];
  9142. if (req->lines) {
  9143. ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
  9144. return -1;
  9145. }
  9146. snprintf(clen, sizeof(clen), "%zu", ast_str_strlen(req->content));
  9147. add_header(req, "Content-Length", clen);
  9148. if (ast_str_strlen(req->content)) {
  9149. ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
  9150. }
  9151. req->lines = ast_str_strlen(req->content) ? 1 : 0;
  9152. return 0;
  9153. }
  9154. /*! \brief Add content (not header) to SIP message */
  9155. static int add_content(struct sip_request *req, const char *line)
  9156. {
  9157. if (req->lines) {
  9158. ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
  9159. return -1;
  9160. }
  9161. ast_str_append(&req->content, 0, "%s", line);
  9162. return 0;
  9163. }
  9164. /*! \brief Copy one header field from one request to another */
  9165. static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
  9166. {
  9167. const char *tmp = get_header(orig, field);
  9168. if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
  9169. return add_header(req, field, tmp);
  9170. ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
  9171. return -1;
  9172. }
  9173. /*! \brief Copy all headers from one request to another */
  9174. static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
  9175. {
  9176. int start = 0;
  9177. int copied = 0;
  9178. for (;;) {
  9179. const char *tmp = __get_header(orig, field, &start);
  9180. if (ast_strlen_zero(tmp))
  9181. break;
  9182. /* Add what we're responding to */
  9183. add_header(req, field, tmp);
  9184. copied++;
  9185. }
  9186. return copied ? 0 : -1;
  9187. }
  9188. /*! \brief Copy SIP VIA Headers from the request to the response
  9189. \note If the client indicates that it wishes to know the port we received from,
  9190. it adds ;rport without an argument to the topmost via header. We need to
  9191. add the port number (from our point of view) to that parameter.
  9192. \verbatim
  9193. We always add ;received=<ip address> to the topmost via header.
  9194. \endverbatim
  9195. Received: RFC 3261, rport RFC 3581 */
  9196. static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
  9197. {
  9198. int copied = 0;
  9199. int start = 0;
  9200. for (;;) {
  9201. char new[512];
  9202. const char *oh = __get_header(orig, field, &start);
  9203. if (ast_strlen_zero(oh))
  9204. break;
  9205. if (!copied) { /* Only check for empty rport in topmost via header */
  9206. char leftmost[512], *others, *rport;
  9207. /* Only work on leftmost value */
  9208. ast_copy_string(leftmost, oh, sizeof(leftmost));
  9209. others = strchr(leftmost, ',');
  9210. if (others)
  9211. *others++ = '\0';
  9212. /* Find ;rport; (empty request) */
  9213. rport = strstr(leftmost, ";rport");
  9214. if (rport && *(rport+6) == '=')
  9215. rport = NULL; /* We already have a parameter to rport */
  9216. if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
  9217. /* We need to add received port - rport */
  9218. char *end;
  9219. rport = strstr(leftmost, ";rport");
  9220. if (rport) {
  9221. end = strchr(rport + 1, ';');
  9222. if (end)
  9223. memmove(rport, end, strlen(end) + 1);
  9224. else
  9225. *rport = '\0';
  9226. }
  9227. /* Add rport to first VIA header if requested */
  9228. snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
  9229. leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
  9230. ast_sockaddr_port(&p->recv),
  9231. others ? "," : "", others ? others : "");
  9232. } else {
  9233. /* We should *always* add a received to the topmost via */
  9234. snprintf(new, sizeof(new), "%s;received=%s%s%s",
  9235. leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
  9236. others ? "," : "", others ? others : "");
  9237. }
  9238. oh = new; /* the header to copy */
  9239. } /* else add the following via headers untouched */
  9240. add_header(req, field, oh);
  9241. copied++;
  9242. }
  9243. if (!copied) {
  9244. ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
  9245. return -1;
  9246. }
  9247. return 0;
  9248. }
  9249. /*! \brief Add route header into request per learned route */
  9250. static void add_route(struct sip_request *req, struct sip_route *route)
  9251. {
  9252. char r[SIPBUFSIZE*2], *p;
  9253. int n, rem = sizeof(r);
  9254. if (!route)
  9255. return;
  9256. p = r;
  9257. for (;route ; route = route->next) {
  9258. n = strlen(route->hop);
  9259. if (rem < n+3) /* we need room for ",<route>" */
  9260. break;
  9261. if (p != r) { /* add a separator after fist route */
  9262. *p++ = ',';
  9263. --rem;
  9264. }
  9265. *p++ = '<';
  9266. ast_copy_string(p, route->hop, rem); /* cannot fail */
  9267. p += n;
  9268. *p++ = '>';
  9269. rem -= (n+2);
  9270. }
  9271. *p = '\0';
  9272. add_header(req, "Route", r);
  9273. }
  9274. /*! \brief Set destination from SIP URI
  9275. *
  9276. * Parse uri to h (host) and port - uri is already just the part inside the <>
  9277. * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
  9278. * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
  9279. * for SIP: uri's
  9280. *
  9281. * If there's a sips: uri scheme, TLS will be required.
  9282. */
  9283. static void set_destination(struct sip_pvt *p, char *uri)
  9284. {
  9285. char *h, *maddr, hostname[256];
  9286. int hn;
  9287. int debug=sip_debug_test_pvt(p);
  9288. int tls_on = FALSE;
  9289. if (debug)
  9290. ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
  9291. /* Find and parse hostname */
  9292. h = strchr(uri, '@');
  9293. if (h)
  9294. ++h;
  9295. else {
  9296. h = uri;
  9297. if (!strncasecmp(h, "sip:", 4)) {
  9298. h += 4;
  9299. } else if (!strncasecmp(h, "sips:", 5)) {
  9300. h += 5;
  9301. tls_on = TRUE;
  9302. }
  9303. }
  9304. hn = strcspn(h, ";>") + 1;
  9305. if (hn > sizeof(hostname))
  9306. hn = sizeof(hostname);
  9307. ast_copy_string(hostname, h, hn);
  9308. /* XXX bug here if string has been trimmed to sizeof(hostname) */
  9309. h += hn - 1;
  9310. /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
  9311. * otherwise, just look for A records */
  9312. if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
  9313. ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
  9314. return;
  9315. }
  9316. /* Got the hostname - but maybe there's a "maddr=" to override address? */
  9317. maddr = strstr(h, "maddr=");
  9318. if (maddr) {
  9319. int port;
  9320. maddr += 6;
  9321. hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  9322. "0123456789-.:[]") + 1;
  9323. if (hn > sizeof(hostname))
  9324. hn = sizeof(hostname);
  9325. ast_copy_string(hostname, maddr, hn);
  9326. port = ast_sockaddr_port(&p->sa);
  9327. /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
  9328. * NAPTR/SRV, otherwise, just look for A records */
  9329. if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
  9330. ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
  9331. return;
  9332. }
  9333. ast_sockaddr_set_port(&p->sa, port);
  9334. }
  9335. if (!ast_sockaddr_port(&p->sa)) {
  9336. ast_sockaddr_set_port(&p->sa, tls_on ?
  9337. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  9338. }
  9339. if (debug) {
  9340. ast_verbose("set_destination: set destination to %s\n",
  9341. ast_sockaddr_stringify(&p->sa));
  9342. }
  9343. }
  9344. /*! \brief Initialize SIP response, based on SIP request */
  9345. static int init_resp(struct sip_request *resp, const char *msg)
  9346. {
  9347. /* Initialize a response */
  9348. memset(resp, 0, sizeof(*resp));
  9349. resp->method = SIP_RESPONSE;
  9350. if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
  9351. goto e_return;
  9352. if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
  9353. goto e_free_data;
  9354. resp->header[0] = 0;
  9355. ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
  9356. resp->headers++;
  9357. return 0;
  9358. e_free_data:
  9359. ast_free(resp->data);
  9360. resp->data = NULL;
  9361. e_return:
  9362. return -1;
  9363. }
  9364. /*! \brief Initialize SIP request */
  9365. static int init_req(struct sip_request *req, int sipmethod, const char *recip)
  9366. {
  9367. /* Initialize a request */
  9368. memset(req, 0, sizeof(*req));
  9369. if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
  9370. goto e_return;
  9371. if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
  9372. goto e_free_data;
  9373. req->method = sipmethod;
  9374. req->header[0] = 0;
  9375. ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
  9376. req->headers++;
  9377. return 0;
  9378. e_free_data:
  9379. ast_free(req->data);
  9380. req->data = NULL;
  9381. e_return:
  9382. return -1;
  9383. }
  9384. /*! \brief Deinitialize SIP response/request */
  9385. static void deinit_req(struct sip_request *req)
  9386. {
  9387. if (req->data) {
  9388. ast_free(req->data);
  9389. req->data = NULL;
  9390. }
  9391. if (req->content) {
  9392. ast_free(req->content);
  9393. req->content = NULL;
  9394. }
  9395. }
  9396. /*! \brief Test if this response needs a contact header */
  9397. static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
  9398. /* Requirements for Contact header inclusion in responses generated
  9399. * from the header tables found in the following RFCs. Where the
  9400. * Contact header was marked mandatory (m) or optional (o) this
  9401. * function returns 1.
  9402. *
  9403. * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
  9404. * - RFC 2976 (INFO)
  9405. * - RFC 3262 (PRACK)
  9406. * - RFC 3265 (SUBSCRIBE, NOTIFY)
  9407. * - RFC 3311 (UPDATE)
  9408. * - RFC 3428 (MESSAGE)
  9409. * - RFC 3515 (REFER)
  9410. * - RFC 3903 (PUBLISH)
  9411. */
  9412. switch (method) {
  9413. /* 1xx, 2xx, 3xx, 485 */
  9414. case SIP_INVITE:
  9415. case SIP_UPDATE:
  9416. case SIP_SUBSCRIBE:
  9417. case SIP_NOTIFY:
  9418. if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
  9419. return 1;
  9420. break;
  9421. /* 2xx, 3xx, 485 */
  9422. case SIP_REGISTER:
  9423. case SIP_OPTIONS:
  9424. if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
  9425. return 1;
  9426. break;
  9427. /* 3xx, 485 */
  9428. case SIP_BYE:
  9429. case SIP_PRACK:
  9430. case SIP_MESSAGE:
  9431. case SIP_PUBLISH:
  9432. if (msg[0] == '3' || !strncmp(msg, "485", 3))
  9433. return 1;
  9434. break;
  9435. /* 2xx, 3xx, 4xx, 5xx, 6xx */
  9436. case SIP_REFER:
  9437. if (msg[0] >= '2' && msg[0] <= '6')
  9438. return 1;
  9439. break;
  9440. /* contact will not be included for everything else */
  9441. case SIP_ACK:
  9442. case SIP_CANCEL:
  9443. case SIP_INFO:
  9444. case SIP_PING:
  9445. default:
  9446. return 0;
  9447. }
  9448. return 0;
  9449. }
  9450. /*! \brief Prepare SIP response packet */
  9451. static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
  9452. {
  9453. char newto[256];
  9454. const char *ot;
  9455. init_resp(resp, msg);
  9456. copy_via_headers(p, resp, req, "Via");
  9457. if (msg[0] == '1' || msg[0] == '2')
  9458. copy_all_header(resp, req, "Record-Route");
  9459. copy_header(resp, req, "From");
  9460. ot = get_header(req, "To");
  9461. if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
  9462. /* Add the proper tag if we don't have it already. If they have specified
  9463. their tag, use it. Otherwise, use our own tag */
  9464. if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
  9465. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
  9466. else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
  9467. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
  9468. else
  9469. ast_copy_string(newto, ot, sizeof(newto));
  9470. ot = newto;
  9471. }
  9472. add_header(resp, "To", ot);
  9473. copy_header(resp, req, "Call-ID");
  9474. copy_header(resp, req, "CSeq");
  9475. if (!ast_strlen_zero(global_useragent))
  9476. add_header(resp, "Server", global_useragent);
  9477. add_header(resp, "Allow", ALLOWED_METHODS);
  9478. add_supported_header(p, resp);
  9479. /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
  9480. if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE) {
  9481. char se_hdr[256];
  9482. snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
  9483. p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
  9484. add_header(resp, "Session-Expires", se_hdr);
  9485. /* RFC 2048, Section 9
  9486. * If the refresher parameter in the Session-Expires header field in the
  9487. * 2xx response has a value of 'uac', the UAS MUST place a Require
  9488. * header field into the response with the value 'timer'.
  9489. * ...
  9490. * If the refresher parameter in
  9491. * the 2xx response has a value of 'uas' and the Supported header field
  9492. * in the request contained the value 'timer', the UAS SHOULD place a
  9493. * Require header field into the response with the value 'timer'
  9494. */
  9495. if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_THEM ||
  9496. (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US &&
  9497. p->stimer->st_active_peer_ua == TRUE)) {
  9498. resp->reqsipoptions |= SIP_OPT_TIMER;
  9499. }
  9500. }
  9501. if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
  9502. /* For registration responses, we also need expiry and
  9503. contact info */
  9504. char tmp[256];
  9505. snprintf(tmp, sizeof(tmp), "%d", p->expiry);
  9506. add_header(resp, "Expires", tmp);
  9507. if (p->expiry) { /* Only add contact if we have an expiry time */
  9508. char contact[SIPBUFSIZE];
  9509. const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
  9510. char *brackets = strchr(contact_uri, '<');
  9511. snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
  9512. add_header(resp, "Contact", contact); /* Not when we unregister */
  9513. }
  9514. } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
  9515. add_header(resp, "Contact", p->our_contact);
  9516. }
  9517. if (!ast_strlen_zero(p->url)) {
  9518. add_header(resp, "Access-URL", p->url);
  9519. ast_string_field_set(p, url, NULL);
  9520. }
  9521. /* default to routing the response to the address where the request
  9522. * came from. Since we don't have a transport layer, we do this here.
  9523. * The process_via() function will update the port to either the port
  9524. * specified in the via header or the default port later on (per RFC
  9525. * 3261 section 18.2.2).
  9526. */
  9527. p->sa = p->recv;
  9528. if (process_via(p, req)) {
  9529. ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
  9530. }
  9531. return 0;
  9532. }
  9533. /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
  9534. static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
  9535. {
  9536. struct sip_request *orig = &p->initreq;
  9537. char stripped[80];
  9538. char tmp[80];
  9539. char newto[256];
  9540. const char *c;
  9541. const char *ot, *of;
  9542. int is_strict = FALSE; /*!< Strict routing flag */
  9543. int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING); /* Session direction */
  9544. snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
  9545. if (!seqno) {
  9546. p->ocseq++;
  9547. seqno = p->ocseq;
  9548. }
  9549. /* A CANCEL must have the same branch as the INVITE that it is canceling. */
  9550. if (sipmethod == SIP_CANCEL) {
  9551. p->branch = p->invite_branch;
  9552. build_via(p);
  9553. } else if (newbranch && (sipmethod == SIP_INVITE)) {
  9554. p->branch ^= ast_random();
  9555. p->invite_branch = p->branch;
  9556. build_via(p);
  9557. } else if (newbranch) {
  9558. p->branch ^= ast_random();
  9559. build_via(p);
  9560. }
  9561. /* Check for strict or loose router */
  9562. if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
  9563. is_strict = TRUE;
  9564. if (sipdebug)
  9565. ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
  9566. }
  9567. if (sipmethod == SIP_CANCEL)
  9568. c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
  9569. else if (sipmethod == SIP_ACK) {
  9570. /* Use URI from Contact: in 200 OK (if INVITE)
  9571. (we only have the contacturi on INVITEs) */
  9572. if (!ast_strlen_zero(p->okcontacturi))
  9573. c = is_strict ? p->route->hop : p->okcontacturi;
  9574. else
  9575. c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
  9576. } else if (!ast_strlen_zero(p->okcontacturi))
  9577. c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
  9578. else if (!ast_strlen_zero(p->uri))
  9579. c = p->uri;
  9580. else {
  9581. char *n;
  9582. /* We have no URI, use To: or From: header as URI (depending on direction) */
  9583. ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
  9584. sizeof(stripped));
  9585. n = get_in_brackets(stripped);
  9586. c = remove_uri_parameters(n);
  9587. }
  9588. init_req(req, sipmethod, c);
  9589. snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
  9590. add_header(req, "Via", p->via);
  9591. /*
  9592. * Use the learned route set unless this is a CANCEL on an ACK for a non-2xx
  9593. * final response. For a CANCEL or ACK, we have to send to the same destination
  9594. * as the original INVITE.
  9595. */
  9596. if (p->route &&
  9597. !(sipmethod == SIP_CANCEL ||
  9598. (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)))) {
  9599. set_destination(p, p->route->hop);
  9600. add_route(req, is_strict ? p->route->next : p->route);
  9601. }
  9602. add_header_max_forwards(p, req);
  9603. ot = get_header(orig, "To");
  9604. of = get_header(orig, "From");
  9605. /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
  9606. as our original request, including tag (or presumably lack thereof) */
  9607. if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
  9608. /* Add the proper tag if we don't have it already. If they have specified
  9609. their tag, use it. Otherwise, use our own tag */
  9610. if (is_outbound && !ast_strlen_zero(p->theirtag))
  9611. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
  9612. else if (!is_outbound)
  9613. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
  9614. else
  9615. snprintf(newto, sizeof(newto), "%s", ot);
  9616. ot = newto;
  9617. }
  9618. if (is_outbound) {
  9619. add_header(req, "From", of);
  9620. add_header(req, "To", ot);
  9621. } else {
  9622. add_header(req, "From", ot);
  9623. add_header(req, "To", of);
  9624. }
  9625. /* Do not add Contact for MESSAGE, BYE and Cancel requests */
  9626. if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
  9627. add_header(req, "Contact", p->our_contact);
  9628. copy_header(req, orig, "Call-ID");
  9629. add_header(req, "CSeq", tmp);
  9630. if (!ast_strlen_zero(global_useragent))
  9631. add_header(req, "User-Agent", global_useragent);
  9632. if (!ast_strlen_zero(p->url)) {
  9633. add_header(req, "Access-URL", p->url);
  9634. ast_string_field_set(p, url, NULL);
  9635. }
  9636. /* Add Session-Timers related headers if the feature is active for this session.
  9637. An exception to this behavior is the ACK request. Since Asterisk never requires
  9638. session-timers support from a remote end-point (UAS) in an INVITE, it must
  9639. not send 'Require: timer' header in the ACK request.
  9640. This should only be added in the INVITE transactions, not MESSAGE or REFER or other
  9641. in-dialog messages.
  9642. */
  9643. if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
  9644. && sipmethod == SIP_INVITE) {
  9645. char se_hdr[256];
  9646. snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
  9647. p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
  9648. add_header(req, "Session-Expires", se_hdr);
  9649. snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
  9650. add_header(req, "Min-SE", se_hdr);
  9651. }
  9652. return 0;
  9653. }
  9654. /*! \brief Base transmit response function */
  9655. static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
  9656. {
  9657. struct sip_request resp;
  9658. uint32_t seqno = 0;
  9659. if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
  9660. ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
  9661. return -1;
  9662. }
  9663. respprep(&resp, p, msg, req);
  9664. if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
  9665. && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
  9666. && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
  9667. ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  9668. add_rpid(&resp, p);
  9669. }
  9670. if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
  9671. add_cc_call_info_to_response(p, &resp);
  9672. }
  9673. /* If we are sending a 302 Redirect we can add a diversion header if the redirect information is set */
  9674. if (!strncmp(msg, "302", 3)) {
  9675. add_diversion_header(&resp, p);
  9676. }
  9677. /* If we are cancelling an incoming invite for some reason, add information
  9678. about the reason why we are doing this in clear text */
  9679. if (p->method == SIP_INVITE && msg[0] != '1') {
  9680. char buf[20];
  9681. if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
  9682. int hangupcause = 0;
  9683. if (p->owner && p->owner->hangupcause) {
  9684. hangupcause = p->owner->hangupcause;
  9685. } else if (p->hangupcause) {
  9686. hangupcause = p->hangupcause;
  9687. } else {
  9688. int respcode;
  9689. if (sscanf(msg, "%30d ", &respcode))
  9690. hangupcause = hangup_sip2cause(respcode);
  9691. }
  9692. if (hangupcause) {
  9693. sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
  9694. add_header(&resp, "Reason", buf);
  9695. }
  9696. }
  9697. if (p->owner && p->owner->hangupcause) {
  9698. add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
  9699. snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
  9700. add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
  9701. }
  9702. }
  9703. return send_response(p, &resp, reliable, seqno);
  9704. }
  9705. 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)
  9706. {
  9707. struct sip_request resp;
  9708. if (need_new_etag) {
  9709. create_new_sip_etag(esc_entry, 1);
  9710. }
  9711. respprep(&resp, p, msg, req);
  9712. add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
  9713. return send_response(p, &resp, 0, 0);
  9714. }
  9715. static int temp_pvt_init(void *data)
  9716. {
  9717. struct sip_pvt *p = data;
  9718. p->do_history = 0; /* XXX do we need it ? isn't already all 0 ? */
  9719. return ast_string_field_init(p, 512);
  9720. }
  9721. static void temp_pvt_cleanup(void *data)
  9722. {
  9723. struct sip_pvt *p = data;
  9724. ast_string_field_free_memory(p);
  9725. ast_free(data);
  9726. }
  9727. /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
  9728. 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)
  9729. {
  9730. struct sip_pvt *p = NULL;
  9731. if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
  9732. ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
  9733. return -1;
  9734. }
  9735. /* XXX the structure may be dirty from previous usage.
  9736. * Here we should state clearly how we should reinitialize it
  9737. * before using it.
  9738. * E.g. certainly the threadstorage should be left alone,
  9739. * but other thihngs such as flags etc. maybe need cleanup ?
  9740. */
  9741. /* Initialize the bare minimum */
  9742. p->method = intended_method;
  9743. if (!addr) {
  9744. ast_sockaddr_copy(&p->ourip, &internip);
  9745. } else {
  9746. ast_sockaddr_copy(&p->sa, addr);
  9747. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  9748. }
  9749. p->branch = ast_random();
  9750. make_our_tag(p);
  9751. p->ocseq = INITIAL_CSEQ;
  9752. if (useglobal_nat && addr) {
  9753. ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
  9754. ast_sockaddr_copy(&p->recv, addr);
  9755. do_setnat(p);
  9756. }
  9757. ast_string_field_set(p, fromdomain, default_fromdomain);
  9758. p->fromdomainport = default_fromdomainport;
  9759. build_via(p);
  9760. ast_string_field_set(p, callid, callid);
  9761. copy_socket_data(&p->socket, &req->socket);
  9762. /* Use this temporary pvt structure to send the message */
  9763. __transmit_response(p, msg, req, XMIT_UNRELIABLE);
  9764. /* Free the string fields, but not the pool space */
  9765. ast_string_field_init(p, 0);
  9766. return 0;
  9767. }
  9768. /*! \brief Transmit response, no retransmits */
  9769. static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
  9770. {
  9771. return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
  9772. }
  9773. /*! \brief Transmit response, no retransmits */
  9774. static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
  9775. {
  9776. struct sip_request resp;
  9777. respprep(&resp, p, msg, req);
  9778. append_date(&resp);
  9779. add_header(&resp, "Unsupported", unsupported);
  9780. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  9781. }
  9782. /*! \brief Transmit 422 response with Min-SE header (Session-Timers) */
  9783. static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
  9784. {
  9785. struct sip_request resp;
  9786. char minse_str[20];
  9787. respprep(&resp, p, msg, req);
  9788. append_date(&resp);
  9789. snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
  9790. add_header(&resp, "Min-SE", minse_str);
  9791. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  9792. }
  9793. /*! \brief Transmit response, Make sure you get an ACK
  9794. This is only used for responses to INVITEs, where we need to make sure we get an ACK
  9795. */
  9796. static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
  9797. {
  9798. return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
  9799. }
  9800. /*! \brief Append date to SIP message */
  9801. static void append_date(struct sip_request *req)
  9802. {
  9803. char tmpdat[256];
  9804. struct tm tm;
  9805. time_t t = time(NULL);
  9806. gmtime_r(&t, &tm);
  9807. strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
  9808. add_header(req, "Date", tmpdat);
  9809. }
  9810. /*! \brief Append Retry-After header field when transmitting response */
  9811. static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
  9812. {
  9813. struct sip_request resp;
  9814. respprep(&resp, p, msg, req);
  9815. add_header(&resp, "Retry-After", seconds);
  9816. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  9817. }
  9818. /*! \brief Append date and content length before transmitting response */
  9819. static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
  9820. {
  9821. struct sip_request resp;
  9822. respprep(&resp, p, msg, req);
  9823. append_date(&resp);
  9824. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  9825. }
  9826. /*! \brief Append Accept header, content length before transmitting response */
  9827. static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
  9828. {
  9829. struct sip_request resp;
  9830. respprep(&resp, p, msg, req);
  9831. add_header(&resp, "Accept", "application/sdp");
  9832. return send_response(p, &resp, reliable, 0);
  9833. }
  9834. /*! \brief Append Min-Expires header, content length before transmitting response */
  9835. static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
  9836. {
  9837. struct sip_request resp;
  9838. char tmp[32];
  9839. snprintf(tmp, sizeof(tmp), "%d", min_expiry);
  9840. respprep(&resp, p, msg, req);
  9841. add_header(&resp, "Min-Expires", tmp);
  9842. return send_response(p, &resp, XMIT_UNRELIABLE, 0);
  9843. }
  9844. /*! \brief Respond with authorization request */
  9845. static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *randdata, enum xmittype reliable, const char *header, int stale)
  9846. {
  9847. struct sip_request resp;
  9848. char tmp[512];
  9849. uint32_t seqno = 0;
  9850. if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
  9851. ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
  9852. return -1;
  9853. }
  9854. /* Choose Realm */
  9855. get_realm(p, req);
  9856. /* Stale means that they sent us correct authentication, but
  9857. based it on an old challenge (nonce) */
  9858. snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
  9859. respprep(&resp, p, msg, req);
  9860. add_header(&resp, header, tmp);
  9861. append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
  9862. return send_response(p, &resp, reliable, seqno);
  9863. }
  9864. /*!
  9865. \brief Extract domain from SIP To/From header
  9866. \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
  9867. \note TODO: Such code is all over SIP channel, there is a sense to organize
  9868. this patern in one function
  9869. */
  9870. static int get_domain(const char *str, char *domain, int len)
  9871. {
  9872. char tmpf[256];
  9873. char *a, *from;
  9874. *domain = '\0';
  9875. ast_copy_string(tmpf, str, sizeof(tmpf));
  9876. from = get_in_brackets(tmpf);
  9877. if (!ast_strlen_zero(from)) {
  9878. if (strncasecmp(from, "sip:", 4)) {
  9879. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
  9880. return -1;
  9881. }
  9882. from += 4;
  9883. } else
  9884. from = NULL;
  9885. if (from) {
  9886. int bracket = 0;
  9887. /* Strip any params or options from user */
  9888. if ((a = strchr(from, ';')))
  9889. *a = '\0';
  9890. /* Strip port from domain if present */
  9891. for (a = from; *a != '\0'; ++a) {
  9892. if (*a == ':' && bracket == 0) {
  9893. *a = '\0';
  9894. break;
  9895. } else if (*a == '[') {
  9896. ++bracket;
  9897. } else if (*a == ']') {
  9898. --bracket;
  9899. }
  9900. }
  9901. if ((a = strchr(from, '@'))) {
  9902. *a = '\0';
  9903. ast_copy_string(domain, a + 1, len);
  9904. } else
  9905. ast_copy_string(domain, from, len);
  9906. }
  9907. return ast_strlen_zero(domain);
  9908. }
  9909. /*!
  9910. \brief Choose realm based on From header and then To header or use globaly configured realm.
  9911. Realm from From/To header should be listed among served domains in config file: domain=...
  9912. */
  9913. static void get_realm(struct sip_pvt *p, const struct sip_request *req)
  9914. {
  9915. char domain[MAXHOSTNAMELEN];
  9916. if (!ast_strlen_zero(p->realm))
  9917. return;
  9918. if (sip_cfg.domainsasrealm &&
  9919. !AST_LIST_EMPTY(&domain_list))
  9920. {
  9921. /* Check From header first */
  9922. if (!get_domain(get_header(req, "From"), domain, sizeof(domain))) {
  9923. if (check_sip_domain(domain, NULL, 0)) {
  9924. ast_string_field_set(p, realm, domain);
  9925. return;
  9926. }
  9927. }
  9928. /* Check To header */
  9929. if (!get_domain(get_header(req, "To"), domain, sizeof(domain))) {
  9930. if (check_sip_domain(domain, NULL, 0)) {
  9931. ast_string_field_set(p, realm, domain);
  9932. return;
  9933. }
  9934. }
  9935. }
  9936. /* Use default realm from config file */
  9937. ast_string_field_set(p, realm, sip_cfg.realm);
  9938. }
  9939. /*!
  9940. * \internal
  9941. *
  9942. * \arg msg Only use a string constant for the msg, here, it is shallow copied
  9943. *
  9944. * \note assumes the sip_pvt is locked.
  9945. */
  9946. static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
  9947. {
  9948. int res;
  9949. if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
  9950. p->last_provisional = msg;
  9951. update_provisional_keepalive(p, with_sdp);
  9952. }
  9953. return res;
  9954. }
  9955. /*! \brief Add text body to SIP message */
  9956. static int add_text(struct sip_request *req, const char *text)
  9957. {
  9958. /* XXX Convert \n's to \r\n's XXX */
  9959. add_header(req, "Content-Type", "text/plain;charset=UTF-8");
  9960. add_content(req, text);
  9961. return 0;
  9962. }
  9963. /*! \brief Add DTMF INFO tone to sip message
  9964. Mode = 0 for application/dtmf-relay (Cisco)
  9965. 1 for application/dtmf
  9966. */
  9967. static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
  9968. {
  9969. char tmp[256];
  9970. int event;
  9971. if (mode) {
  9972. /* Application/dtmf short version used by some implementations */
  9973. if ('0' <= digit && digit <= '9') {
  9974. event = digit - '0';
  9975. } else if (digit == '*') {
  9976. event = 10;
  9977. } else if (digit == '#') {
  9978. event = 11;
  9979. } else if ('A' <= digit && digit <= 'D') {
  9980. event = 12 + digit - 'A';
  9981. } else if ('a' <= digit && digit <= 'd') {
  9982. event = 12 + digit - 'a';
  9983. } else {
  9984. /* Unknown digit */
  9985. event = 0;
  9986. }
  9987. snprintf(tmp, sizeof(tmp), "%d\r\n", event);
  9988. add_header(req, "Content-Type", "application/dtmf");
  9989. add_content(req, tmp);
  9990. } else {
  9991. /* Application/dtmf-relay as documented by Cisco */
  9992. snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
  9993. add_header(req, "Content-Type", "application/dtmf-relay");
  9994. add_content(req, tmp);
  9995. }
  9996. return 0;
  9997. }
  9998. /*!
  9999. * \pre if p->owner exists, it must be locked
  10000. * \brief Add Remote-Party-ID header to SIP message
  10001. */
  10002. static int add_rpid(struct sip_request *req, struct sip_pvt *p)
  10003. {
  10004. struct ast_str *tmp = ast_str_alloca(256);
  10005. char tmp2[256];
  10006. char lid_name_buf[128];
  10007. char *lid_num;
  10008. char *lid_name;
  10009. int lid_pres;
  10010. const char *fromdomain;
  10011. const char *privacy = NULL;
  10012. const char *screen = NULL;
  10013. const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
  10014. if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
  10015. return 0;
  10016. }
  10017. if (!p->owner) {
  10018. return 0;
  10019. }
  10020. lid_num = S_COR(p->owner->connected.id.number.valid,
  10021. p->owner->connected.id.number.str,
  10022. NULL);
  10023. if (!lid_num) {
  10024. return 0;
  10025. }
  10026. lid_name = S_COR(p->owner->connected.id.name.valid,
  10027. p->owner->connected.id.name.str,
  10028. NULL);
  10029. if (!lid_name) {
  10030. lid_name = lid_num;
  10031. }
  10032. ast_escape_quoted(lid_name, lid_name_buf, sizeof(lid_name_buf));
  10033. lid_pres = ast_party_id_presentation(&p->owner->connected.id);
  10034. if (((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) &&
  10035. (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_NO)) {
  10036. /* If pres is not allowed and we don't trust the peer, we don't apply an RPID header */
  10037. return 0;
  10038. }
  10039. fromdomain = p->fromdomain;
  10040. if (!fromdomain ||
  10041. ((ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_YES) &&
  10042. !strcmp("anonymous.invalid", fromdomain))) {
  10043. /* If the fromdomain is NULL or if it was set to anonymous.invalid due to privacy settings and we trust the peer,
  10044. * use the host IP address */
  10045. fromdomain = ast_sockaddr_stringify_host_remote(&p->ourip);
  10046. }
  10047. lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), 0);
  10048. if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
  10049. if (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) != SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY) {
  10050. /* trust_id_outbound = yes - Always give full information even if it's private, but append a privacy header
  10051. * When private data is included */
  10052. ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name_buf, lid_num, fromdomain);
  10053. if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  10054. add_header(req, "Privacy", "id");
  10055. }
  10056. } else {
  10057. /* trust_id_outbound = legacy - behave in a non RFC-3325 compliant manner and send anonymized data when
  10058. * when handling private data. */
  10059. if ((lid_pres & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
  10060. ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name_buf, lid_num, fromdomain);
  10061. } else {
  10062. ast_str_set(&tmp, -1, "%s", anonymous_string);
  10063. }
  10064. }
  10065. add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
  10066. } else {
  10067. ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name_buf, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
  10068. switch (lid_pres) {
  10069. case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
  10070. case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
  10071. privacy = "off";
  10072. screen = "no";
  10073. break;
  10074. case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
  10075. case AST_PRES_ALLOWED_NETWORK_NUMBER:
  10076. privacy = "off";
  10077. screen = "yes";
  10078. break;
  10079. case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
  10080. case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
  10081. privacy = "full";
  10082. screen = "no";
  10083. break;
  10084. case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
  10085. case AST_PRES_PROHIB_NETWORK_NUMBER:
  10086. privacy = "full";
  10087. screen = "yes";
  10088. break;
  10089. case AST_PRES_NUMBER_NOT_AVAILABLE:
  10090. break;
  10091. default:
  10092. if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  10093. privacy = "full";
  10094. }
  10095. else
  10096. privacy = "off";
  10097. screen = "no";
  10098. break;
  10099. }
  10100. if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
  10101. ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
  10102. }
  10103. add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
  10104. }
  10105. return 0;
  10106. }
  10107. /*! \brief add XML encoded media control with update
  10108. \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
  10109. static int add_vidupdate(struct sip_request *req)
  10110. {
  10111. const char *xml_is_a_huge_waste_of_space =
  10112. "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
  10113. " <media_control>\r\n"
  10114. " <vc_primitive>\r\n"
  10115. " <to_encoder>\r\n"
  10116. " <picture_fast_update>\r\n"
  10117. " </picture_fast_update>\r\n"
  10118. " </to_encoder>\r\n"
  10119. " </vc_primitive>\r\n"
  10120. " </media_control>\r\n";
  10121. add_header(req, "Content-Type", "application/media_control+xml");
  10122. add_content(req, xml_is_a_huge_waste_of_space);
  10123. return 0;
  10124. }
  10125. /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
  10126. static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
  10127. struct ast_str **m_buf, struct ast_str **a_buf,
  10128. int debug, int *min_packet_size)
  10129. {
  10130. int rtp_code;
  10131. struct ast_format_list fmt;
  10132. if (debug)
  10133. ast_verbose("Adding codec 0x%" PRIx64 " (%s) to SDP\n", (uint64_t)codec, ast_getformatname(codec));
  10134. if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, codec)) == -1)
  10135. return;
  10136. if (p->rtp) {
  10137. struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
  10138. fmt = ast_codec_pref_getsize(pref, codec);
  10139. } else /* I don't see how you couldn't have p->rtp, but good to check for and error out if not there like earlier code */
  10140. return;
  10141. ast_str_append(m_buf, 0, " %d", rtp_code);
  10142. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
  10143. ast_rtp_lookup_mime_subtype2(1, codec,
  10144. ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
  10145. ast_rtp_lookup_sample_rate2(1, codec));
  10146. switch (codec) {
  10147. case AST_FORMAT_G729A:
  10148. /* Indicate that we don't support VAD (G.729 annex B) */
  10149. ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
  10150. break;
  10151. case AST_FORMAT_G723_1:
  10152. /* Indicate that we don't support VAD (G.723.1 annex A) */
  10153. ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
  10154. break;
  10155. case AST_FORMAT_ILBC:
  10156. /* Add information about us using only 20/30 ms packetization */
  10157. ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
  10158. break;
  10159. case AST_FORMAT_SIREN7:
  10160. /* Indicate that we only expect 32Kbps */
  10161. ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
  10162. break;
  10163. case AST_FORMAT_SIREN14:
  10164. /* Indicate that we only expect 48Kbps */
  10165. ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
  10166. break;
  10167. case AST_FORMAT_G719:
  10168. /* Indicate that we only expect 64Kbps */
  10169. ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
  10170. break;
  10171. }
  10172. if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
  10173. *min_packet_size = fmt.cur_ms;
  10174. /* Our first codec packetization processed cannot be zero */
  10175. if ((*min_packet_size)==0 && fmt.cur_ms)
  10176. *min_packet_size = fmt.cur_ms;
  10177. }
  10178. /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
  10179. /* This is different to the audio one now so we can add more caps later */
  10180. static void add_vcodec_to_sdp(const struct sip_pvt *p, format_t codec,
  10181. struct ast_str **m_buf, struct ast_str **a_buf,
  10182. int debug, int *min_packet_size)
  10183. {
  10184. int rtp_code;
  10185. if (!p->vrtp)
  10186. return;
  10187. if (debug)
  10188. ast_verbose("Adding video codec 0x%" PRIx64 " (%s) to SDP\n", (uint64_t)codec, ast_getformatname(codec));
  10189. if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, codec)) == -1)
  10190. return;
  10191. ast_str_append(m_buf, 0, " %d", rtp_code);
  10192. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
  10193. ast_rtp_lookup_mime_subtype2(1, codec, 0),
  10194. ast_rtp_lookup_sample_rate2(1, codec));
  10195. /* Add fmtp code here */
  10196. }
  10197. /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
  10198. static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
  10199. struct ast_str **m_buf, struct ast_str **a_buf,
  10200. int debug, int *min_packet_size)
  10201. {
  10202. int rtp_code;
  10203. if (!p->trtp)
  10204. return;
  10205. if (debug)
  10206. ast_verbose("Adding text codec 0x%x (%s) to SDP\n", (unsigned)codec, ast_getformatname(codec));
  10207. if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, codec)) == -1)
  10208. return;
  10209. ast_str_append(m_buf, 0, " %d", rtp_code);
  10210. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
  10211. ast_rtp_lookup_mime_subtype2(1, codec, 0),
  10212. ast_rtp_lookup_sample_rate2(1, codec));
  10213. /* Add fmtp code here */
  10214. if (codec == AST_FORMAT_T140RED) {
  10215. int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, AST_FORMAT_T140);
  10216. ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
  10217. t140code,
  10218. t140code,
  10219. t140code);
  10220. }
  10221. }
  10222. /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
  10223. static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
  10224. {
  10225. switch (rate) {
  10226. case AST_T38_RATE_2400:
  10227. return 2400;
  10228. case AST_T38_RATE_4800:
  10229. return 4800;
  10230. case AST_T38_RATE_7200:
  10231. return 7200;
  10232. case AST_T38_RATE_9600:
  10233. return 9600;
  10234. case AST_T38_RATE_12000:
  10235. return 12000;
  10236. case AST_T38_RATE_14400:
  10237. return 14400;
  10238. default:
  10239. return 0;
  10240. }
  10241. }
  10242. /*! \brief Add RFC 2833 DTMF offer to SDP */
  10243. static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
  10244. struct ast_str **m_buf, struct ast_str **a_buf,
  10245. int debug)
  10246. {
  10247. int rtp_code;
  10248. if (debug)
  10249. ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", (unsigned)format, ast_rtp_lookup_mime_subtype2(0, format, 0));
  10250. if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, format)) == -1)
  10251. return;
  10252. ast_str_append(m_buf, 0, " %d", rtp_code);
  10253. ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
  10254. ast_rtp_lookup_mime_subtype2(0, format, 0),
  10255. ast_rtp_lookup_sample_rate2(0, format));
  10256. if (format == AST_RTP_DTMF) /* Indicate we support DTMF and FLASH... */
  10257. ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
  10258. }
  10259. /*! \brief Set all IP media addresses for this call
  10260. \note called from add_sdp()
  10261. */
  10262. static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
  10263. struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
  10264. struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
  10265. struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
  10266. {
  10267. int use_externip = 0;
  10268. /* First, get our address */
  10269. ast_rtp_instance_get_local_address(p->rtp, addr);
  10270. if (p->vrtp) {
  10271. ast_rtp_instance_get_local_address(p->vrtp, vaddr);
  10272. }
  10273. if (p->trtp) {
  10274. ast_rtp_instance_get_local_address(p->trtp, taddr);
  10275. }
  10276. /* If our real IP differs from the local address returned by the RTP engine, use it. */
  10277. /* The premise is that if we are already using that IP to communicate with the client, */
  10278. /* we should be using it for RTP too. */
  10279. use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
  10280. /* Now, try to figure out where we want them to send data */
  10281. /* Is this a re-invite to move the media out, then use the original offer from caller */
  10282. if (!ast_sockaddr_isnull(&p->redirip)) { /* If we have a redirection IP, use it */
  10283. ast_sockaddr_copy(dest, &p->redirip);
  10284. } else {
  10285. /*
  10286. * Audio Destination IP:
  10287. *
  10288. * 1. Specifically configured media address.
  10289. * 2. Local address as specified by the RTP engine.
  10290. * 3. The local IP as defined by chan_sip.
  10291. *
  10292. * Audio Destination Port:
  10293. *
  10294. * 1. Provided by the RTP engine.
  10295. */
  10296. ast_sockaddr_copy(dest,
  10297. !ast_sockaddr_isnull(&media_address) ? &media_address :
  10298. !ast_sockaddr_is_any(addr) && !use_externip ? addr :
  10299. &p->ourip);
  10300. ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
  10301. }
  10302. if (needvideo) {
  10303. /* Determine video destination */
  10304. if (!ast_sockaddr_isnull(&p->vredirip)) {
  10305. ast_sockaddr_copy(vdest, &p->vredirip);
  10306. } else {
  10307. /*
  10308. * Video Destination IP:
  10309. *
  10310. * 1. Specifically configured media address.
  10311. * 2. Local address as specified by the RTP engine.
  10312. * 3. The local IP as defined by chan_sip.
  10313. *
  10314. * Video Destination Port:
  10315. *
  10316. * 1. Provided by the RTP engine.
  10317. */
  10318. ast_sockaddr_copy(vdest,
  10319. !ast_sockaddr_isnull(&media_address) ? &media_address :
  10320. !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr :
  10321. &p->ourip);
  10322. ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
  10323. }
  10324. }
  10325. if (needtext) {
  10326. /* Determine text destination */
  10327. if (!ast_sockaddr_isnull(&p->tredirip)) {
  10328. ast_sockaddr_copy(tdest, &p->tredirip);
  10329. } else {
  10330. /*
  10331. * Text Destination IP:
  10332. *
  10333. * 1. Specifically configured media address.
  10334. * 2. Local address as specified by the RTP engine.
  10335. * 3. The local IP as defined by chan_sip.
  10336. *
  10337. * Text Destination Port:
  10338. *
  10339. * 1. Provided by the RTP engine.
  10340. */
  10341. ast_sockaddr_copy(tdest,
  10342. !ast_sockaddr_isnull(&media_address) ? &media_address :
  10343. !ast_sockaddr_is_any(taddr) && !use_externip ? taddr :
  10344. &p->ourip);
  10345. ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
  10346. }
  10347. }
  10348. }
  10349. static void get_crypto_attrib(struct sip_srtp *srtp, const char **a_crypto)
  10350. {
  10351. /* Set encryption properties */
  10352. if (srtp) {
  10353. if (!srtp->crypto) {
  10354. srtp->crypto = sdp_crypto_setup();
  10355. }
  10356. if (srtp->crypto && (sdp_crypto_offer(srtp->crypto) >= 0)) {
  10357. *a_crypto = sdp_crypto_attrib(srtp->crypto);
  10358. }
  10359. if (!*a_crypto) {
  10360. ast_log(LOG_WARNING, "No SRTP key management enabled\n");
  10361. }
  10362. }
  10363. }
  10364. /*! \brief Add Session Description Protocol message
  10365. If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
  10366. is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
  10367. without modifying the media session in any way.
  10368. */
  10369. static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
  10370. {
  10371. format_t alreadysent = 0;
  10372. int doing_directmedia = FALSE;
  10373. struct ast_sockaddr addr = { {0,} };
  10374. struct ast_sockaddr vaddr = { {0,} };
  10375. struct ast_sockaddr taddr = { {0,} };
  10376. struct ast_sockaddr udptladdr = { {0,} };
  10377. struct ast_sockaddr dest = { {0,} };
  10378. struct ast_sockaddr vdest = { {0,} };
  10379. struct ast_sockaddr tdest = { {0,} };
  10380. struct ast_sockaddr udptldest = { {0,} };
  10381. /* SDP fields */
  10382. char *version = "v=0\r\n"; /* Protocol version */
  10383. char subject[256]; /* Subject of the session */
  10384. char owner[256]; /* Session owner/creator */
  10385. char connection[256]; /* Connection data */
  10386. char *session_time = "t=0 0\r\n"; /* Time the session is active */
  10387. char bandwidth[256] = ""; /* Max bitrate */
  10388. char *hold = "";
  10389. struct ast_str *m_audio = ast_str_alloca(256); /* Media declaration line for audio */
  10390. struct ast_str *m_video = ast_str_alloca(256); /* Media declaration line for video */
  10391. struct ast_str *m_text = ast_str_alloca(256); /* Media declaration line for text */
  10392. struct ast_str *m_modem = ast_str_alloca(256); /* Media declaration line for modem */
  10393. struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
  10394. struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
  10395. struct ast_str *a_text = ast_str_alloca(1024); /* Attributes for text */
  10396. struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
  10397. const char *a_crypto = NULL;
  10398. const char *v_a_crypto = NULL;
  10399. const char *t_a_crypto = NULL;
  10400. format_t x;
  10401. format_t capability = 0;
  10402. int needaudio = FALSE;
  10403. int needvideo = FALSE;
  10404. int needtext = FALSE;
  10405. int debug = sip_debug_test_pvt(p);
  10406. int min_audio_packet_size = 0;
  10407. int min_video_packet_size = 0;
  10408. int min_text_packet_size = 0;
  10409. char codecbuf[SIPBUFSIZE];
  10410. char buf[SIPBUFSIZE];
  10411. char dummy_answer[256];
  10412. /* Set the SDP session name */
  10413. snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
  10414. if (!p->rtp) {
  10415. ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
  10416. return AST_FAILURE;
  10417. }
  10418. /* XXX We should not change properties in the SIP dialog until
  10419. we have acceptance of the offer if this is a re-invite */
  10420. /* Set RTP Session ID and version */
  10421. if (!p->sessionid) {
  10422. p->sessionid = (int)ast_random();
  10423. p->sessionversion = p->sessionid;
  10424. } else {
  10425. if (oldsdp == FALSE)
  10426. p->sessionversion++;
  10427. }
  10428. if (add_audio) {
  10429. doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && p->redircodecs) ? TRUE : FALSE;
  10430. /* Check if we need video in this call */
  10431. if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
  10432. if (doing_directmedia && !(p->jointcapability & AST_FORMAT_VIDEO_MASK & p->redircodecs)) {
  10433. ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
  10434. } else if (p->vrtp) {
  10435. needvideo = TRUE;
  10436. ast_debug(2, "This call needs video offers!\n");
  10437. } else {
  10438. ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
  10439. }
  10440. }
  10441. /* Check if we need text in this call */
  10442. if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
  10443. if (sipdebug_text)
  10444. ast_verbose("We think we can do text\n");
  10445. if (p->trtp) {
  10446. if (sipdebug_text) {
  10447. ast_verbose("And we have a text rtp object\n");
  10448. }
  10449. needtext = TRUE;
  10450. ast_debug(2, "This call needs text offers! \n");
  10451. } else {
  10452. ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
  10453. }
  10454. }
  10455. }
  10456. get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
  10457. snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
  10458. ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
  10459. p->sessionid, p->sessionversion,
  10460. (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
  10461. "IP6" : "IP4",
  10462. ast_sockaddr_stringify_addr_remote(&dest));
  10463. snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
  10464. (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
  10465. "IP6" : "IP4",
  10466. ast_sockaddr_stringify_addr_remote(&dest));
  10467. if (add_audio) {
  10468. if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
  10469. hold = "a=recvonly\r\n";
  10470. doing_directmedia = FALSE;
  10471. } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
  10472. hold = "a=inactive\r\n";
  10473. doing_directmedia = FALSE;
  10474. } else {
  10475. hold = "a=sendrecv\r\n";
  10476. }
  10477. capability = p->jointcapability;
  10478. /* XXX note, Video and Text are negated - 'true' means 'no' */
  10479. ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
  10480. p->novideo ? "True" : "False", p->notext ? "True" : "False");
  10481. ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
  10482. if (doing_directmedia) {
  10483. capability &= p->redircodecs;
  10484. ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
  10485. }
  10486. /* Check if we need audio */
  10487. if (capability & AST_FORMAT_AUDIO_MASK)
  10488. needaudio = TRUE;
  10489. if (debug) {
  10490. ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
  10491. }
  10492. /* Ok, we need video. Let's add what we need for video and set codecs.
  10493. Video is handled differently than audio since we can not transcode. */
  10494. if (needvideo) {
  10495. get_crypto_attrib(p->vsrtp, &v_a_crypto);
  10496. ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
  10497. v_a_crypto ? "SAVP" : "AVP");
  10498. /* Build max bitrate string */
  10499. if (p->maxcallbitrate)
  10500. snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
  10501. if (debug) {
  10502. ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
  10503. }
  10504. }
  10505. /* Ok, we need text. Let's add what we need for text and set codecs.
  10506. Text is handled differently than audio since we can not transcode. */
  10507. if (needtext) {
  10508. if (sipdebug_text)
  10509. ast_verbose("Lets set up the text sdp\n");
  10510. get_crypto_attrib(p->tsrtp, &t_a_crypto);
  10511. ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
  10512. t_a_crypto ? "SAVP" : "AVP");
  10513. if (debug) { /* XXX should I use tdest below ? */
  10514. ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
  10515. }
  10516. }
  10517. /* Start building generic SDP headers */
  10518. /* We break with the "recommendation" and send our IP, in order that our
  10519. peer doesn't have to ast_gethostbyname() us */
  10520. get_crypto_attrib(p->srtp, &a_crypto);
  10521. ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
  10522. a_crypto ? "SAVP" : "AVP");
  10523. /* Now, start adding audio codecs. These are added in this order:
  10524. - First what was requested by the calling channel
  10525. - Then preferences in order from sip.conf device config for this peer/user
  10526. - Then other codecs in capabilities, including video
  10527. */
  10528. /* Prefer the audio codec we were requested to use, first, no matter what
  10529. Note that p->prefcodec can include video codecs, so mask them out
  10530. */
  10531. if ((capability & p->prefcodec) & AST_FORMAT_AUDIO_MASK) {
  10532. format_t codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
  10533. add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
  10534. alreadysent |= codec;
  10535. }
  10536. /* Start by sending our preferred audio/video codecs */
  10537. for (x = 0; x < 64; x++) {
  10538. format_t codec;
  10539. if (!(codec = ast_codec_pref_index(&p->prefs, x)))
  10540. break;
  10541. if (!(capability & codec))
  10542. continue;
  10543. if (alreadysent & codec)
  10544. continue;
  10545. add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
  10546. alreadysent |= codec;
  10547. }
  10548. /* Now send any other common audio and video codecs, and non-codec formats: */
  10549. for (x = 1ULL; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
  10550. if (!(capability & x)) /* Codec not requested */
  10551. continue;
  10552. if (alreadysent & x) /* Already added to SDP */
  10553. continue;
  10554. if (x & AST_FORMAT_AUDIO_MASK)
  10555. add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
  10556. else if (x & AST_FORMAT_VIDEO_MASK)
  10557. add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
  10558. else if (x & AST_FORMAT_TEXT_MASK)
  10559. add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
  10560. }
  10561. /* Now add DTMF RFC2833 telephony-event as a codec */
  10562. for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
  10563. if (!(p->jointnoncodeccapability & x))
  10564. continue;
  10565. add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
  10566. }
  10567. ast_debug(3, "-- Done with adding codecs to SDP\n");
  10568. if (!p->owner || p->owner->timingfd == -1) {
  10569. ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
  10570. }
  10571. if (min_audio_packet_size)
  10572. ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
  10573. /* XXX don't think you can have ptime for video */
  10574. if (min_video_packet_size)
  10575. ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
  10576. /* XXX don't think you can have ptime for text */
  10577. if (min_text_packet_size)
  10578. ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
  10579. if (ast_str_size(m_audio) - ast_str_strlen(m_audio) < 2 || ast_str_size(m_video) - ast_str_strlen(m_video) < 2 ||
  10580. ast_str_size(m_text) - ast_str_strlen(m_text) < 2 || ast_str_size(a_text) - ast_str_strlen(a_text) < 2 ||
  10581. ast_str_size(a_audio) - ast_str_strlen(a_audio) < 2 || ast_str_size(a_video) - ast_str_strlen(a_video) < 2)
  10582. ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
  10583. }
  10584. if (add_t38) {
  10585. /* Our T.38 end is */
  10586. ast_udptl_get_us(p->udptl, &udptladdr);
  10587. /* We don't use directmedia for T.38, so keep the destination the same as our IP address. */
  10588. ast_sockaddr_copy(&udptldest, &p->ourip);
  10589. ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
  10590. if (debug) {
  10591. ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
  10592. }
  10593. /* We break with the "recommendation" and send our IP, in order that our
  10594. peer doesn't have to ast_gethostbyname() us */
  10595. ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
  10596. if (ast_sockaddr_cmp(&udptldest, &dest)) {
  10597. ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
  10598. (ast_sockaddr_is_ipv6(&udptldest) && !ast_sockaddr_is_ipv4_mapped(&udptldest)) ?
  10599. "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
  10600. }
  10601. ast_str_append(&a_modem, 0, "a=T38FaxVersion:%u\r\n", p->t38.our_parms.version);
  10602. ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%u\r\n", t38_get_rate(p->t38.our_parms.rate));
  10603. if (p->t38.our_parms.fill_bit_removal) {
  10604. ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
  10605. }
  10606. if (p->t38.our_parms.transcoding_mmr) {
  10607. ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
  10608. }
  10609. if (p->t38.our_parms.transcoding_jbig) {
  10610. ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
  10611. }
  10612. switch (p->t38.our_parms.rate_management) {
  10613. case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
  10614. ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
  10615. break;
  10616. case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
  10617. ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
  10618. break;
  10619. }
  10620. ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
  10621. switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
  10622. case UDPTL_ERROR_CORRECTION_NONE:
  10623. break;
  10624. case UDPTL_ERROR_CORRECTION_FEC:
  10625. ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
  10626. break;
  10627. case UDPTL_ERROR_CORRECTION_REDUNDANCY:
  10628. ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
  10629. break;
  10630. }
  10631. }
  10632. if (needaudio)
  10633. ast_str_append(&m_audio, 0, "\r\n");
  10634. if (needvideo)
  10635. ast_str_append(&m_video, 0, "\r\n");
  10636. if (needtext)
  10637. ast_str_append(&m_text, 0, "\r\n");
  10638. add_header(resp, "Content-Type", "application/sdp");
  10639. add_content(resp, version);
  10640. add_content(resp, owner);
  10641. add_content(resp, subject);
  10642. add_content(resp, connection);
  10643. /* only if video response is appropriate */
  10644. if (needvideo) {
  10645. add_content(resp, bandwidth);
  10646. }
  10647. add_content(resp, session_time);
  10648. /* if this is a response to an invite, order our offers properly */
  10649. if (p->offered_media[SDP_AUDIO].order_offered ||
  10650. p->offered_media[SDP_VIDEO].order_offered ||
  10651. p->offered_media[SDP_TEXT].order_offered ||
  10652. p->offered_media[SDP_IMAGE].order_offered) {
  10653. int i;
  10654. /* we have up to 3 streams as limited by process_sdp */
  10655. for (i = 1; i <= 3; i++) {
  10656. if (p->offered_media[SDP_AUDIO].order_offered == i) {
  10657. if (needaudio) {
  10658. add_content(resp, ast_str_buffer(m_audio));
  10659. add_content(resp, ast_str_buffer(a_audio));
  10660. add_content(resp, hold);
  10661. if (a_crypto) {
  10662. add_content(resp, a_crypto);
  10663. }
  10664. } else {
  10665. snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
  10666. add_content(resp, dummy_answer);
  10667. }
  10668. } else if (p->offered_media[SDP_VIDEO].order_offered == i) {
  10669. if (needvideo) { /* only if video response is appropriate */
  10670. add_content(resp, ast_str_buffer(m_video));
  10671. add_content(resp, ast_str_buffer(a_video));
  10672. add_content(resp, hold); /* Repeat hold for the video stream */
  10673. if (v_a_crypto) {
  10674. add_content(resp, v_a_crypto);
  10675. }
  10676. } else {
  10677. snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
  10678. add_content(resp, dummy_answer);
  10679. }
  10680. } else if (p->offered_media[SDP_TEXT].order_offered == i) {
  10681. if (needtext) { /* only if text response is appropriate */
  10682. add_content(resp, ast_str_buffer(m_text));
  10683. add_content(resp, ast_str_buffer(a_text));
  10684. add_content(resp, hold); /* Repeat hold for the text stream */
  10685. if (t_a_crypto) {
  10686. add_content(resp, t_a_crypto);
  10687. }
  10688. } else {
  10689. snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
  10690. add_content(resp, dummy_answer);
  10691. }
  10692. } else if (p->offered_media[SDP_IMAGE].order_offered == i) {
  10693. if (add_t38) {
  10694. add_content(resp, ast_str_buffer(m_modem));
  10695. add_content(resp, ast_str_buffer(a_modem));
  10696. } else {
  10697. add_content(resp, "m=image 0 udptl t38\r\n");
  10698. }
  10699. }
  10700. }
  10701. } else {
  10702. /* generate new SDP from scratch, no offers */
  10703. if (needaudio) {
  10704. add_content(resp, ast_str_buffer(m_audio));
  10705. add_content(resp, ast_str_buffer(a_audio));
  10706. add_content(resp, hold);
  10707. if (a_crypto) {
  10708. add_content(resp, a_crypto);
  10709. }
  10710. }
  10711. if (needvideo) { /* only if video response is appropriate */
  10712. add_content(resp, ast_str_buffer(m_video));
  10713. add_content(resp, ast_str_buffer(a_video));
  10714. add_content(resp, hold); /* Repeat hold for the video stream */
  10715. if (v_a_crypto) {
  10716. add_content(resp, v_a_crypto);
  10717. }
  10718. }
  10719. if (needtext) { /* only if text response is appropriate */
  10720. add_content(resp, ast_str_buffer(m_text));
  10721. add_content(resp, ast_str_buffer(a_text));
  10722. add_content(resp, hold); /* Repeat hold for the text stream */
  10723. if (t_a_crypto) {
  10724. add_content(resp, t_a_crypto);
  10725. }
  10726. }
  10727. if (add_t38) {
  10728. add_content(resp, ast_str_buffer(m_modem));
  10729. add_content(resp, ast_str_buffer(a_modem));
  10730. }
  10731. }
  10732. /* Update lastrtprx when we send our SDP */
  10733. p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
  10734. ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
  10735. return AST_SUCCESS;
  10736. }
  10737. /*! \brief Used for 200 OK and 183 early media */
  10738. static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
  10739. {
  10740. struct sip_request resp;
  10741. uint32_t seqno;
  10742. if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
  10743. ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
  10744. return -1;
  10745. }
  10746. respprep(&resp, p, msg, req);
  10747. if (p->udptl) {
  10748. add_sdp(&resp, p, 0, 0, 1);
  10749. } else
  10750. ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
  10751. if (retrans && !p->pendinginvite)
  10752. p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
  10753. return send_response(p, &resp, retrans, seqno);
  10754. }
  10755. /*! \brief copy SIP request (mostly used to save request for responses) */
  10756. static void copy_request(struct sip_request *dst, const struct sip_request *src)
  10757. {
  10758. /* XXX this function can encounter memory allocation errors, perhaps it
  10759. * should return a value */
  10760. struct ast_str *duplicate = dst->data;
  10761. struct ast_str *duplicate_content = dst->content;
  10762. /* copy the entire request then restore the original data and content
  10763. * members from the dst request */
  10764. *dst = *src;
  10765. dst->data = duplicate;
  10766. dst->content = duplicate_content;
  10767. /* copy the data into the dst request */
  10768. if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
  10769. return;
  10770. }
  10771. ast_str_copy_string(&dst->data, src->data);
  10772. /* copy the content into the dst request (if it exists) */
  10773. if (src->content) {
  10774. if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
  10775. return;
  10776. }
  10777. ast_str_copy_string(&dst->content, src->content);
  10778. }
  10779. }
  10780. static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
  10781. {
  10782. char uri[SIPBUFSIZE];
  10783. struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
  10784. struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
  10785. struct sip_cc_agent_pvt *agent_pvt;
  10786. if (!agent) {
  10787. /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
  10788. * agent? Oh well, we'll just warn and return without adding the header.
  10789. */
  10790. ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
  10791. return;
  10792. }
  10793. agent_pvt = agent->private_data;
  10794. if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
  10795. ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
  10796. } else {
  10797. generate_uri(p, uri, sizeof(uri));
  10798. ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
  10799. }
  10800. /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
  10801. * to be more accurate. This parameter has no bearing on the actual operation
  10802. * of the feature; it's just there for informational purposes.
  10803. */
  10804. ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
  10805. add_header(resp, "Call-Info", ast_str_buffer(header));
  10806. ao2_ref(agent, -1);
  10807. }
  10808. /*! \brief Used for 200 OK and 183 early media
  10809. \return Will return XMIT_ERROR for network errors.
  10810. */
  10811. 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)
  10812. {
  10813. struct sip_request resp;
  10814. uint32_t seqno;
  10815. if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
  10816. ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
  10817. return -1;
  10818. }
  10819. respprep(&resp, p, msg, req);
  10820. if (rpid == TRUE) {
  10821. add_rpid(&resp, p);
  10822. }
  10823. if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
  10824. add_cc_call_info_to_response(p, &resp);
  10825. }
  10826. if (p->rtp) {
  10827. if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  10828. ast_debug(1, "Setting framing from config on incoming call\n");
  10829. ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
  10830. }
  10831. ast_rtp_instance_activate(p->rtp);
  10832. try_suggested_sip_codec(p);
  10833. if (p->t38.state == T38_ENABLED) {
  10834. add_sdp(&resp, p, oldsdp, TRUE, TRUE);
  10835. } else {
  10836. add_sdp(&resp, p, oldsdp, TRUE, FALSE);
  10837. }
  10838. } else
  10839. ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
  10840. if (reliable && !p->pendinginvite)
  10841. p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
  10842. add_required_respheader(&resp);
  10843. return send_response(p, &resp, reliable, seqno);
  10844. }
  10845. /*! \brief Parse first line of incoming SIP request */
  10846. static int determine_firstline_parts(struct sip_request *req)
  10847. {
  10848. char *e = ast_skip_blanks(req->data->str); /* there shouldn't be any */
  10849. char *local_rlPart1;
  10850. if (!*e)
  10851. return -1;
  10852. req->rlPart1 = e - req->data->str; /* method or protocol */
  10853. local_rlPart1 = e;
  10854. e = ast_skip_nonblanks(e);
  10855. if (*e)
  10856. *e++ = '\0';
  10857. /* Get URI or status code */
  10858. e = ast_skip_blanks(e);
  10859. if ( !*e )
  10860. return -1;
  10861. ast_trim_blanks(e);
  10862. if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
  10863. if (strlen(e) < 3) /* status code is 3 digits */
  10864. return -1;
  10865. req->rlPart2 = e - req->data->str;
  10866. } else { /* We have a request */
  10867. if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
  10868. ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
  10869. e++;
  10870. if (!*e)
  10871. return -1;
  10872. }
  10873. req->rlPart2 = e - req->data->str; /* URI */
  10874. e = ast_skip_nonblanks(e);
  10875. if (*e)
  10876. *e++ = '\0';
  10877. e = ast_skip_blanks(e);
  10878. if (strcasecmp(e, "SIP/2.0") ) {
  10879. ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
  10880. return -1;
  10881. }
  10882. }
  10883. return 1;
  10884. }
  10885. /*! \brief Transmit reinvite with SDP
  10886. \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
  10887. INVITE that opened the SIP dialogue
  10888. We reinvite so that the audio stream (RTP) go directly between
  10889. the SIP UAs. SIP Signalling stays with * in the path.
  10890. If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
  10891. T38 UDPTL transmission on the channel
  10892. If oldsdp is TRUE then the SDP version number is not incremented. This
  10893. is needed for Session-Timers so we can send a re-invite to refresh the
  10894. SIP session without modifying the media session.
  10895. */
  10896. static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
  10897. {
  10898. struct sip_request req;
  10899. reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
  10900. add_header(&req, "Allow", ALLOWED_METHODS);
  10901. add_supported_header(p, &req);
  10902. if (sipdebug) {
  10903. if (oldsdp == TRUE)
  10904. add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
  10905. else
  10906. add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
  10907. }
  10908. if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
  10909. add_rpid(&req, p);
  10910. if (p->do_history) {
  10911. append_history(p, "ReInv", "Re-invite sent");
  10912. }
  10913. memset(p->offered_media, 0, sizeof(p->offered_media));
  10914. try_suggested_sip_codec(p);
  10915. if (t38version) {
  10916. add_sdp(&req, p, oldsdp, FALSE, TRUE);
  10917. } else {
  10918. add_sdp(&req, p, oldsdp, TRUE, FALSE);
  10919. }
  10920. /* Use this as the basis */
  10921. initialize_initreq(p, &req);
  10922. p->lastinvite = p->ocseq;
  10923. ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
  10924. p->ongoing_reinvite = 1;
  10925. return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  10926. }
  10927. /* \brief Remove URI parameters at end of URI, not in username part though */
  10928. static char *remove_uri_parameters(char *uri)
  10929. {
  10930. char *atsign;
  10931. atsign = strchr(uri, '@'); /* First, locate the at sign */
  10932. if (!atsign) {
  10933. atsign = uri; /* Ok hostname only, let's stick with the rest */
  10934. }
  10935. atsign = strchr(atsign, ';'); /* Locate semi colon */
  10936. if (atsign)
  10937. *atsign = '\0'; /* Kill at the semi colon */
  10938. return uri;
  10939. }
  10940. /*! \brief Check Contact: URI of SIP message */
  10941. static void extract_uri(struct sip_pvt *p, struct sip_request *req)
  10942. {
  10943. char stripped[SIPBUFSIZE];
  10944. char *c;
  10945. ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
  10946. c = get_in_brackets(stripped);
  10947. /* Cut the URI at the at sign after the @, not in the username part */
  10948. c = remove_uri_parameters(c);
  10949. if (!ast_strlen_zero(c)) {
  10950. ast_string_field_set(p, uri, c);
  10951. }
  10952. }
  10953. /*! \brief Build contact header - the contact header we send out */
  10954. static void build_contact(struct sip_pvt *p)
  10955. {
  10956. char tmp[SIPBUFSIZE];
  10957. char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 0);
  10958. if (p->socket.type == SIP_TRANSPORT_UDP) {
  10959. ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
  10960. ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
  10961. } else {
  10962. ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
  10963. ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
  10964. get_transport(p->socket.type));
  10965. }
  10966. }
  10967. /*! \brief Initiate new SIP request to peer/user */
  10968. static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
  10969. {
  10970. struct ast_str *invite = ast_str_alloca(256);
  10971. char from[256];
  10972. char to[256];
  10973. char tmp_n[SIPBUFSIZE/2]; /* build a local copy of 'n' if needed */
  10974. char tmp_l[SIPBUFSIZE/2]; /* build a local copy of 'l' if needed */
  10975. const char *l = NULL; /* XXX what is this, exactly ? */
  10976. const char *n = NULL; /* XXX what is this, exactly ? */
  10977. const char *d = NULL; /* domain in from header */
  10978. const char *urioptions = "";
  10979. int ourport;
  10980. if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
  10981. const char *s = p->username; /* being a string field, cannot be NULL */
  10982. /* Test p->username against allowed characters in AST_DIGIT_ANY
  10983. If it matches the allowed characters list, then sipuser = ";user=phone"
  10984. If not, then sipuser = ""
  10985. */
  10986. /* + is allowed in first position in a tel: uri */
  10987. if (*s == '+')
  10988. s++;
  10989. for (; *s; s++) {
  10990. if (!strchr(AST_DIGIT_ANYNUM, *s) )
  10991. break;
  10992. }
  10993. /* If we have only digits, add ;user=phone to the uri */
  10994. if (!*s)
  10995. urioptions = ";user=phone";
  10996. }
  10997. snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
  10998. if (ast_strlen_zero(p->fromdomain)) {
  10999. d = ast_sockaddr_stringify_host_remote(&p->ourip);
  11000. }
  11001. if (p->owner) {
  11002. if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
  11003. l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
  11004. n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
  11005. } else {
  11006. /* Even if we are using RPID, we shouldn't leak information in the From if the user wants
  11007. * their callerid restricted */
  11008. l = "anonymous";
  11009. n = CALLERID_UNKNOWN;
  11010. d = FROMDOMAIN_INVALID;
  11011. }
  11012. }
  11013. /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
  11014. * XXX Right now, this logic works because the only place that mwi_from
  11015. * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
  11016. * we might end up putting the mwi_from setting into other types of NOTIFY
  11017. * messages as well.
  11018. */
  11019. if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
  11020. l = p->mwi_from;
  11021. }
  11022. if (ast_strlen_zero(l))
  11023. l = default_callerid;
  11024. if (ast_strlen_zero(n))
  11025. n = l;
  11026. /* Allow user to be overridden */
  11027. if (!ast_strlen_zero(p->fromuser))
  11028. l = p->fromuser;
  11029. else /* Save for any further attempts */
  11030. ast_string_field_set(p, fromuser, l);
  11031. /* Allow user to be overridden */
  11032. if (!ast_strlen_zero(p->fromname))
  11033. n = p->fromname;
  11034. else /* Save for any further attempts */
  11035. ast_string_field_set(p, fromname, n);
  11036. /* Allow domain to be overridden */
  11037. if (!ast_strlen_zero(p->fromdomain))
  11038. d = p->fromdomain;
  11039. else /* Save for any further attempts */
  11040. ast_string_field_set(p, fromdomain, d);
  11041. ast_copy_string(tmp_l, l, sizeof(tmp_l));
  11042. if (sip_cfg.pedanticsipchecking) {
  11043. ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
  11044. n = tmp_n;
  11045. ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
  11046. }
  11047. ourport = (p->fromdomainport && (p->fromdomainport != STANDARD_SIP_PORT)) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
  11048. if (!sip_standard_port(p->socket.type, ourport)) {
  11049. snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, tmp_l, d, ourport, p->tag);
  11050. } else {
  11051. snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, tmp_l, d, p->tag);
  11052. }
  11053. if (!ast_strlen_zero(explicit_uri)) {
  11054. ast_str_set(&invite, 0, "%s", explicit_uri);
  11055. } else {
  11056. /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
  11057. if (!ast_strlen_zero(p->fullcontact)) {
  11058. /* If we have full contact, trust it */
  11059. ast_str_append(&invite, 0, "%s", p->fullcontact);
  11060. } else {
  11061. /* Otherwise, use the username while waiting for registration */
  11062. ast_str_append(&invite, 0, "sip:");
  11063. if (!ast_strlen_zero(p->username)) {
  11064. n = p->username;
  11065. if (sip_cfg.pedanticsipchecking) {
  11066. ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
  11067. n = tmp_n;
  11068. }
  11069. ast_str_append(&invite, 0, "%s@", n);
  11070. }
  11071. ast_str_append(&invite, 0, "%s", p->tohost);
  11072. if (p->portinuri) {
  11073. ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
  11074. }
  11075. ast_str_append(&invite, 0, "%s", urioptions);
  11076. }
  11077. }
  11078. /* If custom URI options have been provided, append them */
  11079. if (p->options && !ast_strlen_zero(p->options->uri_options))
  11080. ast_str_append(&invite, 0, ";%s", p->options->uri_options);
  11081. /* This is the request URI, which is the next hop of the call
  11082. which may or may not be the destination of the call
  11083. */
  11084. ast_string_field_set(p, uri, ast_str_buffer(invite));
  11085. if (!ast_strlen_zero(p->todnid)) {
  11086. /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
  11087. if (!strchr(p->todnid, '@')) {
  11088. /* We have no domain in the dnid */
  11089. snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
  11090. } else {
  11091. snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
  11092. }
  11093. } else {
  11094. if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
  11095. /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
  11096. snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
  11097. } else if (p->options && p->options->vxml_url) {
  11098. /* If there is a VXML URL append it to the SIP URL */
  11099. snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
  11100. } else {
  11101. snprintf(to, sizeof(to), "<%s>", p->uri);
  11102. }
  11103. }
  11104. init_req(req, sipmethod, p->uri);
  11105. /* now tmp_n is available so reuse it to build the CSeq */
  11106. snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
  11107. add_header(req, "Via", p->via);
  11108. add_header_max_forwards(p, req);
  11109. /* This will be a no-op most of the time. However, under certain circumstances,
  11110. * NOTIFY messages will use this function for preparing the request and should
  11111. * have Route headers present.
  11112. */
  11113. add_route(req, p->route);
  11114. add_header(req, "From", from);
  11115. add_header(req, "To", to);
  11116. ast_string_field_set(p, exten, l);
  11117. build_contact(p);
  11118. add_header(req, "Contact", p->our_contact);
  11119. add_header(req, "Call-ID", p->callid);
  11120. add_header(req, "CSeq", tmp_n);
  11121. if (!ast_strlen_zero(global_useragent)) {
  11122. add_header(req, "User-Agent", global_useragent);
  11123. }
  11124. }
  11125. /*! \brief Add "Diversion" header to outgoing message
  11126. *
  11127. * We need to add a Diversion header if the owner channel of
  11128. * this dialog has redirecting information associated with it.
  11129. *
  11130. * \param req The request/response to which we will add the header
  11131. * \param pvt The sip_pvt which represents the call-leg
  11132. */
  11133. static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
  11134. {
  11135. const char *diverting_number;
  11136. const char *diverting_name;
  11137. const char *reason;
  11138. char header_text[256];
  11139. if (!pvt->owner) {
  11140. return;
  11141. }
  11142. diverting_number = pvt->owner->redirecting.from.number.str;
  11143. if (!pvt->owner->redirecting.from.number.valid
  11144. || ast_strlen_zero(diverting_number)) {
  11145. return;
  11146. }
  11147. reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
  11148. /* We at least have a number to place in the Diversion header, which is enough */
  11149. diverting_name = pvt->owner->redirecting.from.name.str;
  11150. if (!pvt->owner->redirecting.from.name.valid
  11151. || ast_strlen_zero(diverting_name)) {
  11152. snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
  11153. ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
  11154. } else {
  11155. char diverting_name_buf[128];
  11156. ast_escape_quoted(diverting_name, diverting_name_buf, sizeof(diverting_name_buf));
  11157. snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
  11158. diverting_name_buf, diverting_number,
  11159. ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
  11160. }
  11161. add_header(req, "Diversion", header_text);
  11162. }
  11163. static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
  11164. {
  11165. struct sip_pvt *pvt;
  11166. int expires;
  11167. epa_entry->publish_type = publish_type;
  11168. if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
  11169. return -1;
  11170. }
  11171. sip_pvt_lock(pvt);
  11172. if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
  11173. sip_pvt_unlock(pvt);
  11174. dialog_unlink_all(pvt);
  11175. dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
  11176. return -1;
  11177. }
  11178. ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
  11179. ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
  11180. expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
  11181. pvt->expiry = expires;
  11182. /* Bump refcount for sip_pvt's reference */
  11183. ao2_ref(epa_entry, +1);
  11184. pvt->epa_entry = epa_entry;
  11185. transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
  11186. sip_pvt_unlock(pvt);
  11187. sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
  11188. dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
  11189. return 0;
  11190. }
  11191. /*!
  11192. * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
  11193. * \param p sip_pvt structure
  11194. * \param sipmethod
  11195. * \param sdp unknown
  11196. * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
  11197. * 2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
  11198. * \param explicit_uri
  11199. */
  11200. static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
  11201. {
  11202. struct sip_request req;
  11203. struct ast_variable *var;
  11204. if (init) {/* Bump branch even on initial requests */
  11205. p->branch ^= ast_random();
  11206. p->invite_branch = p->branch;
  11207. build_via(p);
  11208. }
  11209. if (init > 1) {
  11210. initreqprep(&req, p, sipmethod, explicit_uri);
  11211. } else {
  11212. /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
  11213. reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
  11214. }
  11215. if (p->options && p->options->auth) {
  11216. add_header(&req, p->options->authheader, p->options->auth);
  11217. }
  11218. append_date(&req);
  11219. if (sipmethod == SIP_REFER) { /* Call transfer */
  11220. if (p->refer) {
  11221. char buf[SIPBUFSIZE];
  11222. if (!ast_strlen_zero(p->refer->refer_to)) {
  11223. add_header(&req, "Refer-To", p->refer->refer_to);
  11224. }
  11225. if (!ast_strlen_zero(p->refer->referred_by)) {
  11226. snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
  11227. add_header(&req, "Referred-By", buf);
  11228. }
  11229. }
  11230. } else if (sipmethod == SIP_SUBSCRIBE) {
  11231. char buf[SIPBUFSIZE];
  11232. if (p->subscribed == MWI_NOTIFICATION) {
  11233. add_header(&req, "Event", "message-summary");
  11234. add_header(&req, "Accept", "application/simple-message-summary");
  11235. } else if (p->subscribed == CALL_COMPLETION) {
  11236. add_header(&req, "Event", "call-completion");
  11237. add_header(&req, "Accept", "application/call-completion");
  11238. }
  11239. snprintf(buf, sizeof(buf), "%d", p->expiry);
  11240. add_header(&req, "Expires", buf);
  11241. }
  11242. /* This new INVITE is part of an attended transfer. Make sure that the
  11243. other end knows and replace the current call with this new call */
  11244. if (p->options && !ast_strlen_zero(p->options->replaces)) {
  11245. add_header(&req, "Replaces", p->options->replaces);
  11246. add_header(&req, "Require", "replaces");
  11247. }
  11248. /* Add Session-Timers related headers */
  11249. if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE
  11250. || (st_get_mode(p, 0) == SESSION_TIMER_MODE_ACCEPT
  11251. && st_get_se(p, FALSE) != DEFAULT_MIN_SE)) {
  11252. char i2astr[10];
  11253. if (!p->stimer->st_interval) {
  11254. p->stimer->st_interval = st_get_se(p, TRUE);
  11255. }
  11256. p->stimer->st_active = TRUE;
  11257. if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
  11258. snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
  11259. add_header(&req, "Session-Expires", i2astr);
  11260. }
  11261. snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
  11262. add_header(&req, "Min-SE", i2astr);
  11263. }
  11264. add_header(&req, "Allow", ALLOWED_METHODS);
  11265. add_supported_header(p, &req);
  11266. if (p->options && p->options->addsipheaders && p->owner) {
  11267. struct ast_channel *chan = p->owner; /* The owner channel */
  11268. struct varshead *headp;
  11269. ast_channel_lock(chan);
  11270. headp = &chan->varshead;
  11271. if (!headp) {
  11272. ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
  11273. } else {
  11274. const struct ast_var_t *current;
  11275. AST_LIST_TRAVERSE(headp, current, entries) {
  11276. /* SIPADDHEADER: Add SIP header to outgoing call */
  11277. if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
  11278. char *content, *end;
  11279. const char *header = ast_var_value(current);
  11280. char *headdup = ast_strdupa(header);
  11281. /* Strip of the starting " (if it's there) */
  11282. if (*headdup == '"') {
  11283. headdup++;
  11284. }
  11285. if ((content = strchr(headdup, ':'))) {
  11286. *content++ = '\0';
  11287. content = ast_skip_blanks(content); /* Skip white space */
  11288. /* Strip the ending " (if it's there) */
  11289. end = content + strlen(content) -1;
  11290. if (*end == '"') {
  11291. *end = '\0';
  11292. }
  11293. add_header(&req, headdup, content);
  11294. if (sipdebug) {
  11295. ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
  11296. }
  11297. }
  11298. }
  11299. }
  11300. }
  11301. ast_channel_unlock(chan);
  11302. }
  11303. if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
  11304. add_rpid(&req, p);
  11305. if (sipmethod == SIP_INVITE) {
  11306. add_diversion_header(&req, p);
  11307. }
  11308. if (sdp) {
  11309. memset(p->offered_media, 0, sizeof(p->offered_media));
  11310. if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
  11311. ast_debug(1, "T38 is in state %u on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
  11312. add_sdp(&req, p, FALSE, FALSE, TRUE);
  11313. } else if (p->rtp) {
  11314. try_suggested_sip_codec(p);
  11315. add_sdp(&req, p, FALSE, TRUE, FALSE);
  11316. }
  11317. } else if (p->notify) {
  11318. for (var = p->notify->headers; var; var = var->next) {
  11319. add_header(&req, var->name, var->value);
  11320. }
  11321. if (ast_str_strlen(p->notify->content)) {
  11322. add_content(&req, ast_str_buffer(p->notify->content));
  11323. }
  11324. } else if (sipmethod == SIP_PUBLISH) {
  11325. char expires[SIPBUFSIZE];
  11326. switch (p->epa_entry->static_data->event) {
  11327. case CALL_COMPLETION:
  11328. snprintf(expires, sizeof(expires), "%d", p->expiry);
  11329. add_header(&req, "Event", "call-completion");
  11330. add_header(&req, "Expires", expires);
  11331. if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
  11332. add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
  11333. }
  11334. if (!ast_strlen_zero(p->epa_entry->body)) {
  11335. add_header(&req, "Content-Type", "application/pidf+xml");
  11336. add_content(&req, p->epa_entry->body);
  11337. }
  11338. default:
  11339. break;
  11340. }
  11341. }
  11342. if (!p->initreq.headers || init > 2) {
  11343. initialize_initreq(p, &req);
  11344. }
  11345. if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
  11346. p->lastinvite = p->ocseq;
  11347. }
  11348. return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
  11349. }
  11350. /*! \brief Send a subscription or resubscription for MWI */
  11351. static int sip_subscribe_mwi_do(const void *data)
  11352. {
  11353. struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
  11354. if (!mwi) {
  11355. return -1;
  11356. }
  11357. mwi->resub = -1;
  11358. __sip_subscribe_mwi_do(mwi);
  11359. ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
  11360. return 0;
  11361. }
  11362. static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
  11363. {
  11364. struct sip_registry *reg = data;
  11365. const char *old_str;
  11366. /* This shouldn't happen, but just in case */
  11367. if (ast_sockaddr_isnull(new)) {
  11368. ast_debug(1, "Empty sockaddr change...ignoring!\n");
  11369. return;
  11370. }
  11371. if (!ast_sockaddr_port(new)) {
  11372. ast_sockaddr_set_port(new, reg->portno);
  11373. }
  11374. old_str = ast_strdupa(ast_sockaddr_stringify(old));
  11375. ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
  11376. ast_sockaddr_copy(&reg->us, new);
  11377. }
  11378. static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
  11379. {
  11380. struct sip_peer *peer = data;
  11381. const char *old_str;
  11382. /* This shouldn't happen, but just in case */
  11383. if (ast_sockaddr_isnull(new)) {
  11384. ast_debug(1, "Empty sockaddr change...ignoring!\n");
  11385. return;
  11386. }
  11387. if (!ast_sockaddr_isnull(&peer->addr)) {
  11388. ao2_unlink(peers_by_ip, peer);
  11389. }
  11390. if (!ast_sockaddr_port(new)) {
  11391. ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
  11392. }
  11393. old_str = ast_strdupa(ast_sockaddr_stringify(old));
  11394. ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
  11395. ao2_lock(peer);
  11396. ast_sockaddr_copy(&peer->addr, new);
  11397. ao2_unlock(peer);
  11398. ao2_link(peers_by_ip, peer);
  11399. }
  11400. static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
  11401. {
  11402. struct sip_subscription_mwi *mwi = data;
  11403. const char *old_str;
  11404. /* This shouldn't happen, but just in case */
  11405. if (ast_sockaddr_isnull(new)) {
  11406. ast_debug(1, "Empty sockaddr change...ignoring!\n");
  11407. return;
  11408. }
  11409. old_str = ast_strdupa(ast_sockaddr_stringify(old));
  11410. ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
  11411. ast_sockaddr_copy(&mwi->us, new);
  11412. }
  11413. /*! \brief Actually setup an MWI subscription or resubscribe */
  11414. static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
  11415. {
  11416. /* If we have no DNS manager let's do a lookup */
  11417. if (!mwi->dnsmgr) {
  11418. char transport[MAXHOSTNAMELEN];
  11419. struct sip_subscription_mwi *saved;
  11420. snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
  11421. mwi->us.ss.ss_family = get_address_family_filter(mwi->transport); /* Filter address family */
  11422. saved = ASTOBJ_REF(mwi);
  11423. ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, saved);
  11424. if (!mwi->dnsmgr) {
  11425. ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy); /* dnsmgr disabled, remove reference */
  11426. }
  11427. }
  11428. /* If we already have a subscription up simply send a resubscription */
  11429. if (mwi->call) {
  11430. transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
  11431. return 0;
  11432. }
  11433. /* Create a dialog that we will use for the subscription */
  11434. if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
  11435. return -1;
  11436. }
  11437. ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
  11438. if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
  11439. ast_sockaddr_set_port(&mwi->us, mwi->portno);
  11440. }
  11441. /* Setup the destination of our subscription */
  11442. if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
  11443. dialog_unlink_all(mwi->call);
  11444. mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
  11445. return 0;
  11446. }
  11447. mwi->call->expiry = mwi_expiry;
  11448. if (!mwi->dnsmgr && mwi->portno) {
  11449. ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
  11450. ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
  11451. } else {
  11452. mwi->portno = ast_sockaddr_port(&mwi->call->sa);
  11453. }
  11454. /* Set various other information */
  11455. if (!ast_strlen_zero(mwi->authuser)) {
  11456. ast_string_field_set(mwi->call, peername, mwi->authuser);
  11457. ast_string_field_set(mwi->call, authname, mwi->authuser);
  11458. ast_string_field_set(mwi->call, fromuser, mwi->authuser);
  11459. } else {
  11460. ast_string_field_set(mwi->call, peername, mwi->username);
  11461. ast_string_field_set(mwi->call, authname, mwi->username);
  11462. ast_string_field_set(mwi->call, fromuser, mwi->username);
  11463. }
  11464. ast_string_field_set(mwi->call, username, mwi->username);
  11465. if (!ast_strlen_zero(mwi->secret)) {
  11466. ast_string_field_set(mwi->call, peersecret, mwi->secret);
  11467. }
  11468. set_socket_transport(&mwi->call->socket, mwi->transport);
  11469. mwi->call->socket.port = htons(mwi->portno);
  11470. ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
  11471. build_contact(mwi->call);
  11472. build_via(mwi->call);
  11473. /* Change the dialog callid. */
  11474. change_callid_pvt(mwi->call, NULL);
  11475. ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
  11476. /* Associate the call with us */
  11477. mwi->call->mwi = ASTOBJ_REF(mwi);
  11478. mwi->call->subscribed = MWI_NOTIFICATION;
  11479. /* Actually send the packet */
  11480. transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
  11481. return 0;
  11482. }
  11483. /*! \brief Find the channel that is causing the RINGING update */
  11484. static int find_calling_channel(void *obj, void *arg, void *data, int flags)
  11485. {
  11486. struct ast_channel *c = obj;
  11487. struct sip_pvt *p = data;
  11488. int res;
  11489. ast_channel_lock(c);
  11490. res = (c->pbx &&
  11491. (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
  11492. (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
  11493. ast_channel_unlock(c);
  11494. return res ? CMP_MATCH | CMP_STOP : 0;
  11495. }
  11496. /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
  11497. static void state_notify_build_xml(int state, int full, const char *exten, const char *context, struct ast_str **tmp, struct sip_pvt *p, int subscribed, const char *mfrom, const char *mto)
  11498. {
  11499. enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
  11500. const char *statestring = "terminated";
  11501. const char *pidfstate = "--";
  11502. const char *pidfnote= "Ready";
  11503. char hint[AST_MAX_EXTENSION];
  11504. switch (state) {
  11505. case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
  11506. statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
  11507. local_state = NOTIFY_INUSE;
  11508. pidfstate = "busy";
  11509. pidfnote = "Ringing";
  11510. break;
  11511. case AST_EXTENSION_RINGING:
  11512. statestring = "early";
  11513. local_state = NOTIFY_INUSE;
  11514. pidfstate = "busy";
  11515. pidfnote = "Ringing";
  11516. break;
  11517. case AST_EXTENSION_INUSE:
  11518. statestring = "confirmed";
  11519. local_state = NOTIFY_INUSE;
  11520. pidfstate = "busy";
  11521. pidfnote = "On the phone";
  11522. break;
  11523. case AST_EXTENSION_BUSY:
  11524. statestring = "confirmed";
  11525. local_state = NOTIFY_CLOSED;
  11526. pidfstate = "busy";
  11527. pidfnote = "On the phone";
  11528. break;
  11529. case AST_EXTENSION_UNAVAILABLE:
  11530. statestring = "terminated";
  11531. local_state = NOTIFY_CLOSED;
  11532. pidfstate = "away";
  11533. pidfnote = "Unavailable";
  11534. break;
  11535. case AST_EXTENSION_ONHOLD:
  11536. statestring = "confirmed";
  11537. local_state = NOTIFY_CLOSED;
  11538. pidfstate = "busy";
  11539. pidfnote = "On hold";
  11540. break;
  11541. case AST_EXTENSION_NOT_INUSE:
  11542. default:
  11543. /* Default setting */
  11544. break;
  11545. }
  11546. /* Check which device/devices we are watching and if they are registered */
  11547. if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
  11548. char *hint2 = hint, *individual_hint = NULL;
  11549. int hint_count = 0, unavailable_count = 0;
  11550. while ((individual_hint = strsep(&hint2, "&"))) {
  11551. hint_count++;
  11552. if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
  11553. unavailable_count++;
  11554. }
  11555. /* If none of the hinted devices are registered, we will
  11556. * override notification and show no availability.
  11557. */
  11558. if (hint_count > 0 && hint_count == unavailable_count) {
  11559. local_state = NOTIFY_CLOSED;
  11560. pidfstate = "away";
  11561. pidfnote = "Not online";
  11562. }
  11563. }
  11564. switch (subscribed) {
  11565. case XPIDF_XML:
  11566. case CPIM_PIDF_XML:
  11567. ast_str_append(tmp, 0,
  11568. "<?xml version=\"1.0\"?>\n"
  11569. "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
  11570. "<presence>\n");
  11571. ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
  11572. ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
  11573. ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
  11574. ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
  11575. ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
  11576. ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
  11577. break;
  11578. case PIDF_XML: /* Eyebeam supports this format */
  11579. ast_str_append(tmp, 0,
  11580. "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
  11581. "<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);
  11582. ast_str_append(tmp, 0, "<pp:person><status>\n");
  11583. if (pidfstate[0] != '-') {
  11584. ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
  11585. }
  11586. ast_str_append(tmp, 0, "</status></pp:person>\n");
  11587. ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
  11588. ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
  11589. ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
  11590. if (pidfstate[0] == 'b') /* Busy? Still open ... */
  11591. ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
  11592. else
  11593. ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
  11594. ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
  11595. break;
  11596. case DIALOG_INFO_XML: /* SNOM subscribes in this format */
  11597. ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
  11598. 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);
  11599. if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
  11600. /* Twice the extension length should be enough for XML encoding */
  11601. char local_display[AST_MAX_EXTENSION * 2];
  11602. char remote_display[AST_MAX_EXTENSION * 2];
  11603. char *local_target = ast_strdupa(mto);
  11604. /* It may seem odd to base the remote_target on the To header here,
  11605. * but testing by reporters on issue ASTERISK-16735 found that basing
  11606. * on the From header would cause ringing state hints to not work
  11607. * properly on certain SNOM devices. If you are using notifycid properly
  11608. * (i.e. in the same extension and context as the dialed call) then this
  11609. * should not be an issue since the data will be overwritten shortly
  11610. * with channel caller ID
  11611. */
  11612. char *remote_target = ast_strdupa(mto);
  11613. ast_xml_escape(exten, local_display, sizeof(local_display));
  11614. ast_xml_escape(exten, remote_display, sizeof(remote_display));
  11615. /* There are some limitations to how this works. The primary one is that the
  11616. callee must be dialing the same extension that is being monitored. Simply dialing
  11617. the hint'd device is not sufficient. */
  11618. if (sip_cfg.notifycid) {
  11619. struct ast_channel *caller;
  11620. if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
  11621. static char *anonymous = "anonymous";
  11622. static char *invalid = "anonymous.invalid";
  11623. char *cid_num;
  11624. char *connected_num;
  11625. int need;
  11626. int cid_num_restricted, connected_num_restricted;
  11627. ast_channel_lock(caller);
  11628. cid_num_restricted = (caller->caller.id.number.presentation &
  11629. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
  11630. cid_num = S_COR(caller->caller.id.number.valid,
  11631. S_COR(cid_num_restricted, anonymous,
  11632. caller->caller.id.number.str), "");
  11633. need = strlen(cid_num) + (cid_num_restricted ? strlen(invalid) :
  11634. strlen(p->fromdomain)) + sizeof("sip:@");
  11635. remote_target = ast_alloca(need);
  11636. snprintf(remote_target, need, "sip:%s@%s", cid_num,
  11637. cid_num_restricted ? invalid : p->fromdomain);
  11638. ast_xml_escape(S_COR(caller->caller.id.name.valid,
  11639. S_COR((caller->caller.id.name.presentation &
  11640. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
  11641. caller->caller.id.name.str), ""),
  11642. remote_display, sizeof(remote_display));
  11643. connected_num_restricted = (caller->connected.id.number.presentation &
  11644. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
  11645. connected_num = S_COR(caller->connected.id.number.valid,
  11646. S_COR(connected_num_restricted, anonymous,
  11647. caller->connected.id.number.str), "");
  11648. need = strlen(connected_num) + (connected_num_restricted ? strlen(invalid) :
  11649. strlen(p->fromdomain)) + sizeof("sip:@");
  11650. local_target = ast_alloca(need);
  11651. snprintf(local_target, need, "sip:%s@%s", connected_num,
  11652. connected_num_restricted ? invalid : p->fromdomain);
  11653. ast_xml_escape(S_COR(caller->connected.id.name.valid,
  11654. S_COR((caller->connected.id.name.presentation &
  11655. AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
  11656. caller->connected.id.name.str), ""),
  11657. local_display, sizeof(local_display));
  11658. ast_channel_unlock(caller);
  11659. caller = ast_channel_unref(caller);
  11660. }
  11661. /* We create a fake call-id which the phone will send back in an INVITE
  11662. Replaces header which we can grab and do some magic with. */
  11663. if (sip_cfg.pedanticsipchecking) {
  11664. ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
  11665. exten, p->callid, p->theirtag, p->tag);
  11666. } else {
  11667. ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
  11668. exten, p->callid);
  11669. }
  11670. ast_str_append(tmp, 0,
  11671. "<remote>\n"
  11672. /* See the limitations of this above. Luckily the phone seems to still be
  11673. happy when these values are not correct. */
  11674. "<identity display=\"%s\">%s</identity>\n"
  11675. "<target uri=\"%s\"/>\n"
  11676. "</remote>\n"
  11677. "<local>\n"
  11678. "<identity display=\"%s\">%s</identity>\n"
  11679. "<target uri=\"%s\"/>\n"
  11680. "</local>\n",
  11681. remote_display, remote_target, remote_target, local_display, local_target, local_target);
  11682. } else {
  11683. ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
  11684. }
  11685. } else {
  11686. ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
  11687. }
  11688. ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
  11689. if (state == AST_EXTENSION_ONHOLD) {
  11690. ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
  11691. "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
  11692. "</target>\n</local>\n", mto);
  11693. }
  11694. ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
  11695. break;
  11696. case NONE:
  11697. default:
  11698. break;
  11699. }
  11700. }
  11701. static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
  11702. {
  11703. struct sip_request req;
  11704. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  11705. char uri[SIPBUFSIZE];
  11706. char state_str[64];
  11707. char subscription_state_hdr[64];
  11708. if (state < CC_QUEUED || state > CC_READY) {
  11709. ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%u)\n", state);
  11710. return -1;
  11711. }
  11712. reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
  11713. snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
  11714. add_header(&req, "Event", "call-completion");
  11715. add_header(&req, "Content-Type", "application/call-completion");
  11716. snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
  11717. add_header(&req, "Subscription-State", subscription_state_hdr);
  11718. if (state == CC_READY) {
  11719. generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
  11720. snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
  11721. }
  11722. add_content(&req, state_str);
  11723. if (state == CC_READY) {
  11724. add_content(&req, uri);
  11725. }
  11726. return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
  11727. }
  11728. /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
  11729. static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
  11730. {
  11731. struct ast_str *tmp = ast_str_alloca(4000);
  11732. char from[256], to[256];
  11733. char *c, *mfrom, *mto;
  11734. struct sip_request req;
  11735. const struct cfsubscription_types *subscriptiontype;
  11736. /* If the subscription has not yet been accepted do not send a NOTIFY */
  11737. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  11738. return 0;
  11739. }
  11740. memset(from, 0, sizeof(from));
  11741. memset(to, 0, sizeof(to));
  11742. subscriptiontype = find_subscription_type(p->subscribed);
  11743. ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
  11744. c = get_in_brackets(from);
  11745. if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
  11746. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  11747. return -1;
  11748. }
  11749. mfrom = remove_uri_parameters(c);
  11750. ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
  11751. c = get_in_brackets(to);
  11752. if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
  11753. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  11754. return -1;
  11755. }
  11756. mto = remove_uri_parameters(c);
  11757. reqprep(&req, p, SIP_NOTIFY, 0, 1);
  11758. switch(state) {
  11759. case AST_EXTENSION_DEACTIVATED:
  11760. if (timeout)
  11761. add_header(&req, "Subscription-State", "terminated;reason=timeout");
  11762. else {
  11763. add_header(&req, "Subscription-State", "terminated;reason=probation");
  11764. add_header(&req, "Retry-After", "60");
  11765. }
  11766. break;
  11767. case AST_EXTENSION_REMOVED:
  11768. add_header(&req, "Subscription-State", "terminated;reason=noresource");
  11769. break;
  11770. default:
  11771. if (p->expiry)
  11772. add_header(&req, "Subscription-State", "active");
  11773. else /* Expired */
  11774. add_header(&req, "Subscription-State", "terminated;reason=timeout");
  11775. }
  11776. switch (p->subscribed) {
  11777. case XPIDF_XML:
  11778. case CPIM_PIDF_XML:
  11779. add_header(&req, "Event", subscriptiontype->event);
  11780. state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
  11781. add_header(&req, "Content-Type", subscriptiontype->mediatype);
  11782. p->dialogver++;
  11783. break;
  11784. case PIDF_XML: /* Eyebeam supports this format */
  11785. add_header(&req, "Event", subscriptiontype->event);
  11786. state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
  11787. add_header(&req, "Content-Type", subscriptiontype->mediatype);
  11788. p->dialogver++;
  11789. break;
  11790. case DIALOG_INFO_XML: /* SNOM subscribes in this format */
  11791. add_header(&req, "Event", subscriptiontype->event);
  11792. state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
  11793. add_header(&req, "Content-Type", subscriptiontype->mediatype);
  11794. p->dialogver++;
  11795. break;
  11796. case NONE:
  11797. default:
  11798. break;
  11799. }
  11800. add_content(&req, ast_str_buffer(tmp));
  11801. p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
  11802. /* Send as XMIT_CRITICAL as we may never receive a 200 OK Response which clears p->pendinginvite.
  11803. *
  11804. * extensionstate_update() uses p->pendinginvite for queuing control.
  11805. * Updates stall if pendinginvite <> 0.
  11806. *
  11807. * The most appropriate solution is to remove the subscription when the NOTIFY transaction fails.
  11808. * The client will re-subscribe after restarting or maxexpiry timeout.
  11809. */
  11810. /* RFC6665 4.2.2. Sending State Information to Subscribers
  11811. * If the NOTIFY request fails due to expiration of SIP Timer F (transaction timeout),
  11812. * the notifier SHOULD remove the subscription.
  11813. */
  11814. return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  11815. }
  11816. /*! \brief Notify user of messages waiting in voicemail (RFC3842)
  11817. \note - Notification only works for registered peers with mailbox= definitions
  11818. in sip.conf
  11819. - We use the SIP Event package message-summary
  11820. MIME type defaults to "application/simple-message-summary";
  11821. */
  11822. static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
  11823. {
  11824. struct sip_request req;
  11825. struct ast_str *out = ast_str_alloca(500);
  11826. int ourport = (p->fromdomainport && (p->fromdomainport != STANDARD_SIP_PORT)) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
  11827. const char *domain;
  11828. const char *exten = S_OR(vmexten, default_vmexten);
  11829. initreqprep(&req, p, SIP_NOTIFY, NULL);
  11830. add_header(&req, "Event", "message-summary");
  11831. add_header(&req, "Content-Type", default_notifymime);
  11832. ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
  11833. /* domain initialization occurs here because initreqprep changes ast_sockaddr_stringify string. */
  11834. domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
  11835. if (!sip_standard_port(p->socket.type, ourport)) {
  11836. if (p->socket.type == SIP_TRANSPORT_UDP) {
  11837. ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
  11838. } else {
  11839. ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, get_transport(p->socket.type));
  11840. }
  11841. } else {
  11842. if (p->socket.type == SIP_TRANSPORT_UDP) {
  11843. ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
  11844. } else {
  11845. ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, get_transport(p->socket.type));
  11846. }
  11847. }
  11848. /* Cisco has a bug in the SIP stack where it can't accept the
  11849. (0/0) notification. This can temporarily be disabled in
  11850. sip.conf with the "buggymwi" option */
  11851. ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
  11852. newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
  11853. if (p->subscribed) {
  11854. if (p->expiry) {
  11855. add_header(&req, "Subscription-State", "active");
  11856. } else { /* Expired */
  11857. add_header(&req, "Subscription-State", "terminated;reason=timeout");
  11858. }
  11859. }
  11860. add_content(&req, ast_str_buffer(out));
  11861. if (!p->initreq.headers) {
  11862. initialize_initreq(p, &req);
  11863. }
  11864. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  11865. }
  11866. /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
  11867. static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
  11868. {
  11869. struct sip_request req;
  11870. char tmp[SIPBUFSIZE/2];
  11871. reqprep(&req, p, SIP_NOTIFY, 0, 1);
  11872. snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
  11873. add_header(&req, "Event", tmp);
  11874. add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
  11875. add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
  11876. add_header(&req, "Allow", ALLOWED_METHODS);
  11877. add_supported_header(p, &req);
  11878. snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
  11879. add_content(&req, tmp);
  11880. if (!p->initreq.headers) {
  11881. initialize_initreq(p, &req);
  11882. }
  11883. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  11884. }
  11885. static int manager_sipnotify(struct mansession *s, const struct message *m)
  11886. {
  11887. const char *channame = astman_get_header(m, "Channel");
  11888. struct ast_variable *vars = astman_get_variables_order(m, ORDER_NATURAL);
  11889. struct sip_pvt *p;
  11890. struct ast_variable *header, *var;
  11891. if (ast_strlen_zero(channame)) {
  11892. astman_send_error(s, m, "SIPNotify requires a channel name");
  11893. return 0;
  11894. }
  11895. if (!strncasecmp(channame, "sip/", 4)) {
  11896. channame += 4;
  11897. }
  11898. if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
  11899. astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
  11900. return 0;
  11901. }
  11902. if (create_addr(p, channame, NULL, 0)) {
  11903. /* Maybe they're not registered, etc. */
  11904. dialog_unlink_all(p);
  11905. dialog_unref(p, "unref dialog inside for loop" );
  11906. /* sip_destroy(p); */
  11907. astman_send_error(s, m, "Could not create address");
  11908. return 0;
  11909. }
  11910. /* Notify is outgoing call */
  11911. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  11912. sip_notify_allocate(p);
  11913. p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
  11914. for (var = vars; var; var = var->next) {
  11915. if (!strcasecmp(var->name, "Content")) {
  11916. if (ast_str_strlen(p->notify->content))
  11917. ast_str_append(&p->notify->content, 0, "\r\n");
  11918. ast_str_append(&p->notify->content, 0, "%s", var->value);
  11919. } else if (!strcasecmp(var->name, "Content-Length")) {
  11920. ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
  11921. } else {
  11922. header->next = ast_variable_new(var->name, var->value, "");
  11923. header = header->next;
  11924. }
  11925. }
  11926. sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
  11927. transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
  11928. dialog_unref(p, "bump down the count of p since we're done with it.");
  11929. astman_send_ack(s, m, "Notify Sent");
  11930. ast_variables_destroy(vars);
  11931. return 0;
  11932. }
  11933. /*! \brief Send a provisional response indicating that a call was redirected
  11934. */
  11935. static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
  11936. {
  11937. struct sip_request resp;
  11938. if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  11939. return;
  11940. }
  11941. respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
  11942. add_diversion_header(&resp, p);
  11943. send_response(p, &resp, XMIT_UNRELIABLE, 0);
  11944. }
  11945. /*! \brief Notify peer that the connected line has changed */
  11946. static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
  11947. {
  11948. if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
  11949. return;
  11950. }
  11951. if (!p->owner->connected.id.number.valid
  11952. || ast_strlen_zero(p->owner->connected.id.number.str)) {
  11953. return;
  11954. }
  11955. append_history(p, "ConnectedLine", "%s party is now %s <%s>",
  11956. ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
  11957. S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
  11958. S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
  11959. if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  11960. struct sip_request req;
  11961. if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
  11962. reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
  11963. add_header(&req, "Allow", ALLOWED_METHODS);
  11964. add_supported_header(p, &req);
  11965. add_rpid(&req, p);
  11966. add_sdp(&req, p, FALSE, TRUE, FALSE);
  11967. initialize_initreq(p, &req);
  11968. p->lastinvite = p->ocseq;
  11969. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  11970. p->invitestate = INV_CALLING;
  11971. send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  11972. } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) {
  11973. reqprep(&req, p, SIP_UPDATE, 0, 1);
  11974. add_rpid(&req, p);
  11975. add_header(&req, "X-Asterisk-rpid-update", "Yes");
  11976. send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  11977. } else {
  11978. /* We cannot send the update yet, so we have to wait until we can */
  11979. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  11980. }
  11981. } else {
  11982. ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  11983. if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
  11984. struct sip_request resp;
  11985. if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
  11986. ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  11987. respprep(&resp, p, "180 Ringing", &p->initreq);
  11988. add_rpid(&resp, p);
  11989. send_response(p, &resp, XMIT_UNRELIABLE, 0);
  11990. ast_set_flag(&p->flags[0], SIP_RINGING);
  11991. } else if (p->owner->_state == AST_STATE_RINGING) {
  11992. ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
  11993. respprep(&resp, p, "183 Session Progress", &p->initreq);
  11994. add_rpid(&resp, p);
  11995. send_response(p, &resp, XMIT_UNRELIABLE, 0);
  11996. ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
  11997. } else {
  11998. ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", p->owner->name, ast_state2str(p->owner->_state));
  11999. }
  12000. }
  12001. }
  12002. }
  12003. static const struct _map_x_s regstatestrings[] = {
  12004. { REG_STATE_FAILED, "Failed" },
  12005. { REG_STATE_UNREGISTERED, "Unregistered"},
  12006. { REG_STATE_REGSENT, "Request Sent"},
  12007. { REG_STATE_AUTHSENT, "Auth. Sent"},
  12008. { REG_STATE_REGISTERED, "Registered"},
  12009. { REG_STATE_REJECTED, "Rejected"},
  12010. { REG_STATE_TIMEOUT, "Timeout"},
  12011. { REG_STATE_NOAUTH, "No Authentication"},
  12012. { -1, NULL } /* terminator */
  12013. };
  12014. /*! \brief Convert registration state status to string */
  12015. static const char *regstate2str(enum sipregistrystate regstate)
  12016. {
  12017. return map_x_s(regstatestrings, regstate, "Unknown");
  12018. }
  12019. /*! \brief Update registration with SIP Proxy.
  12020. * Called from the scheduler when the previous registration expires,
  12021. * so we don't have to cancel the pending event.
  12022. * We assume the reference so the sip_registry is valid, since it
  12023. * is stored in the scheduled event anyways.
  12024. */
  12025. static int sip_reregister(const void *data)
  12026. {
  12027. /* if we are here, we know that we need to reregister. */
  12028. struct sip_registry *r = (struct sip_registry *) data;
  12029. /* if we couldn't get a reference to the registry object, punt */
  12030. if (!r) {
  12031. return 0;
  12032. }
  12033. if (r->call && r->call->do_history) {
  12034. append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
  12035. }
  12036. /* Since registry's are only added/removed by the the monitor thread, this
  12037. may be overkill to reference/dereference at all here */
  12038. if (sipdebug) {
  12039. ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
  12040. }
  12041. r->expire = -1;
  12042. r->expiry = r->configured_expiry;
  12043. __sip_do_register(r);
  12044. registry_unref(r, "unref the re-register scheduled event");
  12045. return 0;
  12046. }
  12047. /*! \brief Register with SIP proxy
  12048. \return see \ref __sip_xmit
  12049. */
  12050. static int __sip_do_register(struct sip_registry *r)
  12051. {
  12052. int res;
  12053. res = transmit_register(r, SIP_REGISTER, NULL, NULL);
  12054. return res;
  12055. }
  12056. /*! \brief Registration timeout, register again
  12057. * Registered as a timeout handler during transmit_register(),
  12058. * to retransmit the packet if a reply does not come back.
  12059. * This is called by the scheduler so the event is not pending anymore when
  12060. * we are called.
  12061. */
  12062. static int sip_reg_timeout(const void *data)
  12063. {
  12064. /* if we are here, our registration timed out, so we'll just do it over */
  12065. struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
  12066. struct sip_pvt *p;
  12067. /* if we couldn't get a reference to the registry object, punt */
  12068. if (!r) {
  12069. return 0;
  12070. }
  12071. if (r->dnsmgr) {
  12072. /* If the registration has timed out, maybe the IP changed. Force a refresh. */
  12073. ast_dnsmgr_refresh(r->dnsmgr);
  12074. }
  12075. /* If the initial tranmission failed, we may not have an existing dialog,
  12076. * so it is possible that r->call == NULL.
  12077. * Otherwise destroy it, as we have a timeout so we don't want it.
  12078. */
  12079. if (r->call) {
  12080. /* Unlink us, destroy old call. Locking is not relevant here because all this happens
  12081. in the single SIP manager thread. */
  12082. p = r->call;
  12083. sip_pvt_lock(p);
  12084. pvt_set_needdestroy(p, "registration timeout");
  12085. /* Pretend to ACK anything just in case */
  12086. __sip_pretend_ack(p);
  12087. sip_pvt_unlock(p);
  12088. /* decouple the two objects */
  12089. /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
  12090. if (p->registry) {
  12091. p->registry = registry_unref(p->registry, "p->registry unreffed");
  12092. }
  12093. r->call = dialog_unref(r->call, "unrefing r->call");
  12094. }
  12095. /* If we have a limit, stop registration and give up */
  12096. r->timeout = -1;
  12097. if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
  12098. /* Ok, enough is enough. Don't try any more */
  12099. /* We could add an external notification here...
  12100. steal it from app_voicemail :-) */
  12101. ast_log(LOG_NOTICE, " -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
  12102. r->regstate = REG_STATE_FAILED;
  12103. } else {
  12104. r->regstate = REG_STATE_UNREGISTERED;
  12105. transmit_register(r, SIP_REGISTER, NULL, NULL);
  12106. ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
  12107. }
  12108. manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
  12109. registry_unref(r, "unreffing registry_unref r");
  12110. return 0;
  12111. }
  12112. static const char *sip_sanitized_host(const char *host)
  12113. {
  12114. struct ast_sockaddr addr = { { 0, 0, }, };
  12115. /* peer/sip_pvt->tohost and sip_registry->hostname should never have a port
  12116. * in them, so we use PARSE_PORT_FORBID here. If this lookup fails, we return
  12117. * the original host which is most likely a host name and not an IP. */
  12118. if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
  12119. return host;
  12120. }
  12121. return ast_sockaddr_stringify_host_remote(&addr);
  12122. }
  12123. /*! \brief Transmit register to SIP proxy or UA
  12124. * auth = NULL on the initial registration (from sip_reregister())
  12125. */
  12126. static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
  12127. {
  12128. struct sip_request req;
  12129. char from[256];
  12130. char to[256];
  12131. char tmp[80];
  12132. char addr[80];
  12133. struct sip_pvt *p;
  12134. struct sip_peer *peer = NULL;
  12135. int res;
  12136. int portno = 0;
  12137. /* exit if we are already in process with this registrar ?*/
  12138. if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
  12139. if (r) {
  12140. ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
  12141. }
  12142. return 0;
  12143. }
  12144. if (r->dnsmgr == NULL) {
  12145. char transport[MAXHOSTNAMELEN];
  12146. peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
  12147. snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
  12148. r->us.ss.ss_family = get_address_family_filter(r->transport); /* Filter address family */
  12149. /* No point in doing a DNS lookup of the register hostname if we're just going to
  12150. * end up using an outbound proxy. obproxy_get is safe to call with either of r->call
  12151. * or peer NULL. Since we're only concerned with its existence, we're not going to
  12152. * bother getting a ref to the proxy*/
  12153. if (!obproxy_get(r->call, peer)) {
  12154. registry_addref(r, "add reg ref for dnsmgr");
  12155. ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
  12156. if (!r->dnsmgr) {
  12157. /*dnsmgr refresh disabled, no reference added! */
  12158. registry_unref(r, "remove reg ref, dnsmgr disabled");
  12159. }
  12160. }
  12161. if (peer) {
  12162. peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
  12163. }
  12164. }
  12165. if (r->call) { /* We have a registration */
  12166. if (!auth) {
  12167. ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
  12168. return 0;
  12169. } else {
  12170. p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
  12171. ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
  12172. }
  12173. } else {
  12174. /* Build callid for registration if we haven't registered before */
  12175. if (!r->callid_valid) {
  12176. build_callid_registry(r, &internip, default_fromdomain);
  12177. build_localtag_registry(r);
  12178. r->callid_valid = TRUE;
  12179. }
  12180. /* Allocate SIP dialog for registration */
  12181. if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
  12182. ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
  12183. return 0;
  12184. }
  12185. /* reset tag to consistent value from registry */
  12186. ast_string_field_set(p, tag, r->localtag);
  12187. if (p->do_history) {
  12188. append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
  12189. }
  12190. p->socket.type = r->transport;
  12191. /* Use port number specified if no SRV record was found */
  12192. if (!ast_sockaddr_isnull(&r->us)) {
  12193. if (!ast_sockaddr_port(&r->us) && r->portno) {
  12194. ast_sockaddr_set_port(&r->us, r->portno);
  12195. }
  12196. /* It is possible that DNS was unavailable at the time the peer was created.
  12197. * Here, if we've updated the address in the registry via manually calling
  12198. * ast_dnsmgr_lookup_cb() above, then we call the same function that dnsmgr would
  12199. * call if it was updating a peer's address */
  12200. if ((peer = find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
  12201. if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
  12202. on_dns_update_peer(&peer->addr, &r->us, peer);
  12203. }
  12204. peer = unref_peer(peer, "unref after find_peer");
  12205. }
  12206. }
  12207. /* Find address to hostname */
  12208. if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
  12209. /* we have what we hope is a temporary network error,
  12210. * probably DNS. We need to reschedule a registration try */
  12211. dialog_unlink_all(p);
  12212. p = dialog_unref(p, "unref dialog after unlink_all");
  12213. if (r->timeout > -1) {
  12214. AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
  12215. registry_unref(_data, "del for REPLACE of registry ptr"),
  12216. registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
  12217. registry_addref(r,"add for REPLACE registry ptr"));
  12218. ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
  12219. } else {
  12220. r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
  12221. 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);
  12222. }
  12223. r->regattempts++;
  12224. return 0;
  12225. }
  12226. /* Copy back Call-ID in case create_addr changed it */
  12227. ast_string_field_set(r, callid, p->callid);
  12228. if (!r->dnsmgr && r->portno) {
  12229. ast_sockaddr_set_port(&p->sa, r->portno);
  12230. ast_sockaddr_set_port(&p->recv, r->portno);
  12231. }
  12232. if (!ast_strlen_zero(p->fromdomain)) {
  12233. portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
  12234. } else if (!ast_strlen_zero(r->regdomain)) {
  12235. portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
  12236. } else {
  12237. portno = ast_sockaddr_port(&p->sa);
  12238. }
  12239. ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
  12240. r->call = dialog_ref(p, "copying dialog into registry r->call"); /* Save pointer to SIP dialog */
  12241. p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
  12242. if (!ast_strlen_zero(r->secret)) { /* Secret (password) */
  12243. ast_string_field_set(p, peersecret, r->secret);
  12244. }
  12245. if (!ast_strlen_zero(r->md5secret))
  12246. ast_string_field_set(p, peermd5secret, r->md5secret);
  12247. /* User name in this realm
  12248. - if authuser is set, use that, otherwise use username */
  12249. if (!ast_strlen_zero(r->authuser)) {
  12250. ast_string_field_set(p, peername, r->authuser);
  12251. ast_string_field_set(p, authname, r->authuser);
  12252. } else if (!ast_strlen_zero(r->username)) {
  12253. ast_string_field_set(p, peername, r->username);
  12254. ast_string_field_set(p, authname, r->username);
  12255. ast_string_field_set(p, fromuser, r->username);
  12256. }
  12257. if (!ast_strlen_zero(r->username)) {
  12258. ast_string_field_set(p, username, r->username);
  12259. }
  12260. /* Save extension in packet */
  12261. if (!ast_strlen_zero(r->callback)) {
  12262. ast_string_field_set(p, exten, r->callback);
  12263. }
  12264. /* Set transport and port so the correct contact is built */
  12265. set_socket_transport(&p->socket, r->transport);
  12266. if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
  12267. p->socket.port =
  12268. htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
  12269. }
  12270. /*
  12271. check which address we should use in our contact header
  12272. based on whether the remote host is on the external or
  12273. internal network so we can register through nat
  12274. */
  12275. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  12276. build_contact(p);
  12277. }
  12278. /* set up a timeout */
  12279. if (auth == NULL) {
  12280. if (r->timeout > -1) {
  12281. ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
  12282. }
  12283. AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
  12284. registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
  12285. registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
  12286. registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
  12287. ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
  12288. }
  12289. snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
  12290. if (!ast_strlen_zero(p->theirtag)) {
  12291. snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
  12292. } else {
  12293. snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
  12294. }
  12295. /* Fromdomain is what we are registering to, regardless of actual
  12296. host name from SRV */
  12297. if (portno && portno != STANDARD_SIP_PORT) {
  12298. snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
  12299. } else {
  12300. snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
  12301. }
  12302. ast_string_field_set(p, uri, addr);
  12303. p->branch ^= ast_random();
  12304. init_req(&req, sipmethod, addr);
  12305. /* Add to CSEQ */
  12306. snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
  12307. p->ocseq = r->ocseq;
  12308. build_via(p);
  12309. add_header(&req, "Via", p->via);
  12310. add_header_max_forwards(p, &req);
  12311. add_header(&req, "From", from);
  12312. add_header(&req, "To", to);
  12313. add_header(&req, "Call-ID", p->callid);
  12314. add_header(&req, "CSeq", tmp);
  12315. if (!ast_strlen_zero(global_useragent))
  12316. add_header(&req, "User-Agent", global_useragent);
  12317. if (auth) { /* Add auth header */
  12318. add_header(&req, authheader, auth);
  12319. } else if (!ast_strlen_zero(r->nonce)) {
  12320. char digest[1024];
  12321. /* We have auth data to reuse, build a digest header.
  12322. * Note, this is not always useful because some parties do not
  12323. * like nonces to be reused (for good reasons!) so they will
  12324. * challenge us anyways.
  12325. */
  12326. if (sipdebug) {
  12327. ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
  12328. }
  12329. ast_string_field_set(p, realm, r->realm);
  12330. ast_string_field_set(p, nonce, r->nonce);
  12331. ast_string_field_set(p, domain, r->authdomain);
  12332. ast_string_field_set(p, opaque, r->opaque);
  12333. ast_string_field_set(p, qop, r->qop);
  12334. p->noncecount = ++r->noncecount;
  12335. memset(digest, 0, sizeof(digest));
  12336. if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
  12337. add_header(&req, "Authorization", digest);
  12338. } else {
  12339. ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
  12340. }
  12341. }
  12342. snprintf(tmp, sizeof(tmp), "%d", r->expiry);
  12343. add_header(&req, "Expires", tmp);
  12344. add_header(&req, "Contact", p->our_contact);
  12345. initialize_initreq(p, &req);
  12346. if (sip_debug_test_pvt(p)) {
  12347. ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  12348. }
  12349. r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
  12350. r->regattempts++; /* Another attempt */
  12351. ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
  12352. res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
  12353. dialog_unref(p, "p is finished here at the end of transmit_register");
  12354. return res;
  12355. }
  12356. /*! \brief Transmit text with SIP MESSAGE method */
  12357. static int transmit_message_with_text(struct sip_pvt *p, const char *text)
  12358. {
  12359. struct sip_request req;
  12360. reqprep(&req, p, SIP_MESSAGE, 0, 1);
  12361. add_text(&req, text);
  12362. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  12363. }
  12364. /*! \brief Allocate SIP refer structure */
  12365. static int sip_refer_allocate(struct sip_pvt *p)
  12366. {
  12367. p->refer = ast_calloc(1, sizeof(struct sip_refer));
  12368. return p->refer ? 1 : 0;
  12369. }
  12370. /*! \brief Allocate SIP refer structure */
  12371. static int sip_notify_allocate(struct sip_pvt *p)
  12372. {
  12373. p->notify = ast_calloc(1, sizeof(struct sip_notify));
  12374. if (p->notify) {
  12375. p->notify->content = ast_str_create(128);
  12376. }
  12377. return p->notify ? 1 : 0;
  12378. }
  12379. /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
  12380. \note this is currently broken as we have no way of telling the dialplan
  12381. engine whether a transfer succeeds or fails.
  12382. \todo Fix the transfer() dialplan function so that a transfer may fail
  12383. */
  12384. static int transmit_refer(struct sip_pvt *p, const char *dest)
  12385. {
  12386. struct sip_request req = {
  12387. .headers = 0,
  12388. };
  12389. char from[256];
  12390. const char *of;
  12391. char *c;
  12392. char referto[256];
  12393. int use_tls=FALSE;
  12394. if (sipdebug) {
  12395. ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
  12396. }
  12397. /* Are we transfering an inbound or outbound call ? */
  12398. if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  12399. of = get_header(&p->initreq, "To");
  12400. } else {
  12401. of = get_header(&p->initreq, "From");
  12402. }
  12403. ast_copy_string(from, of, sizeof(from));
  12404. of = get_in_brackets(from);
  12405. ast_string_field_set(p, from, of);
  12406. if (!strncasecmp(of, "sip:", 4)) {
  12407. of += 4;
  12408. } else if (!strncasecmp(of, "sips:", 5)) {
  12409. of += 5;
  12410. use_tls = TRUE;
  12411. } else {
  12412. ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
  12413. }
  12414. /* Get just the username part */
  12415. if (strchr(dest, '@')) {
  12416. c = NULL;
  12417. } else if ((c = strchr(of, '@'))) {
  12418. *c++ = '\0';
  12419. }
  12420. if (c) {
  12421. snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
  12422. } else {
  12423. snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
  12424. }
  12425. /* save in case we get 407 challenge */
  12426. sip_refer_allocate(p);
  12427. ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
  12428. ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
  12429. p->refer->status = REFER_SENT; /* Set refer status */
  12430. reqprep(&req, p, SIP_REFER, 0, 1);
  12431. add_header(&req, "Refer-To", referto);
  12432. add_header(&req, "Allow", ALLOWED_METHODS);
  12433. add_supported_header(p, &req);
  12434. if (!ast_strlen_zero(p->our_contact)) {
  12435. add_header(&req, "Referred-By", p->our_contact);
  12436. }
  12437. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  12438. /* We should propably wait for a NOTIFY here until we ack the transfer */
  12439. /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
  12440. /*! \todo In theory, we should hang around and wait for a reply, before
  12441. returning to the dial plan here. Don't know really how that would
  12442. affect the transfer() app or the pbx, but, well, to make this
  12443. useful we should have a STATUS code on transfer().
  12444. */
  12445. }
  12446. /*! \brief Send SIP INFO advice of charge message */
  12447. static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
  12448. {
  12449. struct sip_request req;
  12450. struct ast_str *str = ast_str_alloca(512);
  12451. const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
  12452. enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
  12453. reqprep(&req, p, SIP_INFO, 0, 1);
  12454. if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
  12455. ast_str_append(&str, 0, "type=active;");
  12456. } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
  12457. ast_str_append(&str, 0, "type=terminated;");
  12458. } else {
  12459. /* unsupported message type */
  12460. return -1;
  12461. }
  12462. switch (charging) {
  12463. case AST_AOC_CHARGE_FREE:
  12464. ast_str_append(&str, 0, "free-of-charge;");
  12465. break;
  12466. case AST_AOC_CHARGE_CURRENCY:
  12467. ast_str_append(&str, 0, "charging;");
  12468. ast_str_append(&str, 0, "charging-info=currency;");
  12469. ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
  12470. ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
  12471. if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
  12472. ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
  12473. }
  12474. break;
  12475. case AST_AOC_CHARGE_UNIT:
  12476. ast_str_append(&str, 0, "charging;");
  12477. ast_str_append(&str, 0, "charging-info=pulse;");
  12478. if (unit_entry) {
  12479. ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
  12480. }
  12481. break;
  12482. default:
  12483. ast_str_append(&str, 0, "not-available;");
  12484. };
  12485. add_header(&req, "AOC", ast_str_buffer(str));
  12486. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  12487. }
  12488. /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
  12489. static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
  12490. {
  12491. struct sip_request req;
  12492. reqprep(&req, p, SIP_INFO, 0, 1);
  12493. add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
  12494. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  12495. }
  12496. /*! \brief Send SIP INFO with video update request */
  12497. static int transmit_info_with_vidupdate(struct sip_pvt *p)
  12498. {
  12499. struct sip_request req;
  12500. reqprep(&req, p, SIP_INFO, 0, 1);
  12501. add_vidupdate(&req);
  12502. return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
  12503. }
  12504. /*! \brief Transmit generic SIP request
  12505. returns XMIT_ERROR if transmit failed with a critical error (don't retry)
  12506. */
  12507. static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
  12508. {
  12509. struct sip_request resp;
  12510. reqprep(&resp, p, sipmethod, seqno, newbranch);
  12511. if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
  12512. add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
  12513. }
  12514. if (sipmethod == SIP_ACK) {
  12515. p->invitestate = INV_CONFIRMED;
  12516. }
  12517. return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
  12518. }
  12519. /*! \brief return the request and response header for a 401 or 407 code */
  12520. static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
  12521. {
  12522. if (code == WWW_AUTH) { /* 401 */
  12523. *header = "WWW-Authenticate";
  12524. *respheader = "Authorization";
  12525. } else if (code == PROXY_AUTH) { /* 407 */
  12526. *header = "Proxy-Authenticate";
  12527. *respheader = "Proxy-Authorization";
  12528. } else {
  12529. ast_verbose("-- wrong response code %u\n", code);
  12530. *header = *respheader = "Invalid";
  12531. }
  12532. }
  12533. /*! \brief Transmit SIP request, auth added */
  12534. static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
  12535. {
  12536. struct sip_request resp;
  12537. reqprep(&resp, p, sipmethod, seqno, newbranch);
  12538. if (!ast_strlen_zero(p->realm)) {
  12539. char digest[1024];
  12540. memset(digest, 0, sizeof(digest));
  12541. if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
  12542. char *dummy, *response;
  12543. enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
  12544. auth_headers(code, &dummy, &response);
  12545. add_header(&resp, response, digest);
  12546. } else {
  12547. ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
  12548. }
  12549. }
  12550. /* If we are hanging up and know a cause for that, send it in clear text to make
  12551. debugging easier. */
  12552. if (sipmethod == SIP_BYE) {
  12553. char buf[20];
  12554. if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
  12555. sprintf(buf, "Q.850;cause=%i", p->hangupcause & 0x7f);
  12556. add_header(&resp, "Reason", buf);
  12557. }
  12558. add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
  12559. snprintf(buf, sizeof(buf), "%d", p->hangupcause);
  12560. add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
  12561. }
  12562. return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
  12563. }
  12564. /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
  12565. static void destroy_association(struct sip_peer *peer)
  12566. {
  12567. int realtimeregs = ast_check_realtime("sipregs");
  12568. char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
  12569. if (!sip_cfg.ignore_regexpire) {
  12570. if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
  12571. ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
  12572. } else {
  12573. ast_db_del("SIP/Registry", peer->name);
  12574. ast_db_del("SIP/PeerMethods", peer->name);
  12575. }
  12576. }
  12577. }
  12578. static void set_socket_transport(struct sip_socket *socket, int transport)
  12579. {
  12580. /* if the transport type changes, clear all socket data */
  12581. if (socket->type != transport) {
  12582. socket->fd = -1;
  12583. socket->type = transport;
  12584. if (socket->tcptls_session) {
  12585. ao2_ref(socket->tcptls_session, -1);
  12586. socket->tcptls_session = NULL;
  12587. }
  12588. }
  12589. }
  12590. /*! \brief Expire registration of SIP peer */
  12591. static int expire_register(const void *data)
  12592. {
  12593. struct sip_peer *peer = (struct sip_peer *)data;
  12594. if (!peer) { /* Hmmm. We have no peer. Weird. */
  12595. return 0;
  12596. }
  12597. peer->expire = -1;
  12598. peer->portinuri = 0;
  12599. destroy_association(peer); /* remove registration data from storage */
  12600. set_socket_transport(&peer->socket, peer->default_outbound_transport);
  12601. if (peer->socket.tcptls_session) {
  12602. ao2_ref(peer->socket.tcptls_session, -1);
  12603. peer->socket.tcptls_session = NULL;
  12604. }
  12605. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
  12606. register_peer_exten(peer, FALSE); /* Remove regexten */
  12607. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  12608. /* Do we need to release this peer from memory?
  12609. Only for realtime peers and autocreated peers
  12610. */
  12611. if (peer->is_realtime) {
  12612. ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
  12613. }
  12614. if (peer->selfdestruct ||
  12615. ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
  12616. ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
  12617. }
  12618. if (!ast_sockaddr_isnull(&peer->addr)) {
  12619. /* We still need to unlink the peer from the peers_by_ip table,
  12620. * otherwise we end up with multiple copies hanging around each
  12621. * time a registration expires and the peer re-registers. */
  12622. ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
  12623. }
  12624. /* Only clear the addr after we check for destruction. The addr must remain
  12625. * in order to unlink from the peers_by_ip container correctly */
  12626. memset(&peer->addr, 0, sizeof(peer->addr));
  12627. unref_peer(peer, "removing peer ref for expire_register");
  12628. return 0;
  12629. }
  12630. /*! \brief Poke peer (send qualify to check if peer is alive and well) */
  12631. static int sip_poke_peer_s(const void *data)
  12632. {
  12633. struct sip_peer *peer = (struct sip_peer *)data;
  12634. struct sip_peer *foundpeer;
  12635. peer->pokeexpire = -1;
  12636. foundpeer = ao2_find(peers, peer, OBJ_POINTER);
  12637. if (!foundpeer) {
  12638. unref_peer(peer, "removing poke peer ref");
  12639. return 0;
  12640. } else if (foundpeer->name != peer->name) {
  12641. unref_peer(foundpeer, "removing above peer ref");
  12642. unref_peer(peer, "removing poke peer ref");
  12643. return 0;
  12644. }
  12645. unref_peer(foundpeer, "removing above peer ref");
  12646. sip_poke_peer(peer, 0);
  12647. unref_peer(peer, "removing poke peer ref");
  12648. return 0;
  12649. }
  12650. /*! \brief Get registration details from Asterisk DB */
  12651. static void reg_source_db(struct sip_peer *peer)
  12652. {
  12653. char data[256];
  12654. struct ast_sockaddr sa;
  12655. int expire;
  12656. char full_addr[128];
  12657. AST_DECLARE_APP_ARGS(args,
  12658. AST_APP_ARG(addr);
  12659. AST_APP_ARG(port);
  12660. AST_APP_ARG(expiry_str);
  12661. AST_APP_ARG(username);
  12662. AST_APP_ARG(contact);
  12663. );
  12664. /* If read-only RT backend, then refresh from local DB cache */
  12665. if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
  12666. return;
  12667. }
  12668. if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
  12669. return;
  12670. }
  12671. AST_NONSTANDARD_RAW_ARGS(args, data, ':');
  12672. snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
  12673. if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
  12674. return;
  12675. }
  12676. if (args.expiry_str) {
  12677. expire = atoi(args.expiry_str);
  12678. } else {
  12679. return;
  12680. }
  12681. if (args.username) {
  12682. ast_string_field_set(peer, username, args.username);
  12683. }
  12684. if (args.contact) {
  12685. ast_string_field_set(peer, fullcontact, args.contact);
  12686. }
  12687. ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
  12688. peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
  12689. ast_sockaddr_copy(&peer->addr, &sa);
  12690. if (peer->maxms) {
  12691. /* Don't poke peer immediately, just schedule it within qualifyfreq */
  12692. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
  12693. ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
  12694. sip_poke_peer_s, peer,
  12695. unref_peer(_data, "removing poke peer ref"),
  12696. unref_peer(peer, "removing poke peer ref"),
  12697. ref_peer(peer, "adding poke peer ref"));
  12698. }
  12699. AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
  12700. unref_peer(_data, "remove registration ref"),
  12701. unref_peer(peer, "remove registration ref"),
  12702. ref_peer(peer, "add registration ref"));
  12703. register_peer_exten(peer, TRUE);
  12704. }
  12705. /*! \brief Save contact header for 200 OK on INVITE */
  12706. static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
  12707. {
  12708. char contact[SIPBUFSIZE];
  12709. char *c;
  12710. /* Look for brackets */
  12711. ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
  12712. c = get_in_brackets(contact);
  12713. /* Save full contact to call pvt for later bye or re-invite */
  12714. ast_string_field_set(pvt, fullcontact, c);
  12715. /* Save URI for later ACKs, BYE or RE-invites */
  12716. ast_string_field_set(pvt, okcontacturi, c);
  12717. /* We should return false for URI:s we can't handle,
  12718. like tel:, mailto:,ldap: etc */
  12719. return TRUE;
  12720. }
  12721. /*! \brief parse uri in a way that allows semicolon stripping if legacy mode is enabled
  12722. *
  12723. * \note This calls parse_uri which has the unexpected property that passing more
  12724. * arguments results in more splitting. Most common is to leave out the pass
  12725. * argument, causing user to contain user:pass if available.
  12726. */
  12727. static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
  12728. {
  12729. int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
  12730. if (sip_cfg.legacy_useroption_parsing) { /* if legacy mode is active, strip semis from the user field */
  12731. char *p;
  12732. if ((p = strchr(uri, (int)';'))) {
  12733. *p = '\0';
  12734. }
  12735. }
  12736. return ret;
  12737. }
  12738. static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
  12739. {
  12740. char *hostport, *transport;
  12741. char contact_buf[256];
  12742. char *contact;
  12743. /* Work on a copy */
  12744. ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
  12745. contact = contact_buf;
  12746. /*
  12747. * We have only the part in <brackets> here so we just need to parse a SIP URI.
  12748. *
  12749. * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
  12750. * We still need to be able to send to the remote agent through the proxy.
  12751. */
  12752. if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
  12753. &transport)) {
  12754. ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
  12755. }
  12756. /* XXX This could block for a long time XXX */
  12757. /* We should only do this if it's a name, not an IP */
  12758. /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
  12759. to find transport, port address and hostname. If there's a port number, we have to
  12760. assume that the hostport part is a host name and only look for an A/AAAA record in DNS.
  12761. */
  12762. /* If we took in an invalid URI, hostport may not have been initialized */
  12763. /* ast_sockaddr_resolve requires an initialized hostport string. */
  12764. if (ast_strlen_zero(hostport)) {
  12765. ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
  12766. return -1;
  12767. }
  12768. if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
  12769. ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
  12770. "resolve in DNS) : '%s'\n", hostport);
  12771. return -1;
  12772. }
  12773. /* set port */
  12774. if (!ast_sockaddr_port(addr)) {
  12775. ast_sockaddr_set_port(addr,
  12776. (get_transport_str2enum(transport) ==
  12777. SIP_TRANSPORT_TLS ||
  12778. !strncasecmp(fullcontact, "sips", 4)) ?
  12779. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  12780. }
  12781. return 0;
  12782. }
  12783. /*! \brief Change the other partys IP address based on given contact */
  12784. static int set_address_from_contact(struct sip_pvt *pvt)
  12785. {
  12786. if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
  12787. /* NAT: Don't trust the contact field. Just use what they came to us
  12788. with. */
  12789. /*! \todo We need to save the TRANSPORT here too */
  12790. pvt->sa = pvt->recv;
  12791. return 0;
  12792. }
  12793. return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
  12794. }
  12795. /*! \brief Parse contact header and save registration (peer registration) */
  12796. static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
  12797. {
  12798. char contact[SIPBUFSIZE];
  12799. char data[SIPBUFSIZE];
  12800. const char *expires = get_header(req, "Expires");
  12801. int expire = atoi(expires);
  12802. char *curi = NULL, *hostport = NULL, *transport = NULL;
  12803. int transport_type;
  12804. const char *useragent;
  12805. struct ast_sockaddr oldsin, testsa;
  12806. char *firstcuri = NULL;
  12807. int start = 0;
  12808. int wildcard_found = 0;
  12809. int single_binding_found = 0;
  12810. ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
  12811. if (ast_strlen_zero(expires)) { /* No expires header, try look in Contact: */
  12812. char *s = strcasestr(contact, ";expires=");
  12813. if (s) {
  12814. expires = strsep(&s, ";"); /* trim ; and beyond */
  12815. if (sscanf(expires + 9, "%30d", &expire) != 1) {
  12816. expire = default_expiry;
  12817. }
  12818. } else {
  12819. /* Nothing has been specified */
  12820. expire = default_expiry;
  12821. }
  12822. }
  12823. if (expire > max_expiry) {
  12824. expire = max_expiry;
  12825. }
  12826. if (expire < min_expiry && expire != 0) {
  12827. expire = min_expiry;
  12828. }
  12829. pvt->expiry = expire;
  12830. copy_socket_data(&pvt->socket, &req->socket);
  12831. do {
  12832. /* Look for brackets */
  12833. curi = contact;
  12834. if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
  12835. strsep(&curi, ";"); /* This is Header options, not URI options */
  12836. curi = get_in_brackets(contact);
  12837. if (!firstcuri) {
  12838. firstcuri = ast_strdupa(curi);
  12839. }
  12840. if (!strcasecmp(curi, "*")) {
  12841. wildcard_found = 1;
  12842. } else {
  12843. single_binding_found = 1;
  12844. }
  12845. if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
  12846. /* Contact header parameter "*" detected, so punt if: Expires header is missing,
  12847. * Expires value is not zero, or another Contact header is present. */
  12848. return PARSE_REGISTER_FAILED;
  12849. }
  12850. ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
  12851. } while (!ast_strlen_zero(contact));
  12852. curi = firstcuri;
  12853. /* if they did not specify Contact: or Expires:, they are querying
  12854. what we currently have stored as their contact address, so return
  12855. it
  12856. */
  12857. if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
  12858. /* If we have an active registration, tell them when the registration is going to expire */
  12859. if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
  12860. pvt->expiry = ast_sched_when(sched, peer->expire);
  12861. }
  12862. return PARSE_REGISTER_QUERY;
  12863. } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
  12864. /* This means remove all registrations and return OK */
  12865. AST_SCHED_DEL_UNREF(sched, peer->expire,
  12866. unref_peer(peer, "remove register expire ref"));
  12867. ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
  12868. expire_register(ref_peer(peer,"add ref for explicit expire_register"));
  12869. return PARSE_REGISTER_UPDATE;
  12870. }
  12871. /* Store whatever we got as a contact from the client */
  12872. ast_string_field_set(peer, fullcontact, curi);
  12873. /* For the 200 OK, we should use the received contact */
  12874. ast_string_field_build(pvt, our_contact, "<%s>", curi);
  12875. /* Make sure it's a SIP URL */
  12876. if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
  12877. ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
  12878. }
  12879. /* handle the transport type specified in Contact header. */
  12880. if (!(transport_type = get_transport_str2enum(transport))) {
  12881. transport_type = pvt->socket.type;
  12882. }
  12883. /* if the peer's socket type is different than the Registration
  12884. * transport type, change it. If it got this far, it is a
  12885. * supported type, but check just in case */
  12886. if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
  12887. set_socket_transport(&peer->socket, transport_type);
  12888. }
  12889. oldsin = peer->addr;
  12890. /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
  12891. if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
  12892. ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
  12893. }
  12894. if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
  12895. /* use the data provided in the Contact header for call routing */
  12896. ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
  12897. /* XXX This could block for a long time XXX */
  12898. /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
  12899. if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
  12900. ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
  12901. ast_string_field_set(peer, fullcontact, "");
  12902. ast_string_field_set(pvt, our_contact, "");
  12903. return PARSE_REGISTER_FAILED;
  12904. }
  12905. /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
  12906. The hostport part is actually a host. */
  12907. peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
  12908. if (!ast_sockaddr_port(&testsa)) {
  12909. ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
  12910. }
  12911. ast_sockaddr_copy(&peer->addr, &testsa);
  12912. } else {
  12913. /* Don't trust the contact field. Just use what they came to us
  12914. with */
  12915. ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
  12916. peer->addr = pvt->recv;
  12917. }
  12918. /* Check that they're allowed to register at this IP */
  12919. if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
  12920. ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
  12921. ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
  12922. ast_sockaddr_stringify_addr(&peer->addr));
  12923. ast_string_field_set(peer, fullcontact, "");
  12924. ast_string_field_set(pvt, our_contact, "");
  12925. return PARSE_REGISTER_DENIED;
  12926. }
  12927. /* if the Contact header information copied into peer->addr matches the
  12928. * received address, and the transport types are the same, then copy socket
  12929. * data into the peer struct */
  12930. if ((peer->socket.type == pvt->socket.type) &&
  12931. !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
  12932. copy_socket_data(&peer->socket, &pvt->socket);
  12933. }
  12934. /* Now that our address has been updated put ourselves back into the container for lookups */
  12935. if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  12936. ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
  12937. }
  12938. /* Save SIP options profile */
  12939. peer->sipoptions = pvt->sipoptions;
  12940. if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
  12941. ast_string_field_set(peer, username, curi);
  12942. }
  12943. AST_SCHED_DEL_UNREF(sched, peer->expire,
  12944. unref_peer(peer, "remove register expire ref"));
  12945. if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  12946. peer->expire = -1;
  12947. } else {
  12948. peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
  12949. ref_peer(peer, "add registration ref"));
  12950. if (peer->expire == -1) {
  12951. unref_peer(peer, "remote registration ref");
  12952. }
  12953. }
  12954. snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
  12955. expire, peer->username, peer->fullcontact);
  12956. /* We might not immediately be able to reconnect via TCP, but try caching it anyhow */
  12957. if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
  12958. ast_db_put("SIP/Registry", peer->name, data);
  12959. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\n", peer->name, ast_sockaddr_stringify(&peer->addr));
  12960. /* Is this a new IP address for us? */
  12961. if (VERBOSITY_ATLEAST(2) && ast_sockaddr_cmp(&peer->addr, &oldsin)) {
  12962. ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s\n", peer->name,
  12963. ast_sockaddr_stringify(&peer->addr));
  12964. }
  12965. sip_pvt_unlock(pvt);
  12966. sip_poke_peer(peer, 0);
  12967. sip_pvt_lock(pvt);
  12968. register_peer_exten(peer, 1);
  12969. /* Save User agent */
  12970. useragent = get_header(req, "User-Agent");
  12971. if (strcasecmp(useragent, peer->useragent)) {
  12972. ast_string_field_set(peer, useragent, useragent);
  12973. ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
  12974. }
  12975. return PARSE_REGISTER_UPDATE;
  12976. }
  12977. /*! \brief Remove route from route list */
  12978. static void free_old_route(struct sip_route *route)
  12979. {
  12980. struct sip_route *next;
  12981. while (route) {
  12982. next = route->next;
  12983. ast_free(route);
  12984. route = next;
  12985. }
  12986. }
  12987. /*! \brief List all routes - mostly for debugging */
  12988. static void list_route(struct sip_route *route)
  12989. {
  12990. if (!route) {
  12991. ast_verbose("list_route: no route\n");
  12992. } else {
  12993. for (;route; route = route->next)
  12994. ast_verbose("list_route: hop: <%s>\n", route->hop);
  12995. }
  12996. }
  12997. /*! \brief Build route list from Record-Route header
  12998. \param resp the SIP response code or 0 for a request */
  12999. static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
  13000. {
  13001. struct sip_route *thishop, *head, *tail;
  13002. int start = 0;
  13003. int len;
  13004. const char *rr, *c;
  13005. /* Once a persistent route is set, don't fool with it */
  13006. if (p->route && p->route_persistent) {
  13007. ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
  13008. return;
  13009. }
  13010. if (p->route) {
  13011. free_old_route(p->route);
  13012. p->route = NULL;
  13013. }
  13014. /* We only want to create the route set the first time this is called except
  13015. it is called from a provisional response.*/
  13016. if ((resp < 100) || (resp > 199)) {
  13017. p->route_persistent = 1;
  13018. }
  13019. /* Build a tailq, then assign it to p->route when done.
  13020. * If backwards, we add entries from the head so they end up
  13021. * in reverse order. However, we do need to maintain a correct
  13022. * tail pointer because the contact is always at the end.
  13023. */
  13024. head = NULL;
  13025. tail = head;
  13026. /* 1st we pass through all the hops in any Record-Route headers */
  13027. for (;;) {
  13028. /* Each Record-Route header */
  13029. int len = 0;
  13030. const char *uri;
  13031. rr = __get_header(req, "Record-Route", &start);
  13032. if (*rr == '\0') {
  13033. break;
  13034. }
  13035. while (!get_in_brackets_const(rr, &uri, &len)) {
  13036. len++;
  13037. rr = strchr(rr, ',');
  13038. if(rr >= uri && rr < (uri + len)) {
  13039. /* comma inside brackets*/
  13040. const char *next_br = strchr(rr, '<');
  13041. if (next_br && next_br < (uri + len)) {
  13042. rr++;
  13043. continue;
  13044. }
  13045. continue;
  13046. }
  13047. if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
  13048. ast_copy_string(thishop->hop, uri, len);
  13049. ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
  13050. /* Link in */
  13051. if (backwards) {
  13052. /* Link in at head so they end up in reverse order */
  13053. thishop->next = head;
  13054. head = thishop;
  13055. /* If this was the first then it'll be the tail */
  13056. if (!tail) {
  13057. tail = thishop;
  13058. }
  13059. } else {
  13060. thishop->next = NULL;
  13061. /* Link in at the end */
  13062. if (tail) {
  13063. tail->next = thishop;
  13064. } else {
  13065. head = thishop;
  13066. }
  13067. tail = thishop;
  13068. }
  13069. }
  13070. rr = strchr(uri + len, ',');
  13071. if (rr == NULL) {
  13072. /* No more field-values, we're done with this header */
  13073. break;
  13074. }
  13075. /* Advance past comma */
  13076. rr++;
  13077. }
  13078. }
  13079. /* Only append the contact if we are dealing with a strict router */
  13080. if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
  13081. /* 2nd append the Contact: if there is one */
  13082. /* Can be multiple Contact headers, comma separated values - we just take the first */
  13083. char *contact = ast_strdupa(get_header(req, "Contact"));
  13084. if (!ast_strlen_zero(contact)) {
  13085. ast_debug(2, "build_route: Contact hop: %s\n", contact);
  13086. /* Look for <: delimited address */
  13087. c = get_in_brackets(contact);
  13088. len = strlen(c) + 1;
  13089. if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
  13090. /* ast_calloc is not needed because all fields are initialized in this block */
  13091. ast_copy_string(thishop->hop, c, len);
  13092. thishop->next = NULL;
  13093. /* Goes at the end */
  13094. if (tail) {
  13095. tail->next = thishop;
  13096. } else {
  13097. head = thishop;
  13098. }
  13099. }
  13100. }
  13101. }
  13102. /* Store as new route */
  13103. p->route = head;
  13104. /* For debugging dump what we ended up with */
  13105. if (sip_debug_test_pvt(p)) {
  13106. list_route(p->route);
  13107. }
  13108. }
  13109. /*! \brief builds the sip_pvt's randdata field which is used for the nonce
  13110. * challenge. When forceupdate is not set, the nonce is only updated if
  13111. * the current one is stale. In this case, a stalenonce is one which
  13112. * has already received a response, if a nonce has not received a response
  13113. * it is not always necessary or beneficial to create a new one. */
  13114. static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
  13115. {
  13116. if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
  13117. ast_string_field_build(p, randdata, "%08lx", (unsigned long)ast_random()); /* Create nonce for challenge */
  13118. p->stalenonce = 0;
  13119. }
  13120. }
  13121. AST_THREADSTORAGE(check_auth_buf);
  13122. #define CHECK_AUTH_BUF_INITLEN 256
  13123. /*! \brief Check user authorization from peer definition
  13124. Some actions, like REGISTER and INVITEs from peers require
  13125. authentication (if peer have secret set)
  13126. \return 0 on success, non-zero on error
  13127. */
  13128. static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
  13129. const char *secret, const char *md5secret, int sipmethod,
  13130. const char *uri, enum xmittype reliable, int ignore)
  13131. {
  13132. const char *response;
  13133. char *reqheader, *respheader;
  13134. const char *authtoken;
  13135. char a1_hash[256];
  13136. char resp_hash[256]="";
  13137. char *c;
  13138. int is_bogus_peer = 0;
  13139. int wrongnonce = FALSE;
  13140. int good_response;
  13141. const char *usednonce = p->randdata;
  13142. struct ast_str *buf;
  13143. int res;
  13144. /* table of recognised keywords, and their value in the digest */
  13145. enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
  13146. struct x {
  13147. const char *key;
  13148. const char *s;
  13149. } *i, keys[] = {
  13150. [K_RESP] = { "response=", "" },
  13151. [K_URI] = { "uri=", "" },
  13152. [K_USER] = { "username=", "" },
  13153. [K_NONCE] = { "nonce=", "" },
  13154. [K_LAST] = { NULL, NULL}
  13155. };
  13156. /* Always OK if no secret */
  13157. if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
  13158. return AUTH_SUCCESSFUL;
  13159. /* Always auth with WWW-auth since we're NOT a proxy */
  13160. /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
  13161. response = "401 Unauthorized";
  13162. /*
  13163. * Note the apparent swap of arguments below, compared to other
  13164. * usages of auth_headers().
  13165. */
  13166. auth_headers(WWW_AUTH, &respheader, &reqheader);
  13167. authtoken = get_header(req, reqheader);
  13168. if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
  13169. /* This is a retransmitted invite/register/etc, don't reconstruct authentication
  13170. information */
  13171. if (!reliable) {
  13172. /* Resend message if this was NOT a reliable delivery. Otherwise the
  13173. retransmission should get it */
  13174. transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
  13175. /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
  13176. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  13177. }
  13178. return AUTH_CHALLENGE_SENT;
  13179. } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
  13180. /* We have no auth, so issue challenge and request authentication */
  13181. set_nonce_randdata(p, 1); /* Create nonce for challenge */
  13182. transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
  13183. /* Schedule auto destroy in 32 seconds */
  13184. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  13185. return AUTH_CHALLENGE_SENT;
  13186. }
  13187. /* --- We have auth, so check it */
  13188. /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
  13189. an example in the spec of just what it is you're doing a hash on. */
  13190. if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
  13191. return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
  13192. }
  13193. /* Make a copy of the response and parse it */
  13194. res = ast_str_set(&buf, 0, "%s", authtoken);
  13195. if (res == AST_DYNSTR_BUILD_FAILED) {
  13196. return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
  13197. }
  13198. c = buf->str;
  13199. while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
  13200. for (i = keys; i->key != NULL; i++) {
  13201. const char *separator = ","; /* default */
  13202. if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
  13203. continue;
  13204. }
  13205. /* Found. Skip keyword, take text in quotes or up to the separator. */
  13206. c += strlen(i->key);
  13207. if (*c == '"') { /* in quotes. Skip first and look for last */
  13208. c++;
  13209. separator = "\"";
  13210. }
  13211. i->s = c;
  13212. strsep(&c, separator);
  13213. break;
  13214. }
  13215. if (i->key == NULL) { /* not found, jump after space or comma */
  13216. strsep(&c, " ,");
  13217. }
  13218. }
  13219. /* We cannot rely on the bogus_peer having a bad md5 value. Someone could
  13220. * use it to construct valid auth. */
  13221. if (md5secret && strcmp(md5secret, BOGUS_PEER_MD5SECRET) == 0) {
  13222. is_bogus_peer = 1;
  13223. }
  13224. /* Verify that digest username matches the username we auth as */
  13225. if (strcmp(username, keys[K_USER].s) && !is_bogus_peer) {
  13226. ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
  13227. username, keys[K_USER].s);
  13228. /* Oops, we're trying something here */
  13229. return AUTH_USERNAME_MISMATCH;
  13230. }
  13231. /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
  13232. * If this check fails, send 401 with new nonce */
  13233. if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
  13234. wrongnonce = TRUE;
  13235. usednonce = keys[K_NONCE].s;
  13236. } else {
  13237. p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
  13238. }
  13239. if (!ast_strlen_zero(md5secret)) {
  13240. ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
  13241. } else {
  13242. char a1[256];
  13243. snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
  13244. ast_md5_hash(a1_hash, a1);
  13245. }
  13246. /* compute the expected response to compare with what we received */
  13247. {
  13248. char a2[256];
  13249. char a2_hash[256];
  13250. char resp[256];
  13251. snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
  13252. S_OR(keys[K_URI].s, uri));
  13253. ast_md5_hash(a2_hash, a2);
  13254. snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
  13255. ast_md5_hash(resp_hash, resp);
  13256. }
  13257. good_response = keys[K_RESP].s &&
  13258. !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash)) &&
  13259. !is_bogus_peer; /* lastly, check that the peer isn't the fake peer */
  13260. if (wrongnonce) {
  13261. if (good_response) {
  13262. if (sipdebug)
  13263. ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
  13264. /* We got working auth token, based on stale nonce . */
  13265. set_nonce_randdata(p, 0);
  13266. transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
  13267. } else {
  13268. /* Everything was wrong, so give the device one more try with a new challenge */
  13269. if (!req->ignore) {
  13270. if (sipdebug) {
  13271. ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
  13272. }
  13273. set_nonce_randdata(p, 1);
  13274. } else {
  13275. if (sipdebug) {
  13276. ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
  13277. }
  13278. }
  13279. transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
  13280. }
  13281. /* Schedule auto destroy in 32 seconds */
  13282. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  13283. return AUTH_CHALLENGE_SENT;
  13284. }
  13285. if (good_response) {
  13286. append_history(p, "AuthOK", "Auth challenge successful for %s", username);
  13287. return AUTH_SUCCESSFUL;
  13288. }
  13289. /* Ok, we have a bad username/secret pair */
  13290. /* Tell the UAS not to re-send this authentication data, because
  13291. it will continue to fail
  13292. */
  13293. return AUTH_SECRET_FAILED;
  13294. }
  13295. /*! \brief Change onhold state of a peer using a pvt structure */
  13296. static void sip_peer_hold(struct sip_pvt *p, int hold)
  13297. {
  13298. if (!p->relatedpeer) {
  13299. return;
  13300. }
  13301. /* If they put someone on hold, increment the value... otherwise decrement it */
  13302. ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
  13303. /* Request device state update */
  13304. ast_devstate_changed(AST_DEVICE_UNKNOWN, (p->owner->flags & AST_FLAG_DISABLE_DEVSTATE_CACHE ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE),
  13305. "SIP/%s", p->relatedpeer->name);
  13306. return;
  13307. }
  13308. /*! \brief Receive MWI events that we have subscribed to */
  13309. static void mwi_event_cb(const struct ast_event *event, void *userdata)
  13310. {
  13311. struct sip_peer *peer = userdata;
  13312. sip_send_mwi_to_peer(peer, 0);
  13313. }
  13314. static void network_change_event_subscribe(void)
  13315. {
  13316. if (!network_change_event_subscription) {
  13317. network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
  13318. network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
  13319. }
  13320. }
  13321. static void network_change_event_unsubscribe(void)
  13322. {
  13323. if (network_change_event_subscription) {
  13324. network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
  13325. }
  13326. }
  13327. static int network_change_event_sched_cb(const void *data)
  13328. {
  13329. network_change_event_sched_id = -1;
  13330. sip_send_all_registers();
  13331. sip_send_all_mwi_subscriptions();
  13332. return 0;
  13333. }
  13334. static void network_change_event_cb(const struct ast_event *event, void *userdata)
  13335. {
  13336. ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
  13337. if (network_change_event_sched_id == -1) {
  13338. network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
  13339. }
  13340. }
  13341. static void cb_extensionstate_destroy(int id, void *data)
  13342. {
  13343. struct sip_pvt *p = data;
  13344. dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
  13345. }
  13346. /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
  13347. \note If you add an "hint" priority to the extension in the dial plan,
  13348. you will get notifications on device state changes */
  13349. static int cb_extensionstate(char *context, char* exten, int state, void *data)
  13350. {
  13351. struct sip_pvt *p = data;
  13352. sip_pvt_lock(p);
  13353. switch(state) {
  13354. case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
  13355. case AST_EXTENSION_REMOVED: /* Extension is gone */
  13356. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
  13357. ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
  13358. p->subscribed = NONE;
  13359. append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
  13360. break;
  13361. default: /* Tell user */
  13362. p->laststate = state;
  13363. break;
  13364. }
  13365. if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
  13366. if (!p->pendinginvite) {
  13367. transmit_state_notify(p, state, 1, FALSE);
  13368. } else {
  13369. /* We already have a NOTIFY sent that is not answered. Queue the state up.
  13370. if many state changes happen meanwhile, we will only send a notification of the last one */
  13371. ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
  13372. }
  13373. }
  13374. ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
  13375. ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
  13376. sip_pvt_unlock(p);
  13377. return 0;
  13378. }
  13379. /*! \brief Send a fake 401 Unauthorized response when the administrator
  13380. wants to hide the names of local devices from fishers
  13381. */
  13382. static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable)
  13383. {
  13384. /* We have to emulate EXACTLY what we'd get with a good peer
  13385. * and a bad password, or else we leak information. */
  13386. const char *response = "401 Unauthorized";
  13387. const char *reqheader = "Authorization";
  13388. const char *respheader = "WWW-Authenticate";
  13389. const char *authtoken;
  13390. struct ast_str *buf;
  13391. char *c;
  13392. /* table of recognised keywords, and their value in the digest */
  13393. enum keys { K_NONCE, K_LAST };
  13394. struct x {
  13395. const char *key;
  13396. const char *s;
  13397. } *i, keys[] = {
  13398. [K_NONCE] = { "nonce=", "" },
  13399. [K_LAST] = { NULL, NULL}
  13400. };
  13401. authtoken = get_header(req, reqheader);
  13402. if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
  13403. /* This is a retransmitted invite/register/etc, don't reconstruct authentication
  13404. * information */
  13405. transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
  13406. /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
  13407. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  13408. return;
  13409. } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
  13410. /* We have no auth, so issue challenge and request authentication */
  13411. set_nonce_randdata(p, 1);
  13412. transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
  13413. /* Schedule auto destroy in 32 seconds */
  13414. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  13415. return;
  13416. }
  13417. if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
  13418. __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
  13419. return;
  13420. }
  13421. /* Make a copy of the response and parse it */
  13422. if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
  13423. __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
  13424. return;
  13425. }
  13426. c = buf->str;
  13427. while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
  13428. for (i = keys; i->key != NULL; i++) {
  13429. const char *separator = ","; /* default */
  13430. if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
  13431. continue;
  13432. }
  13433. /* Found. Skip keyword, take text in quotes or up to the separator. */
  13434. c += strlen(i->key);
  13435. if (*c == '"') { /* in quotes. Skip first and look for last */
  13436. c++;
  13437. separator = "\"";
  13438. }
  13439. i->s = c;
  13440. strsep(&c, separator);
  13441. break;
  13442. }
  13443. if (i->key == NULL) { /* not found, jump after space or comma */
  13444. strsep(&c, " ,");
  13445. }
  13446. }
  13447. /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
  13448. if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
  13449. if (!req->ignore) {
  13450. set_nonce_randdata(p, 1);
  13451. }
  13452. transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
  13453. /* Schedule auto destroy in 32 seconds */
  13454. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  13455. } else {
  13456. __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
  13457. }
  13458. }
  13459. /*!
  13460. * Terminate the uri at the first ';' or space.
  13461. * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
  13462. * but don't do it for the time being. Remember the uri format is:
  13463. * (User-parameters was added after RFC 3261)
  13464. *\verbatim
  13465. *
  13466. * sip:user:password;user-parameters@host:port;uri-parameters?headers
  13467. * sips:user:password;user-parameters@host:port;uri-parameters?headers
  13468. *
  13469. *\endverbatim
  13470. * \todo As this function does not support user-parameters, it's considered broken
  13471. * and needs fixing.
  13472. */
  13473. static char *terminate_uri(char *uri)
  13474. {
  13475. char *t = uri;
  13476. while (*t && *t > ' ' && *t != ';') {
  13477. t++;
  13478. }
  13479. *t = '\0';
  13480. return uri;
  13481. }
  13482. /*! \brief Terminate a host:port at the ':'
  13483. * \param hostport The address of the hostport string
  13484. *
  13485. * \note In the case of a bracket-enclosed IPv6 address, the hostport variable
  13486. * will contain the non-bracketed host as a result of calling this function.
  13487. */
  13488. static void extract_host_from_hostport(char **hostport)
  13489. {
  13490. char *dont_care;
  13491. ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
  13492. }
  13493. /*! \internal \brief Helper function to update a peer's lastmsgssent value
  13494. */
  13495. static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
  13496. {
  13497. if (!locked) {
  13498. ao2_lock(peer);
  13499. }
  13500. peer->lastmsgssent = value;
  13501. if (!locked) {
  13502. ao2_unlock(peer);
  13503. }
  13504. }
  13505. /*! \brief Verify registration of user
  13506. - Registration is done in several steps, first a REGISTER without auth
  13507. to get a challenge (nonce) then a second one with auth
  13508. - Registration requests are only matched with peers that are marked as "dynamic"
  13509. */
  13510. static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
  13511. struct sip_request *req, const char *uri)
  13512. {
  13513. enum check_auth_result res = AUTH_NOT_FOUND;
  13514. struct sip_peer *peer;
  13515. char tmp[256];
  13516. char *c, *name, *unused_password, *domain;
  13517. char *uri2 = ast_strdupa(uri);
  13518. int send_mwi = 0;
  13519. terminate_uri(uri2);
  13520. ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
  13521. c = get_in_brackets(tmp);
  13522. c = remove_uri_parameters(c);
  13523. if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
  13524. ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
  13525. return -1;
  13526. }
  13527. SIP_PEDANTIC_DECODE(name);
  13528. SIP_PEDANTIC_DECODE(domain);
  13529. extract_host_from_hostport(&domain);
  13530. if (ast_strlen_zero(domain)) {
  13531. /* <sip:name@[EMPTY]>, never good */
  13532. transmit_response(p, "404 Not found", &p->initreq);
  13533. return AUTH_UNKNOWN_DOMAIN;
  13534. }
  13535. if (ast_strlen_zero(name)) {
  13536. /* <sip:[EMPTY][@]hostport>, unsure whether valid for
  13537. * registration. RFC 3261, 10.2 states:
  13538. * "The To header field and the Request-URI field typically
  13539. * differ, as the former contains a user name."
  13540. * But, Asterisk has always treated the domain-only uri as a
  13541. * username: we allow admins to create accounts described by
  13542. * domain name. */
  13543. name = domain;
  13544. }
  13545. /* This here differs from 1.4 and 1.6: the domain matching ACLs were
  13546. * skipped if it was a domain-only URI (used as username). Here we treat
  13547. * <sip:hostport> as <sip:host@hostport> and won't forget to test the
  13548. * domain ACLs against host. */
  13549. if (!AST_LIST_EMPTY(&domain_list)) {
  13550. if (!check_sip_domain(domain, NULL, 0)) {
  13551. if (sip_cfg.alwaysauthreject) {
  13552. transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
  13553. } else {
  13554. transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
  13555. }
  13556. return AUTH_UNKNOWN_DOMAIN;
  13557. }
  13558. }
  13559. ast_string_field_set(p, exten, name);
  13560. build_contact(p);
  13561. if (req->ignore) {
  13562. /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
  13563. const char *expires = get_header(req, "Expires");
  13564. int expire = atoi(expires);
  13565. if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
  13566. if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
  13567. expire = atoi(expires + 9);
  13568. }
  13569. }
  13570. if (!ast_strlen_zero(expires) && expire == 0) {
  13571. transmit_response_with_date(p, "200 OK", req);
  13572. return 0;
  13573. }
  13574. }
  13575. peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
  13576. /* If we don't want username disclosure, use the bogus_peer when a user
  13577. * is not found. */
  13578. if (!peer && sip_cfg.alwaysauthreject && !sip_cfg.autocreatepeer) {
  13579. peer = bogus_peer;
  13580. ref_peer(peer, "register_verify: ref the bogus_peer");
  13581. }
  13582. if (!(peer && ast_apply_ha(peer->ha, addr))) {
  13583. /* Peer fails ACL check */
  13584. if (peer) {
  13585. unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
  13586. peer = NULL;
  13587. res = AUTH_ACL_FAILED;
  13588. } else {
  13589. res = AUTH_NOT_FOUND;
  13590. }
  13591. }
  13592. if (peer) {
  13593. ao2_lock(peer);
  13594. if (!peer->host_dynamic) {
  13595. ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
  13596. res = AUTH_PEER_NOT_DYNAMIC;
  13597. } else {
  13598. ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
  13599. if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
  13600. if (sip_cancel_destroy(p))
  13601. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  13602. if (check_request_transport(peer, req)) {
  13603. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  13604. transmit_response_with_date(p, "403 Forbidden", req);
  13605. res = AUTH_BAD_TRANSPORT;
  13606. } else {
  13607. /* We have a successful registration attempt with proper authentication,
  13608. now, update the peer */
  13609. switch (parse_register_contact(p, peer, req)) {
  13610. case PARSE_REGISTER_DENIED:
  13611. ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
  13612. transmit_response_with_date(p, "603 Denied", req);
  13613. res = 0;
  13614. break;
  13615. case PARSE_REGISTER_FAILED:
  13616. ast_log(LOG_WARNING, "Failed to parse contact info\n");
  13617. transmit_response_with_date(p, "400 Bad Request", req);
  13618. res = 0;
  13619. break;
  13620. case PARSE_REGISTER_QUERY:
  13621. ast_string_field_set(p, fullcontact, peer->fullcontact);
  13622. transmit_response_with_date(p, "200 OK", req);
  13623. res = 0;
  13624. break;
  13625. case PARSE_REGISTER_UPDATE:
  13626. ast_string_field_set(p, fullcontact, peer->fullcontact);
  13627. /* If expiry is 0, peer has been unregistered already */
  13628. if (p->expiry != 0) {
  13629. update_peer(peer, p->expiry);
  13630. }
  13631. /* Say OK and ask subsystem to retransmit msg counter */
  13632. transmit_response_with_date(p, "200 OK", req);
  13633. send_mwi = 1;
  13634. res = 0;
  13635. break;
  13636. }
  13637. }
  13638. }
  13639. }
  13640. ao2_unlock(peer);
  13641. }
  13642. if (!peer && sip_cfg.autocreatepeer) {
  13643. /* Create peer if we have autocreate mode enabled */
  13644. peer = temp_peer(name);
  13645. if (peer) {
  13646. ao2_t_link(peers, peer, "link peer into peer table");
  13647. if (!ast_sockaddr_isnull(&peer->addr)) {
  13648. ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
  13649. }
  13650. ao2_lock(peer);
  13651. if (sip_cancel_destroy(p))
  13652. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  13653. switch (parse_register_contact(p, peer, req)) {
  13654. case PARSE_REGISTER_DENIED:
  13655. ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
  13656. transmit_response_with_date(p, "403 Forbidden", req);
  13657. res = 0;
  13658. break;
  13659. case PARSE_REGISTER_FAILED:
  13660. ast_log(LOG_WARNING, "Failed to parse contact info\n");
  13661. transmit_response_with_date(p, "400 Bad Request", req);
  13662. res = 0;
  13663. break;
  13664. case PARSE_REGISTER_QUERY:
  13665. ast_string_field_set(p, fullcontact, peer->fullcontact);
  13666. transmit_response_with_date(p, "200 OK", req);
  13667. send_mwi = 1;
  13668. res = 0;
  13669. break;
  13670. case PARSE_REGISTER_UPDATE:
  13671. ast_string_field_set(p, fullcontact, peer->fullcontact);
  13672. /* Say OK and ask subsystem to retransmit msg counter */
  13673. transmit_response_with_date(p, "200 OK", req);
  13674. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\n", peer->name, ast_sockaddr_stringify(addr));
  13675. send_mwi = 1;
  13676. res = 0;
  13677. break;
  13678. }
  13679. ao2_unlock(peer);
  13680. }
  13681. }
  13682. if (!res) {
  13683. if (send_mwi) {
  13684. sip_pvt_unlock(p);
  13685. sip_send_mwi_to_peer(peer, 0);
  13686. sip_pvt_lock(p);
  13687. } else {
  13688. update_peer_lastmsgssent(peer, -1, 0);
  13689. }
  13690. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  13691. }
  13692. if (res < 0) {
  13693. switch (res) {
  13694. case AUTH_SECRET_FAILED:
  13695. /* Wrong password in authentication. Go away, don't try again until you fixed it */
  13696. transmit_response(p, "403 Forbidden", &p->initreq);
  13697. if (global_authfailureevents) {
  13698. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  13699. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  13700. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
  13701. "ChannelType: SIP\r\n"
  13702. "Peer: SIP/%s\r\n"
  13703. "PeerStatus: Rejected\r\n"
  13704. "Cause: AUTH_SECRET_FAILED\r\n"
  13705. "Address: %s\r\n"
  13706. "Port: %s\r\n",
  13707. name, peer_addr, peer_port);
  13708. }
  13709. break;
  13710. case AUTH_USERNAME_MISMATCH:
  13711. /* Username and digest username does not match.
  13712. Asterisk uses the From: username for authentication. We need the
  13713. devices to use the same authentication user name until we support
  13714. proper authentication by digest auth name */
  13715. case AUTH_NOT_FOUND:
  13716. case AUTH_PEER_NOT_DYNAMIC:
  13717. case AUTH_ACL_FAILED:
  13718. if (sip_cfg.alwaysauthreject) {
  13719. transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
  13720. if (global_authfailureevents) {
  13721. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  13722. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  13723. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
  13724. "ChannelType: SIP\r\n"
  13725. "Peer: SIP/%s\r\n"
  13726. "PeerStatus: Rejected\r\n"
  13727. "Cause: %s\r\n"
  13728. "Address: %s\r\n"
  13729. "Port: %s\r\n",
  13730. name,
  13731. res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
  13732. peer_addr, peer_port);
  13733. }
  13734. } else {
  13735. /* URI not found */
  13736. if (res == AUTH_PEER_NOT_DYNAMIC) {
  13737. transmit_response(p, "403 Forbidden", &p->initreq);
  13738. if (global_authfailureevents) {
  13739. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  13740. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  13741. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
  13742. "ChannelType: SIP\r\n"
  13743. "Peer: SIP/%s\r\n"
  13744. "PeerStatus: Rejected\r\n"
  13745. "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
  13746. "Address: %s\r\n"
  13747. "Port: %s\r\n",
  13748. name, peer_addr, peer_port);
  13749. }
  13750. } else {
  13751. transmit_response(p, "404 Not found", &p->initreq);
  13752. if (global_authfailureevents) {
  13753. const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
  13754. const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
  13755. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
  13756. "ChannelType: SIP\r\n"
  13757. "Peer: SIP/%s\r\n"
  13758. "PeerStatus: Rejected\r\n"
  13759. "Cause: %s\r\n"
  13760. "Address: %s\r\n"
  13761. "Port: %s\r\n",
  13762. name,
  13763. (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
  13764. peer_addr, peer_port);
  13765. }
  13766. }
  13767. }
  13768. break;
  13769. case AUTH_BAD_TRANSPORT:
  13770. default:
  13771. break;
  13772. }
  13773. }
  13774. if (peer) {
  13775. unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
  13776. }
  13777. return res;
  13778. }
  13779. /*! \brief Translate referring cause */
  13780. static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
  13781. if (!strcmp(reason, "unknown")) {
  13782. ast_string_field_set(p, redircause, "UNKNOWN");
  13783. } else if (!strcmp(reason, "user-busy")) {
  13784. ast_string_field_set(p, redircause, "BUSY");
  13785. } else if (!strcmp(reason, "no-answer")) {
  13786. ast_string_field_set(p, redircause, "NOANSWER");
  13787. } else if (!strcmp(reason, "unavailable")) {
  13788. ast_string_field_set(p, redircause, "UNREACHABLE");
  13789. } else if (!strcmp(reason, "unconditional")) {
  13790. ast_string_field_set(p, redircause, "UNCONDITIONAL");
  13791. } else if (!strcmp(reason, "time-of-day")) {
  13792. ast_string_field_set(p, redircause, "UNKNOWN");
  13793. } else if (!strcmp(reason, "do-not-disturb")) {
  13794. ast_string_field_set(p, redircause, "UNKNOWN");
  13795. } else if (!strcmp(reason, "deflection")) {
  13796. ast_string_field_set(p, redircause, "UNKNOWN");
  13797. } else if (!strcmp(reason, "follow-me")) {
  13798. ast_string_field_set(p, redircause, "UNKNOWN");
  13799. } else if (!strcmp(reason, "out-of-service")) {
  13800. ast_string_field_set(p, redircause, "UNREACHABLE");
  13801. } else if (!strcmp(reason, "away")) {
  13802. ast_string_field_set(p, redircause, "UNREACHABLE");
  13803. } else {
  13804. ast_string_field_set(p, redircause, "UNKNOWN");
  13805. }
  13806. }
  13807. /*! \brief Parse the parts of the P-Asserted-Identity header
  13808. * on an incoming packet. Returns 1 if a valid header is found
  13809. * and it is different from the current caller id.
  13810. */
  13811. static int get_pai(struct sip_pvt *p, struct sip_request *req)
  13812. {
  13813. char pai[256];
  13814. char privacy[64];
  13815. char *cid_num = NULL;
  13816. char *cid_name = NULL;
  13817. char emptyname[1] = "";
  13818. int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  13819. char *uri = NULL;
  13820. int is_anonymous = 0, do_update = 1, no_name = 0;
  13821. ast_copy_string(pai, get_header(req, "P-Asserted-Identity"), sizeof(pai));
  13822. if (ast_strlen_zero(pai)) {
  13823. return 0;
  13824. }
  13825. /* use the reqresp_parser function get_name_and_number*/
  13826. if (get_name_and_number(pai, &cid_name, &cid_num)) {
  13827. return 0;
  13828. }
  13829. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
  13830. ast_shrink_phone_number(cid_num);
  13831. }
  13832. uri = get_in_brackets(pai);
  13833. if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
  13834. callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  13835. /*XXX Assume no change in cid_num. Perhaps it should be
  13836. * blanked?
  13837. */
  13838. ast_free(cid_num);
  13839. is_anonymous = 1;
  13840. cid_num = (char *)p->cid_num;
  13841. }
  13842. ast_copy_string(privacy, get_header(req, "Privacy"), sizeof(privacy));
  13843. if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
  13844. callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  13845. }
  13846. if (!cid_name) {
  13847. no_name = 1;
  13848. cid_name = (char *)emptyname;
  13849. }
  13850. /* Only return true if the supplied caller id is different */
  13851. if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
  13852. do_update = 0;
  13853. } else {
  13854. ast_string_field_set(p, cid_num, cid_num);
  13855. ast_string_field_set(p, cid_name, cid_name);
  13856. p->callingpres = callingpres;
  13857. if (p->owner) {
  13858. ast_set_callerid(p->owner, cid_num, cid_name, NULL);
  13859. p->owner->caller.id.name.presentation = callingpres;
  13860. p->owner->caller.id.number.presentation = callingpres;
  13861. }
  13862. }
  13863. /* get_name_and_number allocates memory for cid_num and cid_name so we have to free it */
  13864. if (!is_anonymous) {
  13865. ast_free(cid_num);
  13866. }
  13867. if (!no_name) {
  13868. ast_free(cid_name);
  13869. }
  13870. return do_update;
  13871. }
  13872. /*! \brief Get name, number and presentation from remote party id header,
  13873. * returns true if a valid header was found and it was different from the
  13874. * current caller id.
  13875. */
  13876. static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
  13877. {
  13878. char tmp[256];
  13879. struct sip_request *req;
  13880. char *cid_num = "";
  13881. char *cid_name = "";
  13882. int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  13883. char *privacy = "";
  13884. char *screen = "";
  13885. char *start, *end;
  13886. if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
  13887. return 0;
  13888. req = oreq;
  13889. if (!req)
  13890. req = &p->initreq;
  13891. ast_copy_string(tmp, get_header(req, "Remote-Party-ID"), sizeof(tmp));
  13892. if (ast_strlen_zero(tmp)) {
  13893. return get_pai(p, req);
  13894. }
  13895. /*
  13896. * RPID is not:
  13897. * rpid = (name-addr / addr-spec) *(SEMI rpi-token)
  13898. * But it is:
  13899. * rpid = [display-name] LAQUOT addr-spec RAQUOT *(SEMI rpi-token)
  13900. * Ergo, calling parse_name_andor_addr() on it wouldn't be
  13901. * correct because that would allow addr-spec style too.
  13902. */
  13903. start = tmp;
  13904. /* Quoted (note that we're not dealing with escapes properly) */
  13905. if (*start == '"') {
  13906. *start++ = '\0';
  13907. end = strchr(start, '"');
  13908. if (!end)
  13909. return 0;
  13910. *end++ = '\0';
  13911. cid_name = start;
  13912. start = ast_skip_blanks(end);
  13913. /* Unquoted */
  13914. } else {
  13915. cid_name = start;
  13916. start = end = strchr(start, '<');
  13917. if (!start) {
  13918. return 0;
  13919. }
  13920. /* trim blanks if there are any. the mandatory NUL is done below */
  13921. while (--end >= cid_name && *end < 33) {
  13922. *end = '\0';
  13923. }
  13924. }
  13925. if (*start != '<')
  13926. return 0;
  13927. *start++ = '\0';
  13928. end = strchr(start, '@');
  13929. if (!end)
  13930. return 0;
  13931. *end++ = '\0';
  13932. if (strncasecmp(start, "sip:", 4))
  13933. return 0;
  13934. cid_num = start + 4;
  13935. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
  13936. ast_shrink_phone_number(cid_num);
  13937. start = end;
  13938. end = strchr(start, '>');
  13939. if (!end)
  13940. return 0;
  13941. *end++ = '\0';
  13942. if (*end) {
  13943. start = end;
  13944. if (*start != ';')
  13945. return 0;
  13946. *start++ = '\0';
  13947. while (!ast_strlen_zero(start)) {
  13948. end = strchr(start, ';');
  13949. if (end)
  13950. *end++ = '\0';
  13951. if (!strncasecmp(start, "privacy=", 8))
  13952. privacy = start + 8;
  13953. else if (!strncasecmp(start, "screen=", 7))
  13954. screen = start + 7;
  13955. start = end;
  13956. }
  13957. if (!strcasecmp(privacy, "full")) {
  13958. if (!strcasecmp(screen, "yes"))
  13959. callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
  13960. else if (!strcasecmp(screen, "no"))
  13961. callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  13962. } else {
  13963. if (!strcasecmp(screen, "yes"))
  13964. callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
  13965. else if (!strcasecmp(screen, "no"))
  13966. callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  13967. }
  13968. }
  13969. /* Only return true if the supplied caller id is different */
  13970. if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
  13971. return 0;
  13972. ast_string_field_set(p, cid_num, cid_num);
  13973. ast_string_field_set(p, cid_name, cid_name);
  13974. p->callingpres = callingpres;
  13975. if (p->owner) {
  13976. ast_set_callerid(p->owner, cid_num, cid_name, NULL);
  13977. p->owner->caller.id.name.presentation = callingpres;
  13978. p->owner->caller.id.number.presentation = callingpres;
  13979. }
  13980. return 1;
  13981. }
  13982. /*! \brief Get referring dnis */
  13983. static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
  13984. {
  13985. char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
  13986. char *params, *reason_param = NULL;
  13987. struct sip_request *req;
  13988. req = oreq ? oreq : &p->initreq;
  13989. ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
  13990. if (ast_strlen_zero(tmp))
  13991. return -1;
  13992. if ((params = strchr(tmp, '>'))) {
  13993. params = strchr(params, ';');
  13994. }
  13995. exten = get_in_brackets(tmp);
  13996. if (!strncasecmp(exten, "sip:", 4)) {
  13997. exten += 4;
  13998. } else if (!strncasecmp(exten, "sips:", 5)) {
  13999. exten += 5;
  14000. } else {
  14001. ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
  14002. return -1;
  14003. }
  14004. /* Get diversion-reason param if present */
  14005. if (params) {
  14006. *params = '\0'; /* Cut off parameters */
  14007. params++;
  14008. while (*params == ';' || *params == ' ')
  14009. params++;
  14010. /* Check if we have a reason parameter */
  14011. if ((reason_param = strcasestr(params, "reason="))) {
  14012. char *end;
  14013. reason_param+=7;
  14014. if ((end = strchr(reason_param, ';'))) {
  14015. *end = '\0';
  14016. }
  14017. /* Remove enclosing double-quotes */
  14018. if (*reason_param == '"')
  14019. reason_param = ast_strip_quoted(reason_param, "\"", "\"");
  14020. if (!ast_strlen_zero(reason_param)) {
  14021. sip_set_redirstr(p, reason_param);
  14022. if (p->owner) {
  14023. pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
  14024. pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
  14025. }
  14026. }
  14027. }
  14028. }
  14029. rdomain = exten;
  14030. rexten = strsep(&rdomain, "@"); /* trim anything after @ */
  14031. if (p->owner)
  14032. pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
  14033. if (sip_debug_test_pvt(p))
  14034. ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
  14035. /*ast_string_field_set(p, rdnis, rexten);*/
  14036. if (*tmp == '\"') {
  14037. char *end_quote;
  14038. rname = tmp + 1;
  14039. end_quote = strchr(rname, '\"');
  14040. if (end_quote) {
  14041. *end_quote = '\0';
  14042. }
  14043. }
  14044. if (number) {
  14045. *number = ast_strdup(rexten);
  14046. }
  14047. if (name && rname) {
  14048. *name = ast_strdup(rname);
  14049. }
  14050. if (reason && !ast_strlen_zero(reason_param)) {
  14051. *reason = sip_reason_str_to_code(reason_param);
  14052. }
  14053. return 0;
  14054. }
  14055. /*!
  14056. * \brief Find out who the call is for.
  14057. *
  14058. * \details
  14059. * We use the request uri as a destination.
  14060. * This code assumes authentication has been done, so that the
  14061. * device (peer/user) context is already set.
  14062. *
  14063. * \return 0 on success (found a matching extension), non-zero on failure
  14064. *
  14065. * \note If the incoming uri is a SIPS: uri, we are required to carry this across
  14066. * the dialplan, so that the outbound call also is a sips: call or encrypted
  14067. * IAX2 call. If that's not available, the call should FAIL.
  14068. */
  14069. static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
  14070. {
  14071. char tmp[256] = "", *uri, *unused_password, *domain;
  14072. RAII_VAR(char *, tmpf, NULL, ast_free);
  14073. char *from = NULL;
  14074. struct sip_request *req;
  14075. char *decoded_uri;
  14076. req = oreq;
  14077. if (!req) {
  14078. req = &p->initreq;
  14079. }
  14080. /* Find the request URI */
  14081. if (req->rlPart2)
  14082. ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
  14083. uri = ast_strdupa(get_in_brackets(tmp));
  14084. if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
  14085. ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
  14086. return SIP_GET_DEST_INVALID_URI;
  14087. }
  14088. SIP_PEDANTIC_DECODE(domain);
  14089. SIP_PEDANTIC_DECODE(uri);
  14090. extract_host_from_hostport(&domain);
  14091. if (ast_strlen_zero(uri)) {
  14092. /*
  14093. * Either there really was no extension found or the request
  14094. * URI had encoded nulls that made the string "empty". Use "s"
  14095. * as the extension.
  14096. */
  14097. uri = "s";
  14098. }
  14099. ast_string_field_set(p, domain, domain);
  14100. /* Now find the From: caller ID and name */
  14101. /* XXX Why is this done in get_destination? Isn't it already done?
  14102. Needs to be checked
  14103. */
  14104. tmpf = ast_strdup(get_header(req, "From"));
  14105. if (!ast_strlen_zero(tmpf)) {
  14106. from = get_in_brackets(tmpf);
  14107. if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
  14108. ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
  14109. return SIP_GET_DEST_INVALID_URI;
  14110. }
  14111. SIP_PEDANTIC_DECODE(from);
  14112. SIP_PEDANTIC_DECODE(domain);
  14113. extract_host_from_hostport(&domain);
  14114. ast_string_field_set(p, fromdomain, domain);
  14115. }
  14116. if (!AST_LIST_EMPTY(&domain_list)) {
  14117. char domain_context[AST_MAX_EXTENSION];
  14118. domain_context[0] = '\0';
  14119. if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
  14120. if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
  14121. ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
  14122. return SIP_GET_DEST_REFUSED;
  14123. }
  14124. }
  14125. /* If we don't have a peer (i.e. we're a guest call),
  14126. * overwrite the original context */
  14127. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
  14128. ast_string_field_set(p, context, domain_context);
  14129. }
  14130. }
  14131. /* If the request coming in is a subscription and subscribecontext has been specified use it */
  14132. if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
  14133. ast_string_field_set(p, context, p->subscribecontext);
  14134. }
  14135. if (sip_debug_test_pvt(p)) {
  14136. ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
  14137. }
  14138. /* Since extensions.conf can have unescaped characters, try matching a
  14139. * decoded uri in addition to the non-decoded uri. */
  14140. decoded_uri = ast_strdupa(uri);
  14141. ast_uri_decode(decoded_uri);
  14142. /* If this is a subscription we actually just need to see if a hint exists for the extension */
  14143. if (req->method == SIP_SUBSCRIBE) {
  14144. char hint[AST_MAX_EXTENSION];
  14145. int which = 0;
  14146. if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
  14147. (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
  14148. if (!oreq) {
  14149. ast_string_field_set(p, exten, which ? decoded_uri : uri);
  14150. }
  14151. return SIP_GET_DEST_EXTEN_FOUND;
  14152. } else {
  14153. return SIP_GET_DEST_EXTEN_NOT_FOUND;
  14154. }
  14155. } else {
  14156. struct ast_cc_agent *agent;
  14157. /* Check the dialplan for the username part of the request URI,
  14158. the domain will be stored in the SIPDOMAIN variable
  14159. Return 0 if we have a matching extension */
  14160. if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
  14161. if (!oreq) {
  14162. ast_string_field_set(p, exten, uri);
  14163. }
  14164. return SIP_GET_DEST_EXTEN_FOUND;
  14165. }
  14166. if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
  14167. || !strcmp(decoded_uri, ast_pickup_ext())) {
  14168. if (!oreq) {
  14169. ast_string_field_set(p, exten, decoded_uri);
  14170. }
  14171. return SIP_GET_DEST_EXTEN_FOUND;
  14172. }
  14173. if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
  14174. struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
  14175. /* This is a CC recall. We can set p's extension to the exten from
  14176. * the original INVITE
  14177. */
  14178. ast_string_field_set(p, exten, agent_pvt->original_exten);
  14179. /* And we need to let the CC core know that the caller is attempting
  14180. * his recall
  14181. */
  14182. ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
  14183. agent->device_name);
  14184. if (cc_recall_core_id) {
  14185. *cc_recall_core_id = agent->core_id;
  14186. }
  14187. ao2_ref(agent, -1);
  14188. return SIP_GET_DEST_EXTEN_FOUND;
  14189. }
  14190. }
  14191. if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
  14192. && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
  14193. || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
  14194. || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
  14195. /* Overlap dialing is enabled and we need more digits to match an extension. */
  14196. return SIP_GET_DEST_EXTEN_MATCHMORE;
  14197. }
  14198. return SIP_GET_DEST_EXTEN_NOT_FOUND;
  14199. }
  14200. /*! \brief Lock dialog lock and find matching pvt lock
  14201. \return a reference, remember to release it when done
  14202. */
  14203. static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
  14204. {
  14205. struct sip_pvt *sip_pvt_ptr;
  14206. struct sip_pvt tmp_dialog = {
  14207. .callid = callid,
  14208. };
  14209. if (totag) {
  14210. ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
  14211. }
  14212. /* Search dialogs and find the match */
  14213. sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
  14214. if (sip_pvt_ptr) {
  14215. /* Go ahead and lock it (and its owner) before returning */
  14216. sip_pvt_lock(sip_pvt_ptr);
  14217. if (sip_cfg.pedanticsipchecking) {
  14218. unsigned char frommismatch = 0, tomismatch = 0;
  14219. if (ast_strlen_zero(fromtag)) {
  14220. sip_pvt_unlock(sip_pvt_ptr);
  14221. ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
  14222. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
  14223. return NULL;
  14224. }
  14225. if (ast_strlen_zero(totag)) {
  14226. sip_pvt_unlock(sip_pvt_ptr);
  14227. ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
  14228. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
  14229. return NULL;
  14230. }
  14231. /* RFC 3891
  14232. * > 3. User Agent Server Behavior: Receiving a Replaces Header
  14233. * > The Replaces header contains information used to match an existing
  14234. * > SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE
  14235. * > with a Replaces header, the User Agent (UA) attempts to match this
  14236. * > information with a confirmed or early dialog. The User Agent Server
  14237. * > (UAS) matches the to-tag and from-tag parameters as if they were tags
  14238. * > present in an incoming request. In other words, the to-tag parameter
  14239. * > is compared to the local tag, and the from-tag parameter is compared
  14240. * > to the remote tag.
  14241. *
  14242. * Thus, the totag is always compared to the local tag, regardless if
  14243. * this our call is an incoming or outgoing call.
  14244. */
  14245. frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
  14246. tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
  14247. /* Don't check from if the dialog is not established, due to multi forking the from
  14248. * can change when the call is not answered yet.
  14249. */
  14250. if ((frommismatch && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) || tomismatch) {
  14251. sip_pvt_unlock(sip_pvt_ptr);
  14252. if (frommismatch) {
  14253. ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
  14254. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
  14255. fromtag, sip_pvt_ptr->theirtag);
  14256. }
  14257. if (tomismatch) {
  14258. ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
  14259. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
  14260. totag, sip_pvt_ptr->tag);
  14261. }
  14262. return NULL;
  14263. }
  14264. }
  14265. if (totag)
  14266. ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
  14267. sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
  14268. sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
  14269. /* deadlock avoidance... */
  14270. while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
  14271. sip_pvt_unlock(sip_pvt_ptr);
  14272. usleep(1);
  14273. sip_pvt_lock(sip_pvt_ptr);
  14274. }
  14275. }
  14276. return sip_pvt_ptr;
  14277. }
  14278. /*! \brief Call transfer support (the REFER method)
  14279. * Extracts Refer headers into pvt dialog structure
  14280. *
  14281. * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
  14282. * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
  14283. * flag.
  14284. */
  14285. static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
  14286. {
  14287. const char *p_referred_by = NULL;
  14288. char *h_refer_to = NULL;
  14289. char *h_referred_by = NULL;
  14290. char *refer_to;
  14291. const char *p_refer_to;
  14292. char *referred_by_uri = NULL;
  14293. char *ptr;
  14294. struct sip_request *req = NULL;
  14295. const char *transfer_context = NULL;
  14296. struct sip_refer *referdata;
  14297. req = outgoing_req;
  14298. referdata = transferer->refer;
  14299. if (!req) {
  14300. req = &transferer->initreq;
  14301. }
  14302. p_refer_to = get_header(req, "Refer-To");
  14303. if (ast_strlen_zero(p_refer_to)) {
  14304. ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
  14305. return -2; /* Syntax error */
  14306. }
  14307. h_refer_to = ast_strdupa(p_refer_to);
  14308. refer_to = get_in_brackets(h_refer_to);
  14309. if (!strncasecmp(refer_to, "sip:", 4)) {
  14310. refer_to += 4; /* Skip sip: */
  14311. } else if (!strncasecmp(refer_to, "sips:", 5)) {
  14312. refer_to += 5;
  14313. } else {
  14314. ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
  14315. return -3;
  14316. }
  14317. /* Get referred by header if it exists */
  14318. p_referred_by = get_header(req, "Referred-By");
  14319. /* Give useful transfer information to the dialplan */
  14320. if (transferer->owner) {
  14321. struct ast_channel *peer = ast_bridged_channel(transferer->owner);
  14322. if (peer) {
  14323. pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
  14324. pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
  14325. }
  14326. }
  14327. if (!ast_strlen_zero(p_referred_by)) {
  14328. char *lessthan;
  14329. h_referred_by = ast_strdupa(p_referred_by);
  14330. /* Store referrer's caller ID name */
  14331. ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
  14332. if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
  14333. *(lessthan - 1) = '\0'; /* Space */
  14334. }
  14335. referred_by_uri = get_in_brackets(h_referred_by);
  14336. if (!strncasecmp(referred_by_uri, "sip:", 4)) {
  14337. referred_by_uri += 4; /* Skip sip: */
  14338. } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
  14339. referred_by_uri += 5; /* Skip sips: */
  14340. } else {
  14341. ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
  14342. referred_by_uri = NULL;
  14343. }
  14344. }
  14345. /* Check for arguments in the refer_to header */
  14346. if ((ptr = strcasestr(refer_to, "replaces="))) {
  14347. char *to = NULL, *from = NULL;
  14348. /* This is an attended transfer */
  14349. referdata->attendedtransfer = 1;
  14350. ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
  14351. ast_uri_decode(referdata->replaces_callid);
  14352. if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
  14353. *ptr++ = '\0';
  14354. }
  14355. if (ptr) {
  14356. /* Find the different tags before we destroy the string */
  14357. to = strcasestr(ptr, "to-tag=");
  14358. from = strcasestr(ptr, "from-tag=");
  14359. }
  14360. /* Grab the to header */
  14361. if (to) {
  14362. ptr = to + 7;
  14363. if ((to = strchr(ptr, '&'))) {
  14364. *to = '\0';
  14365. }
  14366. if ((to = strchr(ptr, ';'))) {
  14367. *to = '\0';
  14368. }
  14369. ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
  14370. }
  14371. if (from) {
  14372. ptr = from + 9;
  14373. if ((to = strchr(ptr, '&'))) {
  14374. *to = '\0';
  14375. }
  14376. if ((to = strchr(ptr, ';'))) {
  14377. *to = '\0';
  14378. }
  14379. ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
  14380. }
  14381. if (!strcmp(referdata->replaces_callid, transferer->callid) &&
  14382. (!sip_cfg.pedanticsipchecking ||
  14383. (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
  14384. !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
  14385. ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
  14386. return -4;
  14387. }
  14388. if (!sip_cfg.pedanticsipchecking) {
  14389. ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
  14390. } else {
  14391. ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", referdata->replaces_callid, referdata->replaces_callid_fromtag ? referdata->replaces_callid_fromtag : "<none>", referdata->replaces_callid_totag ? referdata->replaces_callid_totag : "<none>" );
  14392. }
  14393. }
  14394. if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
  14395. char *urioption = NULL, *domain;
  14396. int bracket = 0;
  14397. *ptr++ = '\0';
  14398. if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
  14399. *urioption++ = '\0';
  14400. }
  14401. domain = ptr;
  14402. /* Remove :port */
  14403. for (; *ptr != '\0'; ++ptr) {
  14404. if (*ptr == ':' && bracket == 0) {
  14405. *ptr = '\0';
  14406. break;
  14407. } else if (*ptr == '[') {
  14408. ++bracket;
  14409. } else if (*ptr == ']') {
  14410. --bracket;
  14411. }
  14412. }
  14413. SIP_PEDANTIC_DECODE(domain);
  14414. SIP_PEDANTIC_DECODE(urioption);
  14415. /* Save the domain for the dial plan */
  14416. ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
  14417. if (urioption) {
  14418. ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
  14419. }
  14420. }
  14421. if ((ptr = strchr(refer_to, ';'))) /* Remove options */
  14422. *ptr = '\0';
  14423. SIP_PEDANTIC_DECODE(refer_to);
  14424. ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
  14425. if (referred_by_uri) {
  14426. if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
  14427. *ptr = '\0';
  14428. SIP_PEDANTIC_DECODE(referred_by_uri);
  14429. ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
  14430. } else {
  14431. referdata->referred_by[0] = '\0';
  14432. }
  14433. /* Determine transfer context */
  14434. if (transferer->owner) {
  14435. /* By default, use the context in the channel sending the REFER */
  14436. transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
  14437. if (ast_strlen_zero(transfer_context)) {
  14438. transfer_context = transferer->owner->macrocontext;
  14439. }
  14440. }
  14441. if (ast_strlen_zero(transfer_context)) {
  14442. transfer_context = S_OR(transferer->context, sip_cfg.default_context);
  14443. }
  14444. ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
  14445. /* Either an existing extension or the parking extension */
  14446. if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
  14447. if (sip_debug_test_pvt(transferer)) {
  14448. ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
  14449. }
  14450. /* We are ready to transfer to the extension */
  14451. return 0;
  14452. }
  14453. if (sip_debug_test_pvt(transferer))
  14454. ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
  14455. /* Failure, we can't find this extension */
  14456. return -1;
  14457. }
  14458. /*! \brief Call transfer support (old way, deprecated by the IETF)
  14459. * \note does not account for SIPS: uri requirements, nor check transport
  14460. */
  14461. static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
  14462. {
  14463. char tmp[256] = "", *c, *a;
  14464. struct sip_request *req = oreq ? oreq : &p->initreq;
  14465. struct sip_refer *referdata = NULL;
  14466. const char *transfer_context = NULL;
  14467. if (!p->refer && !sip_refer_allocate(p))
  14468. return -1;
  14469. referdata = p->refer;
  14470. ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
  14471. c = get_in_brackets(tmp);
  14472. if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
  14473. ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
  14474. return -1;
  14475. }
  14476. SIP_PEDANTIC_DECODE(c);
  14477. SIP_PEDANTIC_DECODE(a);
  14478. if (!ast_strlen_zero(a)) {
  14479. ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
  14480. }
  14481. if (sip_debug_test_pvt(p))
  14482. ast_verbose("Looking for %s in %s\n", c, p->context);
  14483. /* Determine transfer context */
  14484. if (p->owner) {
  14485. /* By default, use the context in the channel sending the REFER */
  14486. transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
  14487. if (ast_strlen_zero(transfer_context)) {
  14488. transfer_context = p->owner->macrocontext;
  14489. }
  14490. }
  14491. if (ast_strlen_zero(transfer_context)) {
  14492. transfer_context = S_OR(p->context, sip_cfg.default_context);
  14493. }
  14494. if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
  14495. /* This is a blind transfer */
  14496. ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
  14497. ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
  14498. ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
  14499. ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
  14500. /* Set new context */
  14501. ast_string_field_set(p, context, transfer_context);
  14502. return 0;
  14503. } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
  14504. return 1;
  14505. }
  14506. return -1;
  14507. }
  14508. /*! \brief check received= and rport= in a SIP response.
  14509. * If we get a response with received= and/or rport= in the Via:
  14510. * line, use them as 'p->ourip' (see RFC 3581 for rport,
  14511. * and RFC 3261 for received).
  14512. * Using these two fields SIP can produce the correct
  14513. * address and port in the SIP headers without the need for STUN.
  14514. * The address part is also reused for the media sessions.
  14515. * Note that ast_sip_ouraddrfor() still rewrites p->ourip
  14516. * if you specify externaddr/seternaddr/.
  14517. */
  14518. static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
  14519. {
  14520. char via[256];
  14521. char *cur, *opts;
  14522. ast_copy_string(via, get_header(req, "Via"), sizeof(via));
  14523. /* Work on the leftmost value of the topmost Via header */
  14524. opts = strchr(via, ',');
  14525. if (opts)
  14526. *opts = '\0';
  14527. /* parse all relevant options */
  14528. opts = strchr(via, ';');
  14529. if (!opts)
  14530. return; /* no options to parse */
  14531. *opts++ = '\0';
  14532. while ( (cur = strsep(&opts, ";")) ) {
  14533. if (!strncmp(cur, "rport=", 6)) {
  14534. int port = strtol(cur+6, NULL, 10);
  14535. /* XXX add error checking */
  14536. ast_sockaddr_set_port(&p->ourip, port);
  14537. } else if (!strncmp(cur, "received=", 9)) {
  14538. if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
  14539. ; /* XXX add error checking */
  14540. }
  14541. }
  14542. }
  14543. /*! \brief check Via: header for hostname, port and rport request/answer */
  14544. static void check_via(struct sip_pvt *p, const struct sip_request *req)
  14545. {
  14546. char via[512];
  14547. char *c, *maddr;
  14548. struct ast_sockaddr tmp = { { 0, } };
  14549. uint16_t port;
  14550. ast_copy_string(via, get_header(req, "Via"), sizeof(via));
  14551. /* Work on the leftmost value of the topmost Via header */
  14552. c = strchr(via, ',');
  14553. if (c)
  14554. *c = '\0';
  14555. /* Check for rport */
  14556. c = strstr(via, ";rport");
  14557. if (c && (c[6] != '=')) { /* rport query, not answer */
  14558. ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
  14559. ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
  14560. }
  14561. /* Check for maddr */
  14562. maddr = strstr(via, "maddr=");
  14563. if (maddr) {
  14564. maddr += 6;
  14565. c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
  14566. "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
  14567. *c = '\0';
  14568. }
  14569. c = strchr(via, ';');
  14570. if (c)
  14571. *c = '\0';
  14572. c = strchr(via, ' ');
  14573. if (c) {
  14574. *c = '\0';
  14575. c = ast_skip_blanks(c+1);
  14576. if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
  14577. ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
  14578. return;
  14579. }
  14580. if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
  14581. p->sa = p->recv;
  14582. }
  14583. if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
  14584. ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
  14585. port = STANDARD_SIP_PORT;
  14586. } else if (!(port = ast_sockaddr_port(&tmp))) {
  14587. port = STANDARD_SIP_PORT;
  14588. }
  14589. ast_sockaddr_set_port(&p->sa, port);
  14590. if (sip_debug_test_pvt(p)) {
  14591. ast_verbose("Sending to %s (%s)\n",
  14592. ast_sockaddr_stringify(sip_real_dst(p)),
  14593. sip_nat_mode(p));
  14594. }
  14595. }
  14596. }
  14597. /*! \brief Validate device authentication */
  14598. static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
  14599. struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
  14600. struct sip_peer **authpeer,
  14601. enum xmittype reliable, char *calleridname, char *uri2)
  14602. {
  14603. enum check_auth_result res;
  14604. int debug = sip_debug_test_addr(addr);
  14605. struct sip_peer *peer;
  14606. if (sipmethod == SIP_SUBSCRIBE) {
  14607. /* For subscribes, match on device name only; for other methods,
  14608. * match on IP address-port of the incoming request.
  14609. */
  14610. peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
  14611. } else {
  14612. /* First find devices based on username (avoid all type=peer's) */
  14613. peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
  14614. /* Then find devices based on IP */
  14615. if (!peer) {
  14616. peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
  14617. }
  14618. }
  14619. if (!peer) {
  14620. if (debug) {
  14621. ast_verbose("No matching peer for '%s' from '%s'\n",
  14622. of, ast_sockaddr_stringify(&p->recv));
  14623. }
  14624. /* If you don't mind, we can return 404s for devices that do
  14625. * not exist: username disclosure. If we allow guests, there
  14626. * is no way around that. */
  14627. if (sip_cfg.allowguest || !sip_cfg.alwaysauthreject) {
  14628. return AUTH_DONT_KNOW;
  14629. }
  14630. /* If you do mind, we use a peer that will never authenticate.
  14631. * This ensures that we follow the same code path as regular
  14632. * auth: less chance for username disclosure. */
  14633. peer = bogus_peer;
  14634. ref_peer(peer, "ref_peer: check_peer_ok: must ref bogus_peer so unreffing it does not fail");
  14635. }
  14636. if (!ast_apply_ha(peer->ha, addr)) {
  14637. ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
  14638. unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
  14639. return AUTH_ACL_FAILED;
  14640. }
  14641. if (debug && peer != bogus_peer) {
  14642. ast_verbose("Found peer '%s' for '%s' from %s\n",
  14643. peer->name, of, ast_sockaddr_stringify(&p->recv));
  14644. }
  14645. /* XXX what about p->prefs = peer->prefs; ? */
  14646. /* Set Frame packetization */
  14647. if (p->rtp) {
  14648. ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
  14649. p->autoframing = peer->autoframing;
  14650. }
  14651. /* Take the peer */
  14652. ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
  14653. ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  14654. ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  14655. if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
  14656. p->t38_maxdatagram = peer->t38_maxdatagram;
  14657. set_t38_capabilities(p);
  14658. }
  14659. /* Copy SIP extensions profile to peer */
  14660. /* XXX is this correct before a successful auth ? */
  14661. if (p->sipoptions)
  14662. peer->sipoptions = p->sipoptions;
  14663. do_setnat(p);
  14664. ast_string_field_set(p, peersecret, peer->secret);
  14665. ast_string_field_set(p, peermd5secret, peer->md5secret);
  14666. ast_string_field_set(p, subscribecontext, peer->subscribecontext);
  14667. ast_string_field_set(p, mohinterpret, peer->mohinterpret);
  14668. ast_string_field_set(p, mohsuggest, peer->mohsuggest);
  14669. if (!ast_strlen_zero(peer->parkinglot)) {
  14670. ast_string_field_set(p, parkinglot, peer->parkinglot);
  14671. }
  14672. ast_string_field_set(p, engine, peer->engine);
  14673. p->disallowed_methods = peer->disallowed_methods;
  14674. set_pvt_allowed_methods(p, req);
  14675. ast_cc_copy_config_params(p->cc_params, peer->cc_params);
  14676. if (peer->callingpres) /* Peer calling pres setting will override RPID */
  14677. p->callingpres = peer->callingpres;
  14678. if (peer->maxms && peer->lastms)
  14679. p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
  14680. else
  14681. p->timer_t1 = peer->timer_t1;
  14682. /* Set timer B to control transaction timeouts */
  14683. if (peer->timer_b)
  14684. p->timer_b = peer->timer_b;
  14685. else
  14686. p->timer_b = 64 * p->timer_t1;
  14687. p->allowtransfer = peer->allowtransfer;
  14688. if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
  14689. /* Pretend there is no required authentication */
  14690. ast_string_field_set(p, peersecret, NULL);
  14691. ast_string_field_set(p, peermd5secret, NULL);
  14692. }
  14693. if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
  14694. ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
  14695. ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  14696. ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  14697. /* If we have a call limit, set flag */
  14698. if (peer->call_limit)
  14699. ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
  14700. ast_string_field_set(p, peername, peer->name);
  14701. ast_string_field_set(p, authname, peer->name);
  14702. if (sipmethod == SIP_INVITE) {
  14703. /* destroy old channel vars and copy in new ones. */
  14704. ast_variables_destroy(p->chanvars);
  14705. p->chanvars = copy_vars(peer->chanvars);
  14706. }
  14707. if (authpeer) {
  14708. ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
  14709. (*authpeer) = peer; /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
  14710. }
  14711. if (!ast_strlen_zero(peer->username)) {
  14712. ast_string_field_set(p, username, peer->username);
  14713. /* Use the default username for authentication on outbound calls */
  14714. /* XXX this takes the name from the caller... can we override ? */
  14715. ast_string_field_set(p, authname, peer->username);
  14716. }
  14717. if (!get_rpid(p, req)) {
  14718. if (!ast_strlen_zero(peer->cid_num)) {
  14719. char *tmp = ast_strdupa(peer->cid_num);
  14720. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
  14721. ast_shrink_phone_number(tmp);
  14722. ast_string_field_set(p, cid_num, tmp);
  14723. }
  14724. if (!ast_strlen_zero(peer->cid_name))
  14725. ast_string_field_set(p, cid_name, peer->cid_name);
  14726. if (peer->callingpres)
  14727. p->callingpres = peer->callingpres;
  14728. }
  14729. if (!ast_strlen_zero(peer->cid_tag)) {
  14730. ast_string_field_set(p, cid_tag, peer->cid_tag);
  14731. }
  14732. ast_string_field_set(p, fullcontact, peer->fullcontact);
  14733. if (!ast_strlen_zero(peer->context)) {
  14734. ast_string_field_set(p, context, peer->context);
  14735. }
  14736. if (!ast_strlen_zero(peer->mwi_from)) {
  14737. ast_string_field_set(p, mwi_from, peer->mwi_from);
  14738. }
  14739. ast_string_field_set(p, peersecret, peer->secret);
  14740. ast_string_field_set(p, peermd5secret, peer->md5secret);
  14741. ast_string_field_set(p, language, peer->language);
  14742. ast_string_field_set(p, accountcode, peer->accountcode);
  14743. p->amaflags = peer->amaflags;
  14744. p->callgroup = peer->callgroup;
  14745. p->pickupgroup = peer->pickupgroup;
  14746. p->capability = peer->capability;
  14747. p->prefs = peer->prefs;
  14748. p->jointcapability = peer->capability;
  14749. if (peer->maxforwards > 0) {
  14750. p->maxforwards = peer->maxforwards;
  14751. }
  14752. if (p->peercapability)
  14753. p->jointcapability &= p->peercapability;
  14754. p->maxcallbitrate = peer->maxcallbitrate;
  14755. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
  14756. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
  14757. p->noncodeccapability |= AST_RTP_DTMF;
  14758. else
  14759. p->noncodeccapability &= ~AST_RTP_DTMF;
  14760. p->jointnoncodeccapability = p->noncodeccapability;
  14761. p->rtptimeout = peer->rtptimeout;
  14762. p->rtpholdtimeout = peer->rtpholdtimeout;
  14763. p->rtpkeepalive = peer->rtpkeepalive;
  14764. if (!dialog_initialize_rtp(p)) {
  14765. if (p->rtp) {
  14766. ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
  14767. p->autoframing = peer->autoframing;
  14768. }
  14769. } else {
  14770. res = AUTH_RTP_FAILED;
  14771. }
  14772. }
  14773. unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
  14774. return res;
  14775. }
  14776. /*! \brief Check if matching user or peer is defined
  14777. Match user on From: user name and peer on IP/port
  14778. This is used on first invite (not re-invites) and subscribe requests
  14779. \return 0 on success, non-zero on failure
  14780. */
  14781. static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
  14782. int sipmethod, const char *uri, enum xmittype reliable,
  14783. struct ast_sockaddr *addr, struct sip_peer **authpeer)
  14784. {
  14785. char *of, *name, *unused_password, *domain;
  14786. RAII_VAR(char *, ofbuf, NULL, ast_free); /* beware, everyone starts pointing to this */
  14787. RAII_VAR(char *, namebuf, NULL, ast_free);
  14788. enum check_auth_result res = AUTH_DONT_KNOW;
  14789. char calleridname[256];
  14790. char *uri2 = ast_strdupa(uri);
  14791. terminate_uri(uri2); /* trim extra stuff */
  14792. ofbuf = ast_strdup(get_header(req, "From"));
  14793. /* XXX here tries to map the username for invite things */
  14794. /* strip the display-name portion off the beginning of the FROM header. */
  14795. if (!(of = (char *) get_calleridname(ofbuf, calleridname, sizeof(calleridname)))) {
  14796. ast_log(LOG_ERROR, "FROM header can not be parsed\n");
  14797. return res;
  14798. }
  14799. if (calleridname[0]) {
  14800. ast_string_field_set(p, cid_name, calleridname);
  14801. }
  14802. if (ast_strlen_zero(p->exten)) {
  14803. char *t = uri2;
  14804. if (!strncasecmp(t, "sip:", 4))
  14805. t+= 4;
  14806. else if (!strncasecmp(t, "sips:", 5))
  14807. t += 5;
  14808. ast_string_field_set(p, exten, t);
  14809. t = strchr(p->exten, '@');
  14810. if (t)
  14811. *t = '\0';
  14812. if (ast_strlen_zero(p->our_contact))
  14813. build_contact(p);
  14814. }
  14815. of = get_in_brackets(of);
  14816. /* save the URI part of the From header */
  14817. ast_string_field_set(p, from, of);
  14818. if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
  14819. ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
  14820. }
  14821. SIP_PEDANTIC_DECODE(name);
  14822. SIP_PEDANTIC_DECODE(domain);
  14823. extract_host_from_hostport(&domain);
  14824. if (ast_strlen_zero(domain)) {
  14825. /* <sip:name@[EMPTY]>, never good */
  14826. ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
  14827. return res;
  14828. }
  14829. if (ast_strlen_zero(name)) {
  14830. /* <sip:[EMPTY][@]hostport>. Asterisk 1.4 and 1.6 have always
  14831. * treated that as a username, so we continue the tradition:
  14832. * uri is now <sip:host@hostport>. */
  14833. name = domain;
  14834. } else {
  14835. /* Non-empty name, try to get caller id from it */
  14836. char *tmp = ast_strdupa(name);
  14837. /* We need to be able to handle from-headers looking like
  14838. <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
  14839. */
  14840. tmp = strsep(&tmp, ";");
  14841. if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
  14842. ast_shrink_phone_number(tmp);
  14843. }
  14844. ast_string_field_set(p, cid_num, tmp);
  14845. }
  14846. if (global_match_auth_username) {
  14847. /*
  14848. * XXX This is experimental code to grab the search key from the
  14849. * Auth header's username instead of the 'From' name, if available.
  14850. * Do not enable this block unless you understand the side effects (if any!)
  14851. * Note, the search for "username" should be done in a more robust way.
  14852. * Note2, at the moment we check both fields, though maybe we should
  14853. * pick one or another depending on the request ? XXX
  14854. */
  14855. const char *hdr = get_header(req, "Authorization");
  14856. if (ast_strlen_zero(hdr)) {
  14857. hdr = get_header(req, "Proxy-Authorization");
  14858. }
  14859. if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
  14860. namebuf = name = ast_strdup(hdr + strlen("username=\""));
  14861. name = strsep(&name, "\"");
  14862. }
  14863. }
  14864. res = check_peer_ok(p, name, req, sipmethod, addr,
  14865. authpeer, reliable, calleridname, uri2);
  14866. if (res != AUTH_DONT_KNOW) {
  14867. return res;
  14868. }
  14869. /* Finally, apply the guest policy */
  14870. if (sip_cfg.allowguest) {
  14871. /* Ignore check_return warning from Coverity for get_rpid below. */
  14872. get_rpid(p, req);
  14873. p->rtptimeout = global_rtptimeout;
  14874. p->rtpholdtimeout = global_rtpholdtimeout;
  14875. p->rtpkeepalive = global_rtpkeepalive;
  14876. if (!dialog_initialize_rtp(p)) {
  14877. res = AUTH_SUCCESSFUL;
  14878. } else {
  14879. res = AUTH_RTP_FAILED;
  14880. }
  14881. } else {
  14882. res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
  14883. }
  14884. if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
  14885. ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
  14886. }
  14887. return res;
  14888. }
  14889. /*! \brief Find user
  14890. If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
  14891. */
  14892. static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
  14893. {
  14894. return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
  14895. }
  14896. /*! \brief Get message body from a SIP request
  14897. * \param buf Destination buffer
  14898. * \param len Destination buffer size
  14899. * \param req The SIP request
  14900. *
  14901. * When parsing the request originally, the lines are split by LF or CRLF.
  14902. * This function adds a single LF after every line.
  14903. */
  14904. static int get_msg_text(char *buf, int len, struct sip_request *req)
  14905. {
  14906. int x;
  14907. int linelen;
  14908. buf[0] = '\0';
  14909. --len; /* reserve strncat null */
  14910. for (x = 0; len && x < req->lines; ++x) {
  14911. const char *line = REQ_OFFSET_TO_STR(req, line[x]);
  14912. strncat(buf, line, len); /* safe */
  14913. linelen = strlen(buf);
  14914. buf += linelen;
  14915. len -= linelen;
  14916. if (len) {
  14917. strcat(buf, "\n"); /* safe */
  14918. ++buf;
  14919. --len;
  14920. }
  14921. }
  14922. return 0;
  14923. }
  14924. /*! \brief Receive SIP MESSAGE method messages
  14925. \note We only handle messages within current calls currently
  14926. Reference: RFC 3428 */
  14927. static void receive_message(struct sip_pvt *p, struct sip_request *req)
  14928. {
  14929. char buf[1400];
  14930. char *bufp;
  14931. struct ast_frame f;
  14932. const char *content_type = get_header(req, "Content-Type");
  14933. if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
  14934. transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
  14935. if (!p->owner)
  14936. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14937. return;
  14938. }
  14939. if (get_msg_text(buf, sizeof(buf), req)) {
  14940. ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
  14941. transmit_response(p, "500 Internal Server Error", req);
  14942. if (!p->owner) {
  14943. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14944. }
  14945. return;
  14946. }
  14947. /* Strip trailing line feeds from message body. (get_msg_text may add
  14948. * a trailing linefeed and we don't need any at the end) */
  14949. bufp = buf + strlen(buf);
  14950. while (--bufp >= buf && *bufp == '\n') {
  14951. *bufp = '\0';
  14952. }
  14953. if (p->owner) {
  14954. if (sip_debug_test_pvt(p))
  14955. ast_verbose("SIP Text message received: '%s'\n", buf);
  14956. memset(&f, 0, sizeof(f));
  14957. f.frametype = AST_FRAME_TEXT;
  14958. f.subclass.integer = 0;
  14959. f.offset = 0;
  14960. f.data.ptr = buf;
  14961. f.datalen = strlen(buf) + 1;
  14962. ast_queue_frame(p->owner, &f);
  14963. transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
  14964. return;
  14965. }
  14966. /* Message outside of a call, we do not support that */
  14967. ast_log(LOG_WARNING, "Received message to %s from %s, dropped it...\n Content-Type:%s\n Message: %s\n", get_header(req, "To"), get_header(req, "From"), content_type, buf);
  14968. transmit_response(p, "405 Method Not Allowed", req);
  14969. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  14970. return;
  14971. }
  14972. /*! \brief CLI Command to show calls within limits set by call_limit */
  14973. static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  14974. {
  14975. #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
  14976. #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
  14977. char ilimits[40];
  14978. char iused[40];
  14979. int showall = FALSE;
  14980. struct ao2_iterator i;
  14981. struct sip_peer *peer;
  14982. switch (cmd) {
  14983. case CLI_INIT:
  14984. e->command = "sip show inuse";
  14985. e->usage =
  14986. "Usage: sip show inuse [all]\n"
  14987. " List all SIP devices usage counters and limits.\n"
  14988. " Add option \"all\" to show all devices, not only those with a limit.\n";
  14989. return NULL;
  14990. case CLI_GENERATE:
  14991. return NULL;
  14992. }
  14993. if (a->argc < 3)
  14994. return CLI_SHOWUSAGE;
  14995. if (a->argc == 4 && !strcmp(a->argv[3], "all"))
  14996. showall = TRUE;
  14997. ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
  14998. i = ao2_iterator_init(peers, 0);
  14999. while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
  15000. ao2_lock(peer);
  15001. if (peer->call_limit)
  15002. snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
  15003. else
  15004. ast_copy_string(ilimits, "N/A", sizeof(ilimits));
  15005. snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
  15006. if (showall || peer->call_limit)
  15007. ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
  15008. ao2_unlock(peer);
  15009. unref_peer(peer, "toss iterator pointer");
  15010. }
  15011. ao2_iterator_destroy(&i);
  15012. return CLI_SUCCESS;
  15013. #undef FORMAT
  15014. #undef FORMAT2
  15015. }
  15016. /*! \brief Convert transfer mode to text string */
  15017. static char *transfermode2str(enum transfermodes mode)
  15018. {
  15019. if (mode == TRANSFER_OPENFORALL)
  15020. return "open";
  15021. else if (mode == TRANSFER_CLOSED)
  15022. return "closed";
  15023. return "strict";
  15024. }
  15025. /*! \brief Report Peer status in character string
  15026. * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
  15027. */
  15028. /* Session-Timer Modes */
  15029. static const struct _map_x_s stmodes[] = {
  15030. { SESSION_TIMER_MODE_ACCEPT, "Accept"},
  15031. { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
  15032. { SESSION_TIMER_MODE_REFUSE, "Refuse"},
  15033. { -1, NULL},
  15034. };
  15035. static const char *stmode2str(enum st_mode m)
  15036. {
  15037. return map_x_s(stmodes, m, "Unknown");
  15038. }
  15039. static enum st_mode str2stmode(const char *s)
  15040. {
  15041. return map_s_x(stmodes, s, -1);
  15042. }
  15043. /* Session-Timer Refreshers */
  15044. static const struct _map_x_s strefresher_params[] = {
  15045. { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
  15046. { SESSION_TIMER_REFRESHER_PARAM_UAC, "uac" },
  15047. { SESSION_TIMER_REFRESHER_PARAM_UAS, "uas" },
  15048. { -1, NULL },
  15049. };
  15050. static const struct _map_x_s strefreshers[] = {
  15051. { SESSION_TIMER_REFRESHER_AUTO, "auto" },
  15052. { SESSION_TIMER_REFRESHER_US, "us" },
  15053. { SESSION_TIMER_REFRESHER_THEM, "them" },
  15054. { -1, NULL },
  15055. };
  15056. static const char *strefresherparam2str(enum st_refresher r)
  15057. {
  15058. return map_x_s(strefresher_params, r, "Unknown");
  15059. }
  15060. static enum st_refresher str2strefresherparam(const char *s)
  15061. {
  15062. return map_s_x(strefresher_params, s, -1);
  15063. }
  15064. static const char *strefresher2str(enum st_refresher r)
  15065. {
  15066. return map_x_s(strefreshers, r, "Unknown");
  15067. }
  15068. static int peer_status(struct sip_peer *peer, char *status, int statuslen)
  15069. {
  15070. int res = 0;
  15071. if (peer->maxms) {
  15072. if (peer->lastms < 0) {
  15073. ast_copy_string(status, "UNREACHABLE", statuslen);
  15074. } else if (peer->lastms > peer->maxms) {
  15075. snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
  15076. res = 1;
  15077. } else if (peer->lastms) {
  15078. snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
  15079. res = 1;
  15080. } else {
  15081. ast_copy_string(status, "UNKNOWN", statuslen);
  15082. }
  15083. } else {
  15084. ast_copy_string(status, "Unmonitored", statuslen);
  15085. /* Checking if port is 0 */
  15086. res = -1;
  15087. }
  15088. return res;
  15089. }
  15090. /*! \brief Show active TCP connections */
  15091. static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  15092. {
  15093. struct sip_threadinfo *th;
  15094. struct ao2_iterator i;
  15095. #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
  15096. #define FORMAT "%-47.47s %-9.9s %-6.6s\n"
  15097. switch (cmd) {
  15098. case CLI_INIT:
  15099. e->command = "sip show tcp";
  15100. e->usage =
  15101. "Usage: sip show tcp\n"
  15102. " Lists all active TCP/TLS sessions.\n";
  15103. return NULL;
  15104. case CLI_GENERATE:
  15105. return NULL;
  15106. }
  15107. if (a->argc != 3)
  15108. return CLI_SHOWUSAGE;
  15109. ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
  15110. i = ao2_iterator_init(threadt, 0);
  15111. while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
  15112. ast_cli(a->fd, FORMAT,
  15113. ast_sockaddr_stringify(&th->tcptls_session->remote_address),
  15114. get_transport(th->type),
  15115. (th->tcptls_session->client ? "Client" : "Server"));
  15116. ao2_t_ref(th, -1, "decrement ref from iterator");
  15117. }
  15118. ao2_iterator_destroy(&i);
  15119. return CLI_SUCCESS;
  15120. #undef FORMAT
  15121. #undef FORMAT2
  15122. }
  15123. /*! \brief CLI Command 'SIP Show Users' */
  15124. static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  15125. {
  15126. regex_t regexbuf;
  15127. int havepattern = FALSE;
  15128. struct ao2_iterator user_iter;
  15129. struct sip_peer *user;
  15130. #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
  15131. switch (cmd) {
  15132. case CLI_INIT:
  15133. e->command = "sip show users";
  15134. e->usage =
  15135. "Usage: sip show users [like <pattern>]\n"
  15136. " Lists all known SIP users.\n"
  15137. " Optional regular expression pattern is used to filter the user list.\n";
  15138. return NULL;
  15139. case CLI_GENERATE:
  15140. return NULL;
  15141. }
  15142. switch (a->argc) {
  15143. case 5:
  15144. if (!strcasecmp(a->argv[3], "like")) {
  15145. if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
  15146. return CLI_SHOWUSAGE;
  15147. havepattern = TRUE;
  15148. } else
  15149. return CLI_SHOWUSAGE;
  15150. case 3:
  15151. break;
  15152. default:
  15153. return CLI_SHOWUSAGE;
  15154. }
  15155. ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "Forcerport");
  15156. user_iter = ao2_iterator_init(peers, 0);
  15157. while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
  15158. ao2_lock(user);
  15159. if (!(user->type & SIP_TYPE_USER)) {
  15160. ao2_unlock(user);
  15161. unref_peer(user, "sip show users");
  15162. continue;
  15163. }
  15164. if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
  15165. ao2_unlock(user);
  15166. unref_peer(user, "sip show users");
  15167. continue;
  15168. }
  15169. ast_cli(a->fd, FORMAT, user->name,
  15170. user->secret,
  15171. user->accountcode,
  15172. user->context,
  15173. AST_CLI_YESNO(user->ha != NULL),
  15174. AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
  15175. ao2_unlock(user);
  15176. unref_peer(user, "sip show users");
  15177. }
  15178. ao2_iterator_destroy(&user_iter);
  15179. if (havepattern)
  15180. regfree(&regexbuf);
  15181. return CLI_SUCCESS;
  15182. #undef FORMAT
  15183. }
  15184. /*! \brief Show SIP registrations in the manager API */
  15185. static int manager_show_registry(struct mansession *s, const struct message *m)
  15186. {
  15187. const char *id = astman_get_header(m, "ActionID");
  15188. char idtext[256] = "";
  15189. int total = 0;
  15190. if (!ast_strlen_zero(id))
  15191. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  15192. astman_send_listack(s, m, "Registrations will follow", "start");
  15193. ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
  15194. ASTOBJ_RDLOCK(iterator);
  15195. astman_append(s,
  15196. "Event: RegistryEntry\r\n"
  15197. "%s"
  15198. "Host: %s\r\n"
  15199. "Port: %d\r\n"
  15200. "Username: %s\r\n"
  15201. "Domain: %s\r\n"
  15202. "DomainPort: %d\r\n"
  15203. "Refresh: %d\r\n"
  15204. "State: %s\r\n"
  15205. "RegistrationTime: %ld\r\n"
  15206. "\r\n",
  15207. idtext,
  15208. iterator->hostname,
  15209. iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
  15210. iterator->username,
  15211. S_OR(iterator->regdomain,iterator->hostname),
  15212. iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
  15213. iterator->refresh,
  15214. regstate2str(iterator->regstate),
  15215. (long) iterator->regtime.tv_sec);
  15216. ASTOBJ_UNLOCK(iterator);
  15217. total++;
  15218. } while(0));
  15219. astman_append(s,
  15220. "Event: RegistrationsComplete\r\n"
  15221. "EventList: Complete\r\n"
  15222. "ListItems: %d\r\n"
  15223. "%s"
  15224. "\r\n", total, idtext);
  15225. return 0;
  15226. }
  15227. /*! \brief Show SIP peers in the manager API */
  15228. /* Inspired from chan_iax2 */
  15229. static int manager_sip_show_peers(struct mansession *s, const struct message *m)
  15230. {
  15231. const char *id = astman_get_header(m, "ActionID");
  15232. const char *a[] = {"sip", "show", "peers"};
  15233. char idtext[256] = "";
  15234. int total = 0;
  15235. if (!ast_strlen_zero(id))
  15236. snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
  15237. astman_send_listack(s, m, "Peer status list will follow", "start");
  15238. /* List the peers in separate manager events */
  15239. _sip_show_peers(-1, &total, s, m, 3, a);
  15240. /* Send final confirmation */
  15241. astman_append(s,
  15242. "Event: PeerlistComplete\r\n"
  15243. "EventList: Complete\r\n"
  15244. "ListItems: %d\r\n"
  15245. "%s"
  15246. "\r\n", total, idtext);
  15247. return 0;
  15248. }
  15249. /*! \brief CLI Show Peers command */
  15250. static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  15251. {
  15252. switch (cmd) {
  15253. case CLI_INIT:
  15254. e->command = "sip show peers";
  15255. e->usage =
  15256. "Usage: sip show peers [like <pattern>]\n"
  15257. " Lists all known SIP peers.\n"
  15258. " Optional regular expression pattern is used to filter the peer list.\n";
  15259. return NULL;
  15260. case CLI_GENERATE:
  15261. return NULL;
  15262. }
  15263. return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
  15264. }
  15265. int peercomparefunc(const void *a, const void *b);
  15266. int peercomparefunc(const void *a, const void *b)
  15267. {
  15268. struct sip_peer **ap = (struct sip_peer **)a;
  15269. struct sip_peer **bp = (struct sip_peer **)b;
  15270. return strcmp((*ap)->name, (*bp)->name);
  15271. }
  15272. /* the last argument is left-aligned, so we don't need a size anyways */
  15273. #define PEERS_FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-10s %s\n"
  15274. /*! \brief Used in the sip_show_peers functions to pass parameters */
  15275. struct show_peers_context {
  15276. regex_t regexbuf;
  15277. int havepattern;
  15278. char idtext[256];
  15279. int realtimepeers;
  15280. int peers_mon_online;
  15281. int peers_mon_offline;
  15282. int peers_unmon_offline;
  15283. int peers_unmon_online;
  15284. };
  15285. /*! \brief Execute sip show peers command */
  15286. static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
  15287. {
  15288. struct show_peers_context cont = {
  15289. .havepattern = FALSE,
  15290. .idtext = "",
  15291. .peers_mon_online = 0,
  15292. .peers_mon_offline = 0,
  15293. .peers_unmon_online = 0,
  15294. .peers_unmon_offline = 0,
  15295. };
  15296. struct sip_peer *peer;
  15297. struct ao2_iterator* it_peers;
  15298. int total_peers = 0;
  15299. const char *id;
  15300. struct sip_peer **peerarray;
  15301. int k;
  15302. cont.realtimepeers = ast_check_realtime("sippeers");
  15303. if (s) { /* Manager - get ActionID */
  15304. id = astman_get_header(m, "ActionID");
  15305. if (!ast_strlen_zero(id)) {
  15306. snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
  15307. }
  15308. }
  15309. switch (argc) {
  15310. case 5:
  15311. if (!strcasecmp(argv[3], "like")) {
  15312. if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
  15313. return CLI_SHOWUSAGE;
  15314. cont.havepattern = TRUE;
  15315. } else
  15316. return CLI_SHOWUSAGE;
  15317. case 3:
  15318. break;
  15319. default:
  15320. return CLI_SHOWUSAGE;
  15321. }
  15322. if (!s) {
  15323. /* Normal list */
  15324. ast_cli(fd, PEERS_FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", (cont.realtimepeers ? "Realtime" : ""));
  15325. }
  15326. ao2_lock(peers);
  15327. if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
  15328. ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
  15329. ao2_unlock(peers);
  15330. return CLI_FAILURE;
  15331. }
  15332. if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
  15333. ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
  15334. ao2_iterator_destroy(it_peers);
  15335. ao2_unlock(peers);
  15336. return CLI_FAILURE;
  15337. }
  15338. ao2_unlock(peers);
  15339. while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
  15340. ao2_lock(peer);
  15341. if (!(peer->type & SIP_TYPE_PEER)) {
  15342. ao2_unlock(peer);
  15343. unref_peer(peer, "unref peer because it's actually a user");
  15344. continue;
  15345. }
  15346. if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
  15347. ao2_unlock(peer);
  15348. unref_peer(peer, "toss iterator peer ptr before continue");
  15349. continue;
  15350. }
  15351. peerarray[total_peers++] = peer;
  15352. ao2_unlock(peer);
  15353. }
  15354. ao2_iterator_destroy(it_peers);
  15355. qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
  15356. for(k = 0; k < total_peers; k++) {
  15357. peerarray[k] = _sip_show_peers_one(fd, s, &cont, peerarray[k]);
  15358. }
  15359. if (!s) {
  15360. ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
  15361. total_peers, cont.peers_mon_online, cont.peers_mon_offline, cont.peers_unmon_online, cont.peers_unmon_offline);
  15362. }
  15363. if (cont.havepattern) {
  15364. regfree(&cont.regexbuf);
  15365. }
  15366. if (total) {
  15367. *total = total_peers;
  15368. }
  15369. ast_free(peerarray);
  15370. return CLI_SUCCESS;
  15371. }
  15372. /*! \brief Emit informations for one peer during sip show peers command */
  15373. static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer)
  15374. {
  15375. /* _sip_show_peers_one() is separated from _sip_show_peers() to properly free the ast_strdupa
  15376. * (this is executed in a loop in _sip_show_peers() )
  15377. */
  15378. char name[256];
  15379. char status[20] = "";
  15380. char pstatus;
  15381. /*
  15382. * tmp_port and tmp_host store copies of ast_sockaddr_stringify strings since the
  15383. * string pointers for that function aren't valid between subsequent calls to
  15384. * ast_sockaddr_stringify functions
  15385. */
  15386. char *tmp_port;
  15387. char *tmp_host;
  15388. tmp_port = ast_sockaddr_isnull(&peer->addr) ?
  15389. "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
  15390. tmp_host = ast_sockaddr_isnull(&peer->addr) ?
  15391. "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
  15392. ao2_lock(peer);
  15393. if (cont->havepattern && regexec(&cont->regexbuf, peer->name, 0, NULL, 0)) {
  15394. ao2_unlock(peer);
  15395. return unref_peer(peer, "toss iterator peer ptr no match");
  15396. }
  15397. if (!ast_strlen_zero(peer->username) && !s) {
  15398. snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
  15399. } else {
  15400. ast_copy_string(name, peer->name, sizeof(name));
  15401. }
  15402. pstatus = peer_status(peer, status, sizeof(status));
  15403. if (pstatus == 1) {
  15404. cont->peers_mon_online++;
  15405. } else if (pstatus == 0) {
  15406. cont->peers_mon_offline++;
  15407. } else {
  15408. if (ast_sockaddr_isnull(&peer->addr) ||
  15409. !ast_sockaddr_port(&peer->addr)) {
  15410. cont->peers_unmon_offline++;
  15411. } else {
  15412. cont->peers_unmon_online++;
  15413. }
  15414. }
  15415. if (!s) { /* Normal CLI list */
  15416. ast_cli(fd, PEERS_FORMAT2, name,
  15417. tmp_host,
  15418. peer->host_dynamic ? " D " : " ", /* Dynamic or not? */
  15419. ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : " ", /* NAT=yes? */
  15420. peer->ha ? " A " : " ", /* permit/deny */
  15421. tmp_port, status,
  15422. cont->realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
  15423. } else { /* Manager format */
  15424. /* The names here need to be the same as other channels */
  15425. astman_append(s,
  15426. "Event: PeerEntry\r\n%s"
  15427. "Channeltype: SIP\r\n"
  15428. "ObjectName: %s\r\n"
  15429. "ChanObjectType: peer\r\n" /* "peer" or "user" */
  15430. "IPaddress: %s\r\n"
  15431. "IPport: %s\r\n"
  15432. "Dynamic: %s\r\n"
  15433. "Forcerport: %s\r\n"
  15434. "VideoSupport: %s\r\n"
  15435. "TextSupport: %s\r\n"
  15436. "ACL: %s\r\n"
  15437. "Status: %s\r\n"
  15438. "RealtimeDevice: %s\r\n\r\n",
  15439. cont->idtext,
  15440. peer->name,
  15441. ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
  15442. ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
  15443. peer->host_dynamic ? "yes" : "no", /* Dynamic or not? */
  15444. ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no", /* NAT=yes? */
  15445. ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
  15446. ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no", /* TEXTSUPPORT=yes? */
  15447. peer->ha ? "yes" : "no", /* permit/deny */
  15448. status,
  15449. cont->realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
  15450. }
  15451. ao2_unlock(peer);
  15452. return unref_peer(peer, "toss iterator peer ptr");
  15453. }
  15454. #undef PEERS_FORMAT2
  15455. static int peer_dump_func(void *userobj, void *arg, int flags)
  15456. {
  15457. struct sip_peer *peer = userobj;
  15458. int refc = ao2_t_ref(userobj, 0, "");
  15459. struct ast_cli_args *a = (struct ast_cli_args *) arg;
  15460. ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
  15461. peer->name, 0, refc);
  15462. return 0;
  15463. }
  15464. static int dialog_dump_func(void *userobj, void *arg, int flags)
  15465. {
  15466. struct sip_pvt *pvt = userobj;
  15467. int refc = ao2_t_ref(userobj, 0, "");
  15468. struct ast_cli_args *a = (struct ast_cli_args *) arg;
  15469. ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
  15470. pvt->callid, 0, refc);
  15471. return 0;
  15472. }
  15473. /*! \brief List all allocated SIP Objects (realtime or static) */
  15474. static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  15475. {
  15476. char tmp[256];
  15477. switch (cmd) {
  15478. case CLI_INIT:
  15479. e->command = "sip show objects";
  15480. e->usage =
  15481. "Usage: sip show objects\n"
  15482. " Lists status of known SIP objects\n";
  15483. return NULL;
  15484. case CLI_GENERATE:
  15485. return NULL;
  15486. }
  15487. if (a->argc != 3)
  15488. return CLI_SHOWUSAGE;
  15489. ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
  15490. ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
  15491. ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
  15492. ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
  15493. ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
  15494. ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
  15495. ast_cli(a->fd, "-= Dialog objects:\n\n");
  15496. ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
  15497. return CLI_SUCCESS;
  15498. }
  15499. /*! \brief Print call group and pickup group */
  15500. static void print_group(int fd, ast_group_t group, int crlf)
  15501. {
  15502. char buf[256];
  15503. ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
  15504. }
  15505. /*! \brief mapping between dtmf flags and strings */
  15506. static const struct _map_x_s dtmfstr[] = {
  15507. { SIP_DTMF_RFC2833, "rfc2833" },
  15508. { SIP_DTMF_INFO, "info" },
  15509. { SIP_DTMF_SHORTINFO, "shortinfo" },
  15510. { SIP_DTMF_INBAND, "inband" },
  15511. { SIP_DTMF_AUTO, "auto" },
  15512. { -1, NULL }, /* terminator */
  15513. };
  15514. /*! \brief Convert DTMF mode to printable string */
  15515. static const char *dtmfmode2str(int mode)
  15516. {
  15517. return map_x_s(dtmfstr, mode, "<error>");
  15518. }
  15519. /*! \brief maps a string to dtmfmode, returns -1 on error */
  15520. static int str2dtmfmode(const char *str)
  15521. {
  15522. return map_s_x(dtmfstr, str, -1);
  15523. }
  15524. static const struct _map_x_s insecurestr[] = {
  15525. { SIP_INSECURE_PORT, "port" },
  15526. { SIP_INSECURE_INVITE, "invite" },
  15527. { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
  15528. { 0, "no" },
  15529. { -1, NULL }, /* terminator */
  15530. };
  15531. /*! \brief Convert Insecure setting to printable string */
  15532. static const char *insecure2str(int mode)
  15533. {
  15534. return map_x_s(insecurestr, mode, "<error>");
  15535. }
  15536. static const struct _map_x_s allowoverlapstr[] = {
  15537. { SIP_PAGE2_ALLOWOVERLAP_YES, "Yes" },
  15538. { SIP_PAGE2_ALLOWOVERLAP_DTMF, "DTMF" },
  15539. { SIP_PAGE2_ALLOWOVERLAP_NO, "No" },
  15540. { -1, NULL }, /* terminator */
  15541. };
  15542. /*! \brief Convert AllowOverlap setting to printable string */
  15543. static const char *allowoverlap2str(int mode)
  15544. {
  15545. return map_x_s(allowoverlapstr, mode, "<error>");
  15546. }
  15547. static const struct _map_x_s trust_id_outboundstr[] = {
  15548. { SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY, "Legacy" },
  15549. { SIP_PAGE2_TRUST_ID_OUTBOUND_NO, "No" },
  15550. { SIP_PAGE2_TRUST_ID_OUTBOUND_YES, "Yes" },
  15551. { -1, NULL }, /* terminator */
  15552. };
  15553. static const char *trust_id_outbound2str(int mode)
  15554. {
  15555. return map_x_s(trust_id_outboundstr, mode, "<error>");
  15556. }
  15557. /*! \brief Destroy disused contexts between reloads
  15558. Only used in reload_config so the code for regcontext doesn't get ugly
  15559. */
  15560. static void cleanup_stale_contexts(char *new, char *old)
  15561. {
  15562. char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
  15563. while ((oldcontext = strsep(&old, "&"))) {
  15564. stalecontext = '\0';
  15565. ast_copy_string(newlist, new, sizeof(newlist));
  15566. stringp = newlist;
  15567. while ((newcontext = strsep(&stringp, "&"))) {
  15568. if (!strcmp(newcontext, oldcontext)) {
  15569. /* This is not the context you're looking for */
  15570. stalecontext = '\0';
  15571. break;
  15572. } else if (strcmp(newcontext, oldcontext)) {
  15573. stalecontext = oldcontext;
  15574. }
  15575. }
  15576. if (stalecontext)
  15577. ast_context_destroy(ast_context_find(stalecontext), "SIP");
  15578. }
  15579. }
  15580. /*!
  15581. * \brief Match dialogs that need to be destroyed
  15582. *
  15583. * \details This is used with ao2_callback to unlink/delete all dialogs that
  15584. * are marked needdestroy.
  15585. *
  15586. * \todo Re-work this to improve efficiency. Currently, this function is called
  15587. * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
  15588. * potentially even more often when the scheduler has entries to run.
  15589. */
  15590. static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
  15591. {
  15592. struct sip_pvt *dialog = dialogobj;
  15593. time_t *t = arg;
  15594. if (sip_pvt_trylock(dialog)) {
  15595. /* Don't block the monitor thread. This function is called often enough
  15596. * that we can wait for the next time around. */
  15597. return 0;
  15598. }
  15599. /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
  15600. check_rtp_timeout(dialog, *t);
  15601. /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
  15602. if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
  15603. ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
  15604. sip_pvt_unlock(dialog);
  15605. return 0;
  15606. }
  15607. if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
  15608. ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
  15609. sip_pvt_unlock(dialog);
  15610. return 0;
  15611. }
  15612. /* If we have sessions that needs to be destroyed, do it now */
  15613. /* Check if we have outstanding requests not responsed to or an active call
  15614. - if that's the case, wait with destruction */
  15615. if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
  15616. /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
  15617. if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
  15618. ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
  15619. sip_pvt_unlock(dialog);
  15620. return 0;
  15621. }
  15622. if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
  15623. ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
  15624. sip_pvt_unlock(dialog);
  15625. return 0;
  15626. }
  15627. sip_pvt_unlock(dialog);
  15628. /* This dialog needs to be destroyed. */
  15629. ao2_t_link(dialogs_to_destroy, dialog, "Link dialog for destruction");
  15630. return 0;
  15631. }
  15632. sip_pvt_unlock(dialog);
  15633. return 0;
  15634. }
  15635. /*!
  15636. * \internal
  15637. * \brief ao2_callback to unlink the specified dialog object.
  15638. *
  15639. * \param obj Ptr to dialog to unlink.
  15640. * \param arg Don't care.
  15641. * \param flags Don't care.
  15642. *
  15643. * \retval CMP_MATCH
  15644. */
  15645. static int dialog_unlink_callback(void *obj, void *arg, int flags)
  15646. {
  15647. struct sip_pvt *dialog = obj;
  15648. dialog_unlink_all(dialog);
  15649. return CMP_MATCH;
  15650. }
  15651. /*! \brief Remove temporary realtime objects from memory (CLI) */
  15652. /*! \todo XXXX Propably needs an overhaul after removal of the devices */
  15653. static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  15654. {
  15655. struct sip_peer *peer, *pi;
  15656. int prunepeer = FALSE;
  15657. int multi = FALSE;
  15658. const char *name = NULL;
  15659. regex_t regexbuf;
  15660. int havepattern = 0;
  15661. struct ao2_iterator i;
  15662. static const char * const choices[] = { "all", "like", NULL };
  15663. char *cmplt;
  15664. if (cmd == CLI_INIT) {
  15665. e->command = "sip prune realtime [peer|all]";
  15666. e->usage =
  15667. "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
  15668. " Prunes object(s) from the cache.\n"
  15669. " Optional regular expression pattern is used to filter the objects.\n";
  15670. return NULL;
  15671. } else if (cmd == CLI_GENERATE) {
  15672. if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
  15673. cmplt = ast_cli_complete(a->word, choices, a->n);
  15674. if (!cmplt)
  15675. cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
  15676. return cmplt;
  15677. }
  15678. if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
  15679. return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
  15680. return NULL;
  15681. }
  15682. switch (a->argc) {
  15683. case 4:
  15684. name = a->argv[3];
  15685. /* we accept a name in position 3, but keywords are not good. */
  15686. if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
  15687. return CLI_SHOWUSAGE;
  15688. prunepeer = TRUE;
  15689. if (!strcasecmp(name, "all")) {
  15690. multi = TRUE;
  15691. name = NULL;
  15692. }
  15693. /* else a single name, already set */
  15694. break;
  15695. case 5:
  15696. /* sip prune realtime {peer|like} name */
  15697. name = a->argv[4];
  15698. if (!strcasecmp(a->argv[3], "peer"))
  15699. prunepeer = TRUE;
  15700. else if (!strcasecmp(a->argv[3], "like")) {
  15701. prunepeer = TRUE;
  15702. multi = TRUE;
  15703. } else
  15704. return CLI_SHOWUSAGE;
  15705. if (!strcasecmp(name, "like"))
  15706. return CLI_SHOWUSAGE;
  15707. if (!multi && !strcasecmp(name, "all")) {
  15708. multi = TRUE;
  15709. name = NULL;
  15710. }
  15711. break;
  15712. case 6:
  15713. name = a->argv[5];
  15714. multi = TRUE;
  15715. /* sip prune realtime {peer} like name */
  15716. if (strcasecmp(a->argv[4], "like"))
  15717. return CLI_SHOWUSAGE;
  15718. if (!strcasecmp(a->argv[3], "peer")) {
  15719. prunepeer = TRUE;
  15720. } else
  15721. return CLI_SHOWUSAGE;
  15722. break;
  15723. default:
  15724. return CLI_SHOWUSAGE;
  15725. }
  15726. if (multi && name) {
  15727. if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
  15728. return CLI_SHOWUSAGE;
  15729. }
  15730. havepattern = 1;
  15731. }
  15732. if (multi) {
  15733. if (prunepeer) {
  15734. int pruned = 0;
  15735. i = ao2_iterator_init(peers, 0);
  15736. while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  15737. ao2_lock(pi);
  15738. if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
  15739. ao2_unlock(pi);
  15740. unref_peer(pi, "toss iterator peer ptr before continue");
  15741. continue;
  15742. };
  15743. if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  15744. pi->the_mark = 1;
  15745. pruned++;
  15746. }
  15747. ao2_unlock(pi);
  15748. unref_peer(pi, "toss iterator peer ptr");
  15749. }
  15750. ao2_iterator_destroy(&i);
  15751. if (pruned) {
  15752. unlink_marked_peers_from_tables();
  15753. ast_cli(a->fd, "%d peers pruned.\n", pruned);
  15754. } else
  15755. ast_cli(a->fd, "No peers found to prune.\n");
  15756. }
  15757. } else {
  15758. if (prunepeer) {
  15759. struct sip_peer tmp;
  15760. ast_copy_string(tmp.name, name, sizeof(tmp.name));
  15761. if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
  15762. if (!ast_sockaddr_isnull(&peer->addr)) {
  15763. ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
  15764. }
  15765. if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  15766. ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
  15767. /* put it back! */
  15768. ao2_t_link(peers, peer, "link peer into peer table");
  15769. if (!ast_sockaddr_isnull(&peer->addr)) {
  15770. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  15771. }
  15772. } else
  15773. ast_cli(a->fd, "Peer '%s' pruned.\n", name);
  15774. unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
  15775. } else
  15776. ast_cli(a->fd, "Peer '%s' not found.\n", name);
  15777. }
  15778. }
  15779. if (havepattern) {
  15780. regfree(&regexbuf);
  15781. }
  15782. return CLI_SUCCESS;
  15783. }
  15784. /*! \brief Print codec list from preference to CLI/manager */
  15785. static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
  15786. {
  15787. int x;
  15788. format_t codec;
  15789. for(x = 0; x < 64 ; x++) {
  15790. codec = ast_codec_pref_index(pref, x);
  15791. if (!codec)
  15792. break;
  15793. ast_cli(fd, "%s", ast_getformatname(codec));
  15794. ast_cli(fd, ":%d", pref->framing[x]);
  15795. if (x < 31 && ast_codec_pref_index(pref, x + 1))
  15796. ast_cli(fd, ",");
  15797. }
  15798. if (!x)
  15799. ast_cli(fd, "none");
  15800. }
  15801. /*! \brief Print domain mode to cli */
  15802. static const char *domain_mode_to_text(const enum domain_mode mode)
  15803. {
  15804. switch (mode) {
  15805. case SIP_DOMAIN_AUTO:
  15806. return "[Automatic]";
  15807. case SIP_DOMAIN_CONFIG:
  15808. return "[Configured]";
  15809. }
  15810. return "";
  15811. }
  15812. /*! \brief CLI command to list local domains */
  15813. static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  15814. {
  15815. struct domain *d;
  15816. #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
  15817. switch (cmd) {
  15818. case CLI_INIT:
  15819. e->command = "sip show domains";
  15820. e->usage =
  15821. "Usage: sip show domains\n"
  15822. " Lists all configured SIP local domains.\n"
  15823. " Asterisk only responds to SIP messages to local domains.\n";
  15824. return NULL;
  15825. case CLI_GENERATE:
  15826. return NULL;
  15827. }
  15828. if (AST_LIST_EMPTY(&domain_list)) {
  15829. ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
  15830. return CLI_SUCCESS;
  15831. } else {
  15832. ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
  15833. AST_LIST_LOCK(&domain_list);
  15834. AST_LIST_TRAVERSE(&domain_list, d, list)
  15835. ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
  15836. domain_mode_to_text(d->mode));
  15837. AST_LIST_UNLOCK(&domain_list);
  15838. ast_cli(a->fd, "\n");
  15839. return CLI_SUCCESS;
  15840. }
  15841. }
  15842. #undef FORMAT
  15843. /*! \brief Show SIP peers in the manager API */
  15844. static int manager_sip_show_peer(struct mansession *s, const struct message *m)
  15845. {
  15846. const char *a[4];
  15847. const char *peer;
  15848. peer = astman_get_header(m, "Peer");
  15849. if (ast_strlen_zero(peer)) {
  15850. astman_send_error(s, m, "Peer: <name> missing.");
  15851. return 0;
  15852. }
  15853. a[0] = "sip";
  15854. a[1] = "show";
  15855. a[2] = "peer";
  15856. a[3] = peer;
  15857. _sip_show_peer(1, -1, s, m, 4, a);
  15858. astman_append(s, "\r\n" );
  15859. return 0;
  15860. }
  15861. /*! \brief Show one peer in detail */
  15862. static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  15863. {
  15864. switch (cmd) {
  15865. case CLI_INIT:
  15866. e->command = "sip show peer";
  15867. e->usage =
  15868. "Usage: sip show peer <name> [load]\n"
  15869. " Shows all details on one SIP peer and the current status.\n"
  15870. " Option \"load\" forces lookup of peer in realtime storage.\n";
  15871. return NULL;
  15872. case CLI_GENERATE:
  15873. return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
  15874. }
  15875. return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
  15876. }
  15877. /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
  15878. static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
  15879. {
  15880. struct sip_peer *peer;
  15881. int load_realtime;
  15882. if (argc < 4)
  15883. return CLI_SHOWUSAGE;
  15884. load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
  15885. if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
  15886. sip_poke_peer(peer, 1);
  15887. unref_peer(peer, "qualify: done with peer");
  15888. } else if (type == 0) {
  15889. ast_cli(fd, "Peer '%s' not found\n", argv[3]);
  15890. } else {
  15891. astman_send_error(s, m, "Peer not found");
  15892. }
  15893. return CLI_SUCCESS;
  15894. }
  15895. /*! \brief Qualify SIP peers in the manager API */
  15896. static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
  15897. {
  15898. const char *a[4];
  15899. const char *peer;
  15900. peer = astman_get_header(m, "Peer");
  15901. if (ast_strlen_zero(peer)) {
  15902. astman_send_error(s, m, "Peer: <name> missing.");
  15903. return 0;
  15904. }
  15905. a[0] = "sip";
  15906. a[1] = "qualify";
  15907. a[2] = "peer";
  15908. a[3] = peer;
  15909. _sip_qualify_peer(1, -1, s, m, 4, a);
  15910. astman_append(s, "\r\n\r\n" );
  15911. return 0;
  15912. }
  15913. /*! \brief Send an OPTIONS packet to a SIP peer */
  15914. static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  15915. {
  15916. switch (cmd) {
  15917. case CLI_INIT:
  15918. e->command = "sip qualify peer";
  15919. e->usage =
  15920. "Usage: sip qualify peer <name> [load]\n"
  15921. " Requests a response from one SIP peer and the current status.\n"
  15922. " Option \"load\" forces lookup of peer in realtime storage.\n";
  15923. return NULL;
  15924. case CLI_GENERATE:
  15925. return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
  15926. }
  15927. return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
  15928. }
  15929. /*! \brief list peer mailboxes to CLI */
  15930. static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
  15931. {
  15932. struct sip_mailbox *mailbox;
  15933. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  15934. ast_str_append(mailbox_str, 0, "%s%s%s%s",
  15935. mailbox->mailbox,
  15936. ast_strlen_zero(mailbox->context) ? "" : "@",
  15937. S_OR(mailbox->context, ""),
  15938. AST_LIST_NEXT(mailbox, entry) ? "," : "");
  15939. }
  15940. }
  15941. static struct _map_x_s faxecmodes[] = {
  15942. { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
  15943. { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
  15944. { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
  15945. { -1, NULL},
  15946. };
  15947. static const char *faxec2str(int faxec)
  15948. {
  15949. return map_x_s(faxecmodes, faxec, "Unknown");
  15950. }
  15951. /*! \brief Show one peer in detail (main function) */
  15952. static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
  15953. {
  15954. char status[30] = "";
  15955. char cbuf[256];
  15956. struct sip_peer *peer;
  15957. char codec_buf[512];
  15958. struct ast_codec_pref *pref;
  15959. struct ast_variable *v;
  15960. int x = 0, load_realtime;
  15961. format_t codec = 0;
  15962. int realtimepeers;
  15963. realtimepeers = ast_check_realtime("sippeers");
  15964. if (argc < 4)
  15965. return CLI_SHOWUSAGE;
  15966. load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
  15967. peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
  15968. if (s) { /* Manager */
  15969. if (peer) {
  15970. const char *id = astman_get_header(m, "ActionID");
  15971. astman_append(s, "Response: Success\r\n");
  15972. if (!ast_strlen_zero(id))
  15973. astman_append(s, "ActionID: %s\r\n", id);
  15974. } else {
  15975. snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
  15976. astman_send_error(s, m, cbuf);
  15977. return CLI_SUCCESS;
  15978. }
  15979. }
  15980. if (peer && type==0 ) { /* Normal listing */
  15981. struct ast_str *mailbox_str = ast_str_alloca(512);
  15982. struct sip_auth_container *credentials;
  15983. ao2_lock(peer);
  15984. credentials = peer->auth;
  15985. if (credentials) {
  15986. ao2_t_ref(credentials, +1, "Ref peer auth for show");
  15987. }
  15988. ao2_unlock(peer);
  15989. ast_cli(fd, "\n\n");
  15990. ast_cli(fd, " * Name : %s\n", peer->name);
  15991. if (realtimepeers) { /* Realtime is enabled */
  15992. ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
  15993. }
  15994. ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
  15995. ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
  15996. ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
  15997. if (credentials) {
  15998. struct sip_auth *auth;
  15999. AST_LIST_TRAVERSE(&credentials->list, auth, node) {
  16000. ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s %s\n",
  16001. auth->realm,
  16002. auth->username,
  16003. !ast_strlen_zero(auth->secret)
  16004. ? "<Secret set>"
  16005. : (!ast_strlen_zero(auth->md5secret)
  16006. ? "<MD5secret set>" : "<Not set>"));
  16007. }
  16008. ao2_t_ref(credentials, -1, "Unref peer auth for show");
  16009. }
  16010. ast_cli(fd, " Context : %s\n", peer->context);
  16011. ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
  16012. ast_cli(fd, " Language : %s\n", peer->language);
  16013. if (!ast_strlen_zero(peer->accountcode))
  16014. ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
  16015. ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
  16016. ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
  16017. ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
  16018. if (!ast_strlen_zero(peer->fromuser))
  16019. ast_cli(fd, " FromUser : %s\n", peer->fromuser);
  16020. if (!ast_strlen_zero(peer->fromdomain))
  16021. ast_cli(fd, " FromDomain : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
  16022. ast_cli(fd, " Callgroup : ");
  16023. print_group(fd, peer->callgroup, 0);
  16024. ast_cli(fd, " Pickupgroup : ");
  16025. print_group(fd, peer->pickupgroup, 0);
  16026. peer_mailboxes_to_str(&mailbox_str, peer);
  16027. ast_cli(fd, " MOH Suggest : %s\n", peer->mohsuggest);
  16028. ast_cli(fd, " Mailbox : %s\n", ast_str_buffer(mailbox_str));
  16029. ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
  16030. ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
  16031. ast_cli(fd, " Call limit : %d\n", peer->call_limit);
  16032. ast_cli(fd, " Max forwards : %d\n", peer->maxforwards);
  16033. if (peer->busy_level)
  16034. ast_cli(fd, " Busy level : %d\n", peer->busy_level);
  16035. ast_cli(fd, " Dynamic : %s\n", AST_CLI_YESNO(peer->host_dynamic));
  16036. ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
  16037. ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
  16038. ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
  16039. ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
  16040. ast_cli(fd, " Force rport : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)));
  16041. ast_cli(fd, " ACL : %s\n", AST_CLI_YESNO(peer->ha != NULL));
  16042. ast_cli(fd, " DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
  16043. ast_cli(fd, " T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
  16044. ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
  16045. ast_cli(fd, " T.38 MaxDtgrm: %u\n", peer->t38_maxdatagram);
  16046. ast_cli(fd, " DirectMedia : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
  16047. ast_cli(fd, " PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
  16048. ast_cli(fd, " User=Phone : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
  16049. 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)));
  16050. ast_cli(fd, " Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
  16051. ast_cli(fd, " Ign SDP ver : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
  16052. ast_cli(fd, " Trust RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
  16053. ast_cli(fd, " Send RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
  16054. ast_cli(fd, " TrustIDOutbnd: %s\n", trust_id_outbound2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND)));
  16055. ast_cli(fd, " Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
  16056. ast_cli(fd, " Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
  16057. if (peer->outboundproxy)
  16058. ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
  16059. peer->outboundproxy->force ? "(forced)" : "");
  16060. /* - is enumerated */
  16061. ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
  16062. ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
  16063. ast_cli(fd, " Timer B : %d\n", peer->timer_b);
  16064. ast_cli(fd, " ToHost : %s\n", peer->tohost);
  16065. ast_cli(fd, " Addr->IP : %s\n", ast_sockaddr_stringify(&peer->addr));
  16066. ast_cli(fd, " Defaddr->IP : %s\n", ast_sockaddr_stringify(&peer->defaddr));
  16067. ast_cli(fd, " Prim.Transp. : %s\n", get_transport(peer->socket.type));
  16068. ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
  16069. if (!ast_strlen_zero(sip_cfg.regcontext))
  16070. ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
  16071. ast_cli(fd, " Def. Username: %s\n", peer->username);
  16072. ast_cli(fd, " SIP Options : ");
  16073. if (peer->sipoptions) {
  16074. int lastoption = -1;
  16075. for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
  16076. if (sip_options[x].id != lastoption) {
  16077. if (peer->sipoptions & sip_options[x].id)
  16078. ast_cli(fd, "%s ", sip_options[x].text);
  16079. lastoption = x;
  16080. }
  16081. }
  16082. } else
  16083. ast_cli(fd, "(none)");
  16084. ast_cli(fd, "\n");
  16085. ast_cli(fd, " Codecs : ");
  16086. ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
  16087. ast_cli(fd, "%s\n", codec_buf);
  16088. ast_cli(fd, " Codec Order : (");
  16089. print_codec_to_cli(fd, &peer->prefs);
  16090. ast_cli(fd, ")\n");
  16091. ast_cli(fd, " Auto-Framing : %s\n", AST_CLI_YESNO(peer->autoframing));
  16092. ast_cli(fd, " Status : ");
  16093. peer_status(peer, status, sizeof(status));
  16094. ast_cli(fd, "%s\n", status);
  16095. ast_cli(fd, " Useragent : %s\n", peer->useragent);
  16096. ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
  16097. ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
  16098. if (peer->chanvars) {
  16099. ast_cli(fd, " Variables :\n");
  16100. for (v = peer->chanvars ; v ; v = v->next)
  16101. ast_cli(fd, " %s = %s\n", v->name, v->value);
  16102. }
  16103. ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
  16104. ast_cli(fd, " Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
  16105. ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
  16106. ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
  16107. ast_cli(fd, " RTP Engine : %s\n", peer->engine);
  16108. ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
  16109. ast_cli(fd, " Use Reason : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
  16110. ast_cli(fd, " Encryption : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
  16111. ast_cli(fd, "\n");
  16112. peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
  16113. } else if (peer && type == 1) { /* manager listing */
  16114. char buffer[256];
  16115. struct ast_str *mailbox_str = ast_str_alloca(512);
  16116. astman_append(s, "Channeltype: SIP\r\n");
  16117. astman_append(s, "ObjectName: %s\r\n", peer->name);
  16118. astman_append(s, "ChanObjectType: peer\r\n");
  16119. astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
  16120. astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
  16121. astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
  16122. astman_append(s, "Context: %s\r\n", peer->context);
  16123. astman_append(s, "Language: %s\r\n", peer->language);
  16124. if (!ast_strlen_zero(peer->accountcode))
  16125. astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
  16126. astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
  16127. astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
  16128. if (!ast_strlen_zero(peer->fromuser))
  16129. astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
  16130. if (!ast_strlen_zero(peer->fromdomain))
  16131. astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
  16132. astman_append(s, "Callgroup: ");
  16133. astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
  16134. astman_append(s, "Pickupgroup: ");
  16135. astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
  16136. astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
  16137. peer_mailboxes_to_str(&mailbox_str, peer);
  16138. astman_append(s, "VoiceMailbox: %s\r\n", ast_str_buffer(mailbox_str));
  16139. astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
  16140. astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
  16141. astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
  16142. astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
  16143. astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
  16144. astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
  16145. astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
  16146. astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
  16147. astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
  16148. astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
  16149. astman_append(s, "SIP-Forcerport: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)?"Y":"N"));
  16150. astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
  16151. astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
  16152. astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
  16153. astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
  16154. astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
  16155. astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
  16156. astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
  16157. astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
  16158. astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
  16159. astman_append(s, "SIP-T.38MaxDtgrm: %u\r\n", peer->t38_maxdatagram);
  16160. astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
  16161. astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
  16162. astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
  16163. astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
  16164. astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
  16165. astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
  16166. /* - is enumerated */
  16167. astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
  16168. astman_append(s, "ToHost: %s\r\n", peer->tohost);
  16169. astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
  16170. 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));
  16171. astman_append(s, "Default-Username: %s\r\n", peer->username);
  16172. if (!ast_strlen_zero(sip_cfg.regcontext))
  16173. astman_append(s, "RegExtension: %s\r\n", peer->regexten);
  16174. astman_append(s, "Codecs: ");
  16175. ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
  16176. astman_append(s, "%s\r\n", codec_buf);
  16177. astman_append(s, "CodecOrder: ");
  16178. pref = &peer->prefs;
  16179. for(x = 0; x < 64 ; x++) {
  16180. codec = ast_codec_pref_index(pref, x);
  16181. if (!codec)
  16182. break;
  16183. astman_append(s, "%s", ast_getformatname(codec));
  16184. if (x < 63 && ast_codec_pref_index(pref, x+1))
  16185. astman_append(s, ",");
  16186. }
  16187. astman_append(s, "\r\n");
  16188. astman_append(s, "Status: ");
  16189. peer_status(peer, status, sizeof(status));
  16190. astman_append(s, "%s\r\n", status);
  16191. astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
  16192. astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
  16193. astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
  16194. astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
  16195. if (peer->chanvars) {
  16196. for (v = peer->chanvars ; v ; v = v->next) {
  16197. astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
  16198. }
  16199. }
  16200. astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
  16201. peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
  16202. } else {
  16203. ast_cli(fd, "Peer %s not found.\n", argv[3]);
  16204. ast_cli(fd, "\n");
  16205. }
  16206. return CLI_SUCCESS;
  16207. }
  16208. /*! \brief Do completion on user name */
  16209. static char *complete_sip_user(const char *word, int state)
  16210. {
  16211. char *result = NULL;
  16212. int wordlen = strlen(word);
  16213. int which = 0;
  16214. struct ao2_iterator user_iter;
  16215. struct sip_peer *user;
  16216. user_iter = ao2_iterator_init(peers, 0);
  16217. while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
  16218. ao2_lock(user);
  16219. if (!(user->type & SIP_TYPE_USER)) {
  16220. ao2_unlock(user);
  16221. unref_peer(user, "complete sip user");
  16222. continue;
  16223. }
  16224. /* locking of the object is not required because only the name and flags are being compared */
  16225. if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
  16226. result = ast_strdup(user->name);
  16227. }
  16228. ao2_unlock(user);
  16229. unref_peer(user, "complete sip user");
  16230. if (result) {
  16231. break;
  16232. }
  16233. }
  16234. ao2_iterator_destroy(&user_iter);
  16235. return result;
  16236. }
  16237. /*! \brief Support routine for 'sip show user' CLI */
  16238. static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
  16239. {
  16240. if (pos == 3)
  16241. return complete_sip_user(word, state);
  16242. return NULL;
  16243. }
  16244. /*! \brief Show one user in detail */
  16245. static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16246. {
  16247. char cbuf[256];
  16248. struct sip_peer *user;
  16249. struct ast_variable *v;
  16250. int load_realtime;
  16251. switch (cmd) {
  16252. case CLI_INIT:
  16253. e->command = "sip show user";
  16254. e->usage =
  16255. "Usage: sip show user <name> [load]\n"
  16256. " Shows all details on one SIP user and the current status.\n"
  16257. " Option \"load\" forces lookup of peer in realtime storage.\n";
  16258. return NULL;
  16259. case CLI_GENERATE:
  16260. return complete_sip_show_user(a->line, a->word, a->pos, a->n);
  16261. }
  16262. if (a->argc < 4)
  16263. return CLI_SHOWUSAGE;
  16264. /* Load from realtime storage? */
  16265. load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
  16266. if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
  16267. ao2_lock(user);
  16268. ast_cli(a->fd, "\n\n");
  16269. ast_cli(a->fd, " * Name : %s\n", user->name);
  16270. ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
  16271. ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
  16272. ast_cli(a->fd, " Context : %s\n", user->context);
  16273. ast_cli(a->fd, " Language : %s\n", user->language);
  16274. if (!ast_strlen_zero(user->accountcode))
  16275. ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
  16276. ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
  16277. ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
  16278. ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
  16279. ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
  16280. ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
  16281. ast_cli(a->fd, " Callgroup : ");
  16282. print_group(a->fd, user->callgroup, 0);
  16283. ast_cli(a->fd, " Pickupgroup : ");
  16284. print_group(a->fd, user->pickupgroup, 0);
  16285. ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
  16286. ast_cli(a->fd, " ACL : %s\n", AST_CLI_YESNO(user->ha != NULL));
  16287. ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
  16288. ast_cli(a->fd, " Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
  16289. ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
  16290. ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
  16291. ast_cli(a->fd, " RTP Engine : %s\n", user->engine);
  16292. ast_cli(a->fd, " Codec Order : (");
  16293. print_codec_to_cli(a->fd, &user->prefs);
  16294. ast_cli(a->fd, ")\n");
  16295. ast_cli(a->fd, " Auto-Framing: %s \n", AST_CLI_YESNO(user->autoframing));
  16296. if (user->chanvars) {
  16297. ast_cli(a->fd, " Variables :\n");
  16298. for (v = user->chanvars ; v ; v = v->next)
  16299. ast_cli(a->fd, " %s = %s\n", v->name, v->value);
  16300. }
  16301. ast_cli(a->fd, "\n");
  16302. ao2_unlock(user);
  16303. unref_peer(user, "sip show user");
  16304. } else {
  16305. ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
  16306. ast_cli(a->fd, "\n");
  16307. }
  16308. return CLI_SUCCESS;
  16309. }
  16310. static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16311. {
  16312. struct ast_str *cbuf;
  16313. struct ast_cb_names cbnames = {9, { "retrans_pkt",
  16314. "__sip_autodestruct",
  16315. "expire_register",
  16316. "auto_congest",
  16317. "sip_reg_timeout",
  16318. "sip_poke_peer_s",
  16319. "sip_poke_noanswer",
  16320. "sip_reregister",
  16321. "sip_reinvite_retry"},
  16322. { retrans_pkt,
  16323. __sip_autodestruct,
  16324. expire_register,
  16325. auto_congest,
  16326. sip_reg_timeout,
  16327. sip_poke_peer_s,
  16328. sip_poke_noanswer,
  16329. sip_reregister,
  16330. sip_reinvite_retry}};
  16331. switch (cmd) {
  16332. case CLI_INIT:
  16333. e->command = "sip show sched";
  16334. e->usage =
  16335. "Usage: sip show sched\n"
  16336. " Shows stats on what's in the sched queue at the moment\n";
  16337. return NULL;
  16338. case CLI_GENERATE:
  16339. return NULL;
  16340. }
  16341. cbuf = ast_str_alloca(2048);
  16342. ast_cli(a->fd, "\n");
  16343. ast_sched_report(sched, &cbuf, &cbnames);
  16344. ast_cli(a->fd, "%s", ast_str_buffer(cbuf));
  16345. return CLI_SUCCESS;
  16346. }
  16347. /*! \brief Show SIP Registry (registrations with other SIP proxies */
  16348. static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16349. {
  16350. #define FORMAT2 "%-39.39s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
  16351. #define FORMAT "%-39.39s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
  16352. char host[80];
  16353. char user[80];
  16354. char tmpdat[256];
  16355. struct ast_tm tm;
  16356. int counter = 0;
  16357. switch (cmd) {
  16358. case CLI_INIT:
  16359. e->command = "sip show registry";
  16360. e->usage =
  16361. "Usage: sip show registry\n"
  16362. " Lists all registration requests and status.\n";
  16363. return NULL;
  16364. case CLI_GENERATE:
  16365. return NULL;
  16366. }
  16367. if (a->argc != 3)
  16368. return CLI_SHOWUSAGE;
  16369. ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
  16370. ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
  16371. ASTOBJ_RDLOCK(iterator);
  16372. snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
  16373. snprintf(user, sizeof(user), "%s", iterator->username);
  16374. if (!ast_strlen_zero(iterator->regdomain)) {
  16375. snprintf(tmpdat, sizeof(tmpdat), "%s", user);
  16376. snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
  16377. if (iterator->regdomainport) {
  16378. snprintf(tmpdat, sizeof(tmpdat), "%s", user);
  16379. snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
  16380. if (iterator->regtime.tv_sec) {
  16381. ast_localtime(&iterator->regtime, &tm, NULL);
  16382. ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
  16383. } else
  16384. tmpdat[0] = '\0';
  16385. ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
  16386. ASTOBJ_UNLOCK(iterator);
  16387. counter++;
  16388. } while(0));
  16389. ast_cli(a->fd, "%d SIP registrations.\n", counter);
  16390. return CLI_SUCCESS;
  16391. #undef FORMAT
  16392. #undef FORMAT2
  16393. }
  16394. /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
  16395. \note This function does not tell the SIP device what's going on,
  16396. so use it with great care.
  16397. */
  16398. static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16399. {
  16400. struct sip_peer *peer;
  16401. int load_realtime = 0;
  16402. switch (cmd) {
  16403. case CLI_INIT:
  16404. e->command = "sip unregister";
  16405. e->usage =
  16406. "Usage: sip unregister <peer>\n"
  16407. " Unregister (force expiration) a SIP peer from the registry\n";
  16408. return NULL;
  16409. case CLI_GENERATE:
  16410. return complete_sip_unregister(a->line, a->word, a->pos, a->n);
  16411. }
  16412. if (a->argc != 3)
  16413. return CLI_SHOWUSAGE;
  16414. if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
  16415. if (peer->expire > 0) {
  16416. AST_SCHED_DEL_UNREF(sched, peer->expire,
  16417. unref_peer(peer, "remove register expire ref"));
  16418. expire_register(ref_peer(peer, "ref for expire_register"));
  16419. ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
  16420. } else {
  16421. ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
  16422. }
  16423. unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
  16424. } else {
  16425. ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
  16426. }
  16427. return CLI_SUCCESS;
  16428. }
  16429. /*! \brief Callback for show_chanstats */
  16430. static int show_chanstats_cb(void *__cur, void *__arg, int flags)
  16431. {
  16432. #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
  16433. #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"
  16434. struct sip_pvt *cur = __cur;
  16435. struct ast_rtp_instance_stats stats;
  16436. char durbuf[10];
  16437. int duration;
  16438. int durh, durm, durs;
  16439. struct ast_channel *c;
  16440. struct __show_chan_arg *arg = __arg;
  16441. int fd = arg->fd;
  16442. sip_pvt_lock(cur);
  16443. c = cur->owner;
  16444. if (cur->subscribed != NONE) {
  16445. /* Subscriptions */
  16446. sip_pvt_unlock(cur);
  16447. return 0; /* don't care, we scan all channels */
  16448. }
  16449. if (!cur->rtp) {
  16450. if (sipdebug) {
  16451. ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n",
  16452. ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
  16453. invitestate2string[cur->invitestate].desc,
  16454. "-- No RTP active");
  16455. }
  16456. sip_pvt_unlock(cur);
  16457. return 0; /* don't care, we scan all channels */
  16458. }
  16459. if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
  16460. sip_pvt_unlock(cur);
  16461. ast_log(LOG_WARNING, "Could not get RTP stats.\n");
  16462. return 0;
  16463. }
  16464. if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
  16465. duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
  16466. durh = duration / 3600;
  16467. durm = (duration % 3600) / 60;
  16468. durs = duration % 60;
  16469. snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
  16470. } else {
  16471. durbuf[0] = '\0';
  16472. }
  16473. ast_cli(fd, FORMAT,
  16474. ast_sockaddr_stringify_addr(&cur->sa),
  16475. cur->callid,
  16476. durbuf,
  16477. stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
  16478. stats.rxcount > (unsigned int) 100000 ? "K":" ",
  16479. stats.rxploss,
  16480. (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
  16481. stats.rxjitter,
  16482. stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
  16483. stats.txcount > (unsigned int) 100000 ? "K":" ",
  16484. stats.txploss,
  16485. stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
  16486. stats.txjitter
  16487. );
  16488. arg->numchans++;
  16489. sip_pvt_unlock(cur);
  16490. return 0; /* don't care, we scan all channels */
  16491. }
  16492. /*! \brief SIP show channelstats CLI (main function) */
  16493. static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16494. {
  16495. struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
  16496. switch (cmd) {
  16497. case CLI_INIT:
  16498. e->command = "sip show channelstats";
  16499. e->usage =
  16500. "Usage: sip show channelstats\n"
  16501. " Lists all currently active SIP channel's RTCP statistics.\n"
  16502. " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
  16503. return NULL;
  16504. case CLI_GENERATE:
  16505. return NULL;
  16506. }
  16507. if (a->argc != 3)
  16508. return CLI_SHOWUSAGE;
  16509. ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
  16510. /* iterate on the container and invoke the callback on each item */
  16511. ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
  16512. ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
  16513. return CLI_SUCCESS;
  16514. }
  16515. #undef FORMAT
  16516. #undef FORMAT2
  16517. /*! \brief List global settings for the SIP channel */
  16518. static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16519. {
  16520. int realtimepeers;
  16521. int realtimeregs;
  16522. char codec_buf[SIPBUFSIZE];
  16523. const char *msg; /* temporary msg pointer */
  16524. struct sip_auth_container *credentials;
  16525. switch (cmd) {
  16526. case CLI_INIT:
  16527. e->command = "sip show settings";
  16528. e->usage =
  16529. "Usage: sip show settings\n"
  16530. " Provides detailed list of the configuration of the SIP channel.\n";
  16531. return NULL;
  16532. case CLI_GENERATE:
  16533. return NULL;
  16534. }
  16535. if (a->argc != 3)
  16536. return CLI_SHOWUSAGE;
  16537. realtimepeers = ast_check_realtime("sippeers");
  16538. realtimeregs = ast_check_realtime("sipregs");
  16539. ast_mutex_lock(&authl_lock);
  16540. credentials = authl;
  16541. if (credentials) {
  16542. ao2_t_ref(credentials, +1, "Ref global auth for show");
  16543. }
  16544. ast_mutex_unlock(&authl_lock);
  16545. ast_cli(a->fd, "\n\nGlobal Settings:\n");
  16546. ast_cli(a->fd, "----------------\n");
  16547. ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_sockaddr_stringify(&bindaddr));
  16548. if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
  16549. ast_cli(a->fd, " ** Additional Info:\n");
  16550. ast_cli(a->fd, " [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
  16551. }
  16552. ast_cli(a->fd, " TCP SIP Bindaddress: %s\n",
  16553. sip_cfg.tcp_enabled != FALSE ?
  16554. ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
  16555. "Disabled");
  16556. ast_cli(a->fd, " TLS SIP Bindaddress: %s\n",
  16557. default_tls_cfg.enabled != FALSE ?
  16558. ast_sockaddr_stringify(&sip_tls_desc.local_address) :
  16559. "Disabled");
  16560. ast_cli(a->fd, " Videosupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
  16561. ast_cli(a->fd, " Textsupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
  16562. ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
  16563. ast_cli(a->fd, " AutoCreate Peer: %s\n", AST_CLI_YESNO(sip_cfg.autocreatepeer));
  16564. ast_cli(a->fd, " Match Auth Username: %s\n", AST_CLI_YESNO(global_match_auth_username));
  16565. ast_cli(a->fd, " Allow unknown access: %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
  16566. ast_cli(a->fd, " Allow subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
  16567. ast_cli(a->fd, " Allow overlap dialing: %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
  16568. ast_cli(a->fd, " Allow promisc. redir: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
  16569. ast_cli(a->fd, " Enable call counters: %s\n", AST_CLI_YESNO(global_callcounter));
  16570. ast_cli(a->fd, " SIP domain support: %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
  16571. ast_cli(a->fd, " Realm. auth: %s\n", AST_CLI_YESNO(credentials != NULL));
  16572. if (credentials) {
  16573. struct sip_auth *auth;
  16574. AST_LIST_TRAVERSE(&credentials->list, auth, node) {
  16575. ast_cli(a->fd, " Realm. auth entry: Realm %-15.15s User %-10.20s %s\n",
  16576. auth->realm,
  16577. auth->username,
  16578. !ast_strlen_zero(auth->secret)
  16579. ? "<Secret set>"
  16580. : (!ast_strlen_zero(auth->md5secret)
  16581. ? "<MD5secret set>" : "<Not set>"));
  16582. }
  16583. ao2_t_ref(credentials, -1, "Unref global auth for show");
  16584. }
  16585. ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
  16586. ast_cli(a->fd, " Use domains as realms: %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
  16587. ast_cli(a->fd, " Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
  16588. ast_cli(a->fd, " URI user is phone no: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
  16589. ast_cli(a->fd, " Always auth rejects: %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
  16590. ast_cli(a->fd, " Direct RTP setup: %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
  16591. ast_cli(a->fd, " User Agent: %s\n", global_useragent);
  16592. ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
  16593. ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
  16594. ast_cli(a->fd, " Reg. context: %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
  16595. ast_cli(a->fd, " Regexten on Qualify: %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
  16596. ast_cli(a->fd, " Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
  16597. ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
  16598. if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
  16599. ast_cli(a->fd, " From: Domain: %s:%d\n", default_fromdomain, default_fromdomainport);
  16600. } else {
  16601. ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
  16602. }
  16603. ast_cli(a->fd, " Record SIP history: %s\n", AST_CLI_ONOFF(recordhistory));
  16604. ast_cli(a->fd, " Call Events: %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
  16605. ast_cli(a->fd, " Auth. Failure Events: %s\n", AST_CLI_ONOFF(global_authfailureevents));
  16606. ast_cli(a->fd, " T.38 support: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
  16607. ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
  16608. ast_cli(a->fd, " T.38 MaxDtgrm: %u\n", global_t38_maxdatagram);
  16609. if (!realtimepeers && !realtimeregs)
  16610. ast_cli(a->fd, " SIP realtime: Disabled\n" );
  16611. else
  16612. ast_cli(a->fd, " SIP realtime: Enabled\n" );
  16613. ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
  16614. ast_cli(a->fd, " Q.850 Reason header: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
  16615. ast_cli(a->fd, " Store SIP_CAUSE: %s\n", AST_CLI_YESNO(global_store_sip_cause));
  16616. ast_cli(a->fd, "\nNetwork QoS Settings:\n");
  16617. ast_cli(a->fd, "---------------------------\n");
  16618. ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
  16619. ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
  16620. ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
  16621. ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
  16622. ast_cli(a->fd, " 802.1p CoS SIP: %u\n", global_cos_sip);
  16623. ast_cli(a->fd, " 802.1p CoS RTP audio: %u\n", global_cos_audio);
  16624. ast_cli(a->fd, " 802.1p CoS RTP video: %u\n", global_cos_video);
  16625. ast_cli(a->fd, " 802.1p CoS RTP text: %u\n", global_cos_text);
  16626. ast_cli(a->fd, " Jitterbuffer enabled: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
  16627. if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
  16628. ast_cli(a->fd, " Jitterbuffer forced: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
  16629. ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
  16630. ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
  16631. ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
  16632. if (!strcasecmp(global_jbconf.impl, "adaptive")) {
  16633. ast_cli(a->fd, " Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
  16634. }
  16635. ast_cli(a->fd, " Jitterbuffer log: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
  16636. }
  16637. ast_cli(a->fd, "\nNetwork Settings:\n");
  16638. ast_cli(a->fd, "---------------------------\n");
  16639. /* determine if/how SIP address can be remapped */
  16640. if (localaddr == NULL)
  16641. msg = "Disabled, no localnet list";
  16642. else if (ast_sockaddr_isnull(&externaddr))
  16643. msg = "Disabled";
  16644. else if (!ast_strlen_zero(externhost))
  16645. msg = "Enabled using externhost";
  16646. else
  16647. msg = "Enabled using externaddr";
  16648. ast_cli(a->fd, " SIP address remapping: %s\n", msg);
  16649. ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
  16650. ast_cli(a->fd, " Externaddr: %s\n", ast_sockaddr_stringify(&externaddr));
  16651. ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
  16652. {
  16653. struct ast_ha *d;
  16654. const char *prefix = "Localnet:";
  16655. for (d = localaddr; d ; prefix = "", d = d->next) {
  16656. const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
  16657. const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
  16658. ast_cli(a->fd, " %-24s%s/%s\n", prefix, addr, mask);
  16659. }
  16660. }
  16661. ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
  16662. ast_cli(a->fd, "---------------------------\n");
  16663. ast_cli(a->fd, " Codecs: ");
  16664. ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.capability);
  16665. ast_cli(a->fd, "%s\n", codec_buf);
  16666. ast_cli(a->fd, " Codec Order: ");
  16667. print_codec_to_cli(a->fd, &default_prefs);
  16668. ast_cli(a->fd, "\n");
  16669. ast_cli(a->fd, " Relax DTMF: %s\n", AST_CLI_YESNO(global_relaxdtmf));
  16670. ast_cli(a->fd, " RFC2833 Compensation: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
  16671. ast_cli(a->fd, " Symmetric RTP: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
  16672. ast_cli(a->fd, " Compact SIP headers: %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
  16673. ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
  16674. ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
  16675. ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
  16676. ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
  16677. ast_cli(a->fd, " DNS SRV lookup: %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
  16678. ast_cli(a->fd, " Pedantic SIP support: %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
  16679. ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
  16680. ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
  16681. ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
  16682. ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
  16683. ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
  16684. ast_cli(a->fd, " Outbound reg. retry 403:%d\n", global_reg_retry_403);
  16685. ast_cli(a->fd, " Notify ringing state: %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
  16686. if (sip_cfg.notifyringing) {
  16687. ast_cli(a->fd, " Include CID: %s%s\n",
  16688. AST_CLI_YESNO(sip_cfg.notifycid),
  16689. sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
  16690. }
  16691. ast_cli(a->fd, " Notify hold state: %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
  16692. ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
  16693. ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
  16694. ast_cli(a->fd, " Auto-Framing: %s\n", AST_CLI_YESNO(global_autoframing));
  16695. ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
  16696. sip_cfg.outboundproxy.force ? "(forced)" : "");
  16697. ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
  16698. ast_cli(a->fd, " Session Refresher: %s\n", strefresherparam2str(global_st_refresher));
  16699. ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
  16700. ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
  16701. ast_cli(a->fd, " Timer T1: %d\n", global_t1);
  16702. ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
  16703. ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
  16704. ast_cli(a->fd, " No premature media: %s\n", AST_CLI_YESNO(global_prematuremediafilter));
  16705. ast_cli(a->fd, " Max forwards: %d\n", sip_cfg.default_max_forwards);
  16706. ast_cli(a->fd, "\nDefault Settings:\n");
  16707. ast_cli(a->fd, "-----------------\n");
  16708. ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
  16709. ast_cli(a->fd, " Outbound transport: %s\n", get_transport(default_primary_transport));
  16710. ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
  16711. ast_cli(a->fd, " Force rport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT)));
  16712. ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
  16713. ast_cli(a->fd, " Qualify: %d\n", default_qualify);
  16714. ast_cli(a->fd, " Use ClientCode: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
  16715. 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)));
  16716. ast_cli(a->fd, " Language: %s\n", default_language);
  16717. ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
  16718. ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
  16719. ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
  16720. if (realtimepeers || realtimeregs) {
  16721. ast_cli(a->fd, "\nRealtime SIP Settings:\n");
  16722. ast_cli(a->fd, "----------------------\n");
  16723. ast_cli(a->fd, " Realtime Peers: %s\n", AST_CLI_YESNO(realtimepeers));
  16724. ast_cli(a->fd, " Realtime Regs: %s\n", AST_CLI_YESNO(realtimeregs));
  16725. ast_cli(a->fd, " Cache Friends: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
  16726. ast_cli(a->fd, " Update: %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
  16727. ast_cli(a->fd, " Ignore Reg. Expire: %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
  16728. ast_cli(a->fd, " Save sys. name: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
  16729. ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
  16730. }
  16731. ast_cli(a->fd, "\n----\n");
  16732. return CLI_SUCCESS;
  16733. }
  16734. static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16735. {
  16736. #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
  16737. char host[80];
  16738. switch (cmd) {
  16739. case CLI_INIT:
  16740. e->command = "sip show mwi";
  16741. e->usage =
  16742. "Usage: sip show mwi\n"
  16743. " Provides a list of MWI subscriptions and status.\n";
  16744. return NULL;
  16745. case CLI_GENERATE:
  16746. return NULL;
  16747. }
  16748. ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
  16749. ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
  16750. ASTOBJ_RDLOCK(iterator);
  16751. snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
  16752. ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
  16753. ASTOBJ_UNLOCK(iterator);
  16754. } while(0));
  16755. return CLI_SUCCESS;
  16756. #undef FORMAT
  16757. }
  16758. /*! \brief Show subscription type in string format */
  16759. static const char *subscription_type2str(enum subscriptiontype subtype)
  16760. {
  16761. int i;
  16762. for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
  16763. if (subscription_types[i].type == subtype) {
  16764. return subscription_types[i].text;
  16765. }
  16766. }
  16767. return subscription_types[0].text;
  16768. }
  16769. /*! \brief Find subscription type in array */
  16770. static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
  16771. {
  16772. int i;
  16773. for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
  16774. if (subscription_types[i].type == subtype) {
  16775. return &subscription_types[i];
  16776. }
  16777. }
  16778. return &subscription_types[0];
  16779. }
  16780. /*
  16781. * We try to structure all functions that loop on data structures as
  16782. * a handler for individual entries, and a mainloop that iterates
  16783. * on the main data structure. This way, moving the code to containers
  16784. * that support iteration through callbacks will be a lot easier.
  16785. */
  16786. #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
  16787. #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
  16788. #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-10.10s %-10.10s\n"
  16789. #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s %-10.10s\n"
  16790. /*! \brief callback for show channel|subscription */
  16791. static int show_channels_cb(void *__cur, void *__arg, int flags)
  16792. {
  16793. struct sip_pvt *cur = __cur;
  16794. struct __show_chan_arg *arg = __arg;
  16795. const struct ast_sockaddr *dst;
  16796. sip_pvt_lock(cur);
  16797. dst = sip_real_dst(cur);
  16798. /* XXX indentation preserved to reduce diff. Will be fixed later */
  16799. if (cur->subscribed == NONE && !arg->subscriptions) {
  16800. /* set if SIP transfer in progress */
  16801. const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
  16802. char formatbuf[SIPBUFSIZE/2];
  16803. ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
  16804. S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
  16805. cur->callid,
  16806. ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
  16807. AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
  16808. cur->needdestroy ? "(d)" : "",
  16809. cur->lastmsg ,
  16810. referstatus,
  16811. cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
  16812. );
  16813. arg->numchans++;
  16814. }
  16815. if (cur->subscribed != NONE && arg->subscriptions) {
  16816. struct ast_str *mailbox_str = ast_str_alloca(512);
  16817. if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
  16818. peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
  16819. ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
  16820. S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
  16821. cur->callid,
  16822. /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
  16823. cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
  16824. cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
  16825. subscription_type2str(cur->subscribed),
  16826. cur->subscribed == MWI_NOTIFICATION ? S_OR(ast_str_buffer(mailbox_str), "<none>") : "<none>",
  16827. cur->expiry
  16828. );
  16829. arg->numchans++;
  16830. }
  16831. sip_pvt_unlock(cur);
  16832. return 0; /* don't care, we scan all channels */
  16833. }
  16834. /*! \brief CLI for show channels or subscriptions.
  16835. * This is a new-style CLI handler so a single function contains
  16836. * the prototype for the function, the 'generator' to produce multiple
  16837. * entries in case it is required, and the actual handler for the command.
  16838. */
  16839. static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  16840. {
  16841. struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
  16842. if (cmd == CLI_INIT) {
  16843. e->command = "sip show {channels|subscriptions}";
  16844. e->usage =
  16845. "Usage: sip show channels\n"
  16846. " Lists all currently active SIP calls (dialogs).\n"
  16847. "Usage: sip show subscriptions\n"
  16848. " Lists active SIP subscriptions.\n";
  16849. return NULL;
  16850. } else if (cmd == CLI_GENERATE)
  16851. return NULL;
  16852. if (a->argc != e->args)
  16853. return CLI_SHOWUSAGE;
  16854. arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
  16855. if (!arg.subscriptions)
  16856. ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
  16857. else
  16858. ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
  16859. /* iterate on the container and invoke the callback on each item */
  16860. ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
  16861. /* print summary information */
  16862. ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
  16863. (arg.subscriptions ? "subscription" : "dialog"),
  16864. ESS(arg.numchans)); /* ESS(n) returns an "s" if n>1 */
  16865. return CLI_SUCCESS;
  16866. #undef FORMAT
  16867. #undef FORMAT2
  16868. #undef FORMAT3
  16869. }
  16870. /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
  16871. * This is in charge of generating all strings that match a prefix in the
  16872. * given position. As many functions of this kind, each invokation has
  16873. * O(state) time complexity so be careful in using it.
  16874. */
  16875. static char *complete_sipch(const char *line, const char *word, int pos, int state)
  16876. {
  16877. int which=0;
  16878. struct sip_pvt *cur;
  16879. char *c = NULL;
  16880. int wordlen = strlen(word);
  16881. struct ao2_iterator i;
  16882. if (pos != 3) {
  16883. return NULL;
  16884. }
  16885. i = ao2_iterator_init(dialogs, 0);
  16886. while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  16887. sip_pvt_lock(cur);
  16888. if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
  16889. c = ast_strdup(cur->callid);
  16890. sip_pvt_unlock(cur);
  16891. dialog_unref(cur, "drop ref in iterator loop break");
  16892. break;
  16893. }
  16894. sip_pvt_unlock(cur);
  16895. dialog_unref(cur, "drop ref in iterator loop");
  16896. }
  16897. ao2_iterator_destroy(&i);
  16898. return c;
  16899. }
  16900. /*! \brief Do completion on peer name */
  16901. static char *complete_sip_peer(const char *word, int state, int flags2)
  16902. {
  16903. char *result = NULL;
  16904. int wordlen = strlen(word);
  16905. int which = 0;
  16906. struct ao2_iterator i = ao2_iterator_init(peers, 0);
  16907. struct sip_peer *peer;
  16908. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  16909. /* locking of the object is not required because only the name and flags are being compared */
  16910. if (!strncasecmp(word, peer->name, wordlen) &&
  16911. (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
  16912. ++which > state)
  16913. result = ast_strdup(peer->name);
  16914. unref_peer(peer, "toss iterator peer ptr before break");
  16915. if (result) {
  16916. break;
  16917. }
  16918. }
  16919. ao2_iterator_destroy(&i);
  16920. return result;
  16921. }
  16922. /*! \brief Do completion on registered peer name */
  16923. static char *complete_sip_registered_peer(const char *word, int state, int flags2)
  16924. {
  16925. char *result = NULL;
  16926. int wordlen = strlen(word);
  16927. int which = 0;
  16928. struct ao2_iterator i;
  16929. struct sip_peer *peer;
  16930. i = ao2_iterator_init(peers, 0);
  16931. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  16932. if (!strncasecmp(word, peer->name, wordlen) &&
  16933. (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
  16934. ++which > state && peer->expire > 0)
  16935. result = ast_strdup(peer->name);
  16936. if (result) {
  16937. unref_peer(peer, "toss iterator peer ptr before break");
  16938. break;
  16939. }
  16940. unref_peer(peer, "toss iterator peer ptr");
  16941. }
  16942. ao2_iterator_destroy(&i);
  16943. return result;
  16944. }
  16945. /*! \brief Support routine for 'sip show history' CLI */
  16946. static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
  16947. {
  16948. if (pos == 3)
  16949. return complete_sipch(line, word, pos, state);
  16950. return NULL;
  16951. }
  16952. /*! \brief Support routine for 'sip show peer' CLI */
  16953. static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
  16954. {
  16955. if (pos == 3) {
  16956. return complete_sip_peer(word, state, 0);
  16957. }
  16958. return NULL;
  16959. }
  16960. /*! \brief Support routine for 'sip unregister' CLI */
  16961. static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
  16962. {
  16963. if (pos == 2)
  16964. return complete_sip_registered_peer(word, state, 0);
  16965. return NULL;
  16966. }
  16967. /*! \brief Support routine for 'sip notify' CLI */
  16968. static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
  16969. {
  16970. char *c = NULL;
  16971. if (pos == 2) {
  16972. int which = 0;
  16973. char *cat = NULL;
  16974. int wordlen = strlen(word);
  16975. /* do completion for notify type */
  16976. if (!notify_types)
  16977. return NULL;
  16978. while ( (cat = ast_category_browse(notify_types, cat)) ) {
  16979. if (!strncasecmp(word, cat, wordlen) && ++which > state) {
  16980. c = ast_strdup(cat);
  16981. break;
  16982. }
  16983. }
  16984. return c;
  16985. }
  16986. if (pos > 2)
  16987. return complete_sip_peer(word, state, 0);
  16988. return NULL;
  16989. }
  16990. static const char *transport2str(enum sip_transport transport)
  16991. {
  16992. switch (transport) {
  16993. case SIP_TRANSPORT_TLS:
  16994. return "TLS";
  16995. case SIP_TRANSPORT_UDP:
  16996. return "UDP";
  16997. case SIP_TRANSPORT_TCP:
  16998. return "TCP";
  16999. }
  17000. return "Undefined";
  17001. }
  17002. /*! \brief Show details of one active dialog */
  17003. static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17004. {
  17005. struct sip_pvt *cur;
  17006. size_t len;
  17007. int found = 0;
  17008. struct ao2_iterator i;
  17009. switch (cmd) {
  17010. case CLI_INIT:
  17011. e->command = "sip show channel";
  17012. e->usage =
  17013. "Usage: sip show channel <call-id>\n"
  17014. " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
  17015. return NULL;
  17016. case CLI_GENERATE:
  17017. return complete_sipch(a->line, a->word, a->pos, a->n);
  17018. }
  17019. if (a->argc != 4)
  17020. return CLI_SHOWUSAGE;
  17021. len = strlen(a->argv[3]);
  17022. i = ao2_iterator_init(dialogs, 0);
  17023. while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  17024. sip_pvt_lock(cur);
  17025. if (!strncasecmp(cur->callid, a->argv[3], len)) {
  17026. char formatbuf[SIPBUFSIZE/2];
  17027. ast_cli(a->fd, "\n");
  17028. if (cur->subscribed != NONE)
  17029. ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
  17030. else
  17031. ast_cli(a->fd, " * SIP Call\n");
  17032. ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
  17033. ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
  17034. ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
  17035. ast_cli(a->fd, " Our Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->capability));
  17036. ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
  17037. ast_cli(a->fd, " Their Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercapability));
  17038. ast_cli(a->fd, " Joint Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcapability));
  17039. ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
  17040. ast_cli(a->fd, " T.38 support %s\n", AST_CLI_YESNO(cur->udptl != NULL));
  17041. ast_cli(a->fd, " Video support %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
  17042. ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
  17043. ast_cli(a->fd, " Theoretical Address: %s\n", ast_sockaddr_stringify(&cur->sa));
  17044. ast_cli(a->fd, " Received Address: %s\n", ast_sockaddr_stringify(&cur->recv));
  17045. ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
  17046. ast_cli(a->fd, " Force rport: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_NAT_FORCE_RPORT)));
  17047. if (ast_sockaddr_isnull(&cur->redirip)) {
  17048. ast_cli(a->fd,
  17049. " Audio IP: %s (local)\n",
  17050. ast_sockaddr_stringify_addr(&cur->ourip));
  17051. } else {
  17052. ast_cli(a->fd,
  17053. " Audio IP: %s (Outside bridge)\n",
  17054. ast_sockaddr_stringify_addr(&cur->redirip));
  17055. }
  17056. ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
  17057. ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
  17058. ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
  17059. if (!ast_strlen_zero(cur->username))
  17060. ast_cli(a->fd, " Username: %s\n", cur->username);
  17061. if (!ast_strlen_zero(cur->peername))
  17062. ast_cli(a->fd, " Peername: %s\n", cur->peername);
  17063. if (!ast_strlen_zero(cur->uri))
  17064. ast_cli(a->fd, " Original uri: %s\n", cur->uri);
  17065. if (!ast_strlen_zero(cur->cid_num))
  17066. ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
  17067. ast_cli(a->fd, " Need Destroy: %s\n", AST_CLI_YESNO(cur->needdestroy));
  17068. ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
  17069. ast_cli(a->fd, " Promiscuous Redir: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
  17070. ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
  17071. ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
  17072. ast_cli(a->fd, " SIP Options: ");
  17073. if (cur->sipoptions) {
  17074. int x;
  17075. for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
  17076. if (cur->sipoptions & sip_options[x].id)
  17077. ast_cli(a->fd, "%s ", sip_options[x].text);
  17078. }
  17079. ast_cli(a->fd, "\n");
  17080. } else
  17081. ast_cli(a->fd, "(none)\n");
  17082. if (!cur->stimer)
  17083. ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
  17084. else {
  17085. ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
  17086. if (cur->stimer->st_active == TRUE) {
  17087. ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
  17088. ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
  17089. ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
  17090. ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
  17091. ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
  17092. ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
  17093. ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresherparam2str(cur->stimer->st_cached_ref));
  17094. ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
  17095. }
  17096. }
  17097. /* add transport and media types */
  17098. ast_cli(a->fd, " Transport: %s\n", transport2str(cur->socket.type));
  17099. ast_cli(a->fd, " Media: %s\n", cur->srtp ? "SRTP" : cur->rtp ? "RTP" : "None");
  17100. ast_cli(a->fd, "\n\n");
  17101. found++;
  17102. }
  17103. sip_pvt_unlock(cur);
  17104. ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
  17105. }
  17106. ao2_iterator_destroy(&i);
  17107. if (!found)
  17108. ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
  17109. return CLI_SUCCESS;
  17110. }
  17111. /*! \brief Show history details of one dialog */
  17112. static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17113. {
  17114. struct sip_pvt *cur;
  17115. size_t len;
  17116. int found = 0;
  17117. struct ao2_iterator i;
  17118. switch (cmd) {
  17119. case CLI_INIT:
  17120. e->command = "sip show history";
  17121. e->usage =
  17122. "Usage: sip show history <call-id>\n"
  17123. " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
  17124. return NULL;
  17125. case CLI_GENERATE:
  17126. return complete_sip_show_history(a->line, a->word, a->pos, a->n);
  17127. }
  17128. if (a->argc != 4)
  17129. return CLI_SHOWUSAGE;
  17130. if (!recordhistory)
  17131. ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
  17132. len = strlen(a->argv[3]);
  17133. i = ao2_iterator_init(dialogs, 0);
  17134. while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  17135. sip_pvt_lock(cur);
  17136. if (!strncasecmp(cur->callid, a->argv[3], len)) {
  17137. struct sip_history *hist;
  17138. int x = 0;
  17139. ast_cli(a->fd, "\n");
  17140. if (cur->subscribed != NONE)
  17141. ast_cli(a->fd, " * Subscription\n");
  17142. else
  17143. ast_cli(a->fd, " * SIP Call\n");
  17144. if (cur->history)
  17145. AST_LIST_TRAVERSE(cur->history, hist, list)
  17146. ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
  17147. if (x == 0)
  17148. ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
  17149. found++;
  17150. }
  17151. sip_pvt_unlock(cur);
  17152. ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
  17153. }
  17154. ao2_iterator_destroy(&i);
  17155. if (!found)
  17156. ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
  17157. return CLI_SUCCESS;
  17158. }
  17159. /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
  17160. static void sip_dump_history(struct sip_pvt *dialog)
  17161. {
  17162. int x = 0;
  17163. struct sip_history *hist;
  17164. static int errmsg = 0;
  17165. if (!dialog)
  17166. return;
  17167. if (!option_debug && !sipdebug) {
  17168. if (!errmsg) {
  17169. ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
  17170. errmsg = 1;
  17171. }
  17172. return;
  17173. }
  17174. ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
  17175. if (dialog->subscribed)
  17176. ast_debug(1, " * Subscription\n");
  17177. else
  17178. ast_debug(1, " * SIP Call\n");
  17179. if (dialog->history)
  17180. AST_LIST_TRAVERSE(dialog->history, hist, list)
  17181. ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
  17182. if (!x)
  17183. ast_debug(1, "Call '%s' has no history\n", dialog->callid);
  17184. ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
  17185. }
  17186. /*! \brief Receive SIP INFO Message */
  17187. static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
  17188. {
  17189. char buf[1024] = "";
  17190. unsigned int event;
  17191. const char *c = get_header(req, "Content-Type");
  17192. /* Need to check the media/type */
  17193. if (!strcasecmp(c, "application/dtmf-relay") ||
  17194. !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
  17195. !strcasecmp(c, "application/dtmf")) {
  17196. unsigned int duration = 0;
  17197. if (!p->owner) { /* not a PBX call */
  17198. transmit_response(p, "481 Call leg/transaction does not exist", req);
  17199. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  17200. return;
  17201. }
  17202. /* If dtmf-relay or vnd.nortelnetworks.digits, parse the signal and duration;
  17203. * otherwise use the body as the signal */
  17204. if (strcasecmp(c, "application/dtmf")) {
  17205. const char *msg_body;
  17206. if ( ast_strlen_zero(msg_body = get_body(req, "Signal", '='))
  17207. && ast_strlen_zero(msg_body = get_body(req, "d", '='))) {
  17208. ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
  17209. "call %s\n", p->callid);
  17210. transmit_response(p, "200 OK", req);
  17211. return;
  17212. }
  17213. ast_copy_string(buf, msg_body, sizeof(buf));
  17214. if (!ast_strlen_zero((msg_body = get_body(req, "Duration", '=')))) {
  17215. sscanf(msg_body, "%30u", &duration);
  17216. }
  17217. } else {
  17218. /* Type is application/dtmf, simply use what's in the message body */
  17219. get_msg_text(buf, sizeof(buf), req);
  17220. }
  17221. /* An empty message body requires us to send a 200 OK */
  17222. if (ast_strlen_zero(buf)) {
  17223. transmit_response(p, "200 OK", req);
  17224. return;
  17225. }
  17226. if (!duration) {
  17227. duration = 100; /* 100 ms */
  17228. }
  17229. if (buf[0] == '*') {
  17230. event = 10;
  17231. } else if (buf[0] == '#') {
  17232. event = 11;
  17233. } else if (buf[0] == '!') {
  17234. event = 16;
  17235. } else if ('A' <= buf[0] && buf[0] <= 'D') {
  17236. event = 12 + buf[0] - 'A';
  17237. } else if ('a' <= buf[0] && buf[0] <= 'd') {
  17238. event = 12 + buf[0] - 'a';
  17239. } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
  17240. ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
  17241. "value for INFO message on call %s\n", p->callid);
  17242. transmit_response(p, "200 OK", req);
  17243. return;
  17244. }
  17245. if (event == 16) {
  17246. /* send a FLASH event */
  17247. struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
  17248. ast_queue_frame(p->owner, &f);
  17249. if (sipdebug) {
  17250. ast_verbose("* DTMF-relay event received: FLASH\n");
  17251. }
  17252. } else {
  17253. /* send a DTMF event */
  17254. struct ast_frame f = { AST_FRAME_DTMF, };
  17255. if (event < 10) {
  17256. f.subclass.integer = '0' + event;
  17257. } else if (event == 10) {
  17258. f.subclass.integer = '*';
  17259. } else if (event == 11) {
  17260. f.subclass.integer = '#';
  17261. } else {
  17262. f.subclass.integer = 'A' + (event - 12);
  17263. }
  17264. f.len = duration;
  17265. ast_queue_frame(p->owner, &f);
  17266. if (sipdebug) {
  17267. ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
  17268. }
  17269. }
  17270. transmit_response(p, "200 OK", req);
  17271. return;
  17272. } else if (!strcasecmp(c, "application/media_control+xml")) {
  17273. /* Eh, we'll just assume it's a fast picture update for now */
  17274. if (p->owner)
  17275. ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
  17276. transmit_response(p, "200 OK", req);
  17277. return;
  17278. } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
  17279. /* Client code (from SNOM phone) */
  17280. if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
  17281. if (p->owner && p->owner->cdr)
  17282. ast_cdr_setuserfield(p->owner, c);
  17283. if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
  17284. ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
  17285. transmit_response(p, "200 OK", req);
  17286. } else {
  17287. transmit_response(p, "403 Forbidden", req);
  17288. }
  17289. return;
  17290. } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
  17291. /* INFO messages generated by some phones to start/stop recording
  17292. on phone calls.
  17293. OEJ: I think this should be something that is enabled/disabled
  17294. per device. I don't want incoming callers to record calls in my
  17295. pbx.
  17296. */
  17297. struct ast_call_feature *feat;
  17298. int j;
  17299. struct ast_frame f = { AST_FRAME_DTMF, };
  17300. if (!p->owner) { /* not a PBX call */
  17301. transmit_response(p, "481 Call leg/transaction does not exist", req);
  17302. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  17303. return;
  17304. }
  17305. /* first, get the feature string, if it exists */
  17306. ast_rdlock_call_features();
  17307. feat = ast_find_call_feature("automon");
  17308. if (!feat || ast_strlen_zero(feat->exten)) {
  17309. ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
  17310. /* 403 means that we don't support this feature, so don't request it again */
  17311. transmit_response(p, "403 Forbidden", req);
  17312. ast_unlock_call_features();
  17313. return;
  17314. }
  17315. /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
  17316. f.len = 100;
  17317. for (j=0; j < strlen(feat->exten); j++) {
  17318. f.subclass.integer = feat->exten[j];
  17319. ast_queue_frame(p->owner, &f);
  17320. if (sipdebug)
  17321. ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
  17322. }
  17323. ast_unlock_call_features();
  17324. ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
  17325. transmit_response(p, "200 OK", req);
  17326. return;
  17327. } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
  17328. /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
  17329. transmit_response(p, "200 OK", req);
  17330. return;
  17331. }
  17332. /* Other type of INFO message, not really understood by Asterisk */
  17333. /* if (get_msg_text(buf, sizeof(buf), req)) { */
  17334. ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
  17335. transmit_response(p, "415 Unsupported media type", req);
  17336. return;
  17337. }
  17338. /*! \brief Enable SIP Debugging for a single IP */
  17339. static char *sip_do_debug_ip(int fd, const char *arg)
  17340. {
  17341. if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
  17342. return CLI_SHOWUSAGE;
  17343. }
  17344. ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
  17345. sipdebug |= sip_debug_console;
  17346. return CLI_SUCCESS;
  17347. }
  17348. /*! \brief Turn on SIP debugging for a given peer */
  17349. static char *sip_do_debug_peer(int fd, const char *arg)
  17350. {
  17351. struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
  17352. if (!peer)
  17353. ast_cli(fd, "No such peer '%s'\n", arg);
  17354. else if (ast_sockaddr_isnull(&peer->addr))
  17355. ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
  17356. else {
  17357. ast_sockaddr_copy(&debugaddr, &peer->addr);
  17358. ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
  17359. sipdebug |= sip_debug_console;
  17360. }
  17361. if (peer)
  17362. unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
  17363. return CLI_SUCCESS;
  17364. }
  17365. /*! \brief Turn on SIP debugging (CLI command) */
  17366. static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17367. {
  17368. int oldsipdebug = sipdebug & sip_debug_console;
  17369. const char *what;
  17370. if (cmd == CLI_INIT) {
  17371. e->command = "sip set debug {on|off|ip|peer}";
  17372. e->usage =
  17373. "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
  17374. " Globally disables dumping of SIP packets,\n"
  17375. " or enables it either globally or for a (single)\n"
  17376. " IP address or registered peer.\n";
  17377. return NULL;
  17378. } else if (cmd == CLI_GENERATE) {
  17379. if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
  17380. return complete_sip_peer(a->word, a->n, 0);
  17381. return NULL;
  17382. }
  17383. what = a->argv[e->args-1]; /* guaranteed to exist */
  17384. if (a->argc == e->args) { /* on/off */
  17385. if (!strcasecmp(what, "on")) {
  17386. sipdebug |= sip_debug_console;
  17387. sipdebug_text = 1; /*! \note this can be a special debug command - "sip debug text" or something */
  17388. memset(&debugaddr, 0, sizeof(debugaddr));
  17389. ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
  17390. return CLI_SUCCESS;
  17391. } else if (!strcasecmp(what, "off")) {
  17392. sipdebug &= ~sip_debug_console;
  17393. sipdebug_text = 0;
  17394. ast_cli(a->fd, "SIP Debugging Disabled\n");
  17395. return CLI_SUCCESS;
  17396. }
  17397. } else if (a->argc == e->args +1) {/* ip/peer */
  17398. if (!strcasecmp(what, "ip"))
  17399. return sip_do_debug_ip(a->fd, a->argv[e->args]);
  17400. else if (!strcasecmp(what, "peer"))
  17401. return sip_do_debug_peer(a->fd, a->argv[e->args]);
  17402. }
  17403. return CLI_SHOWUSAGE; /* default, failure */
  17404. }
  17405. /*! \brief Cli command to send SIP notify to peer */
  17406. static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17407. {
  17408. struct ast_variable *varlist;
  17409. int i;
  17410. switch (cmd) {
  17411. case CLI_INIT:
  17412. e->command = "sip notify";
  17413. e->usage =
  17414. "Usage: sip notify <type> <peer> [<peer>...]\n"
  17415. " Send a NOTIFY message to a SIP peer or peers\n"
  17416. " Message types are defined in sip_notify.conf\n";
  17417. return NULL;
  17418. case CLI_GENERATE:
  17419. return complete_sipnotify(a->line, a->word, a->pos, a->n);
  17420. }
  17421. if (a->argc < 4)
  17422. return CLI_SHOWUSAGE;
  17423. if (!notify_types) {
  17424. ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
  17425. return CLI_FAILURE;
  17426. }
  17427. varlist = ast_variable_browse(notify_types, a->argv[2]);
  17428. if (!varlist) {
  17429. ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
  17430. return CLI_FAILURE;
  17431. }
  17432. for (i = 3; i < a->argc; i++) {
  17433. struct sip_pvt *p;
  17434. char buf[512];
  17435. struct ast_variable *header, *var;
  17436. if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
  17437. ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
  17438. return CLI_FAILURE;
  17439. }
  17440. if (create_addr(p, a->argv[i], NULL, 1)) {
  17441. /* Maybe they're not registered, etc. */
  17442. dialog_unlink_all(p);
  17443. dialog_unref(p, "unref dialog inside for loop" );
  17444. /* sip_destroy(p); */
  17445. ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
  17446. continue;
  17447. }
  17448. /* Notify is outgoing call */
  17449. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  17450. sip_notify_allocate(p);
  17451. p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
  17452. for (var = varlist; var; var = var->next) {
  17453. ast_copy_string(buf, var->value, sizeof(buf));
  17454. ast_unescape_semicolon(buf);
  17455. if (!strcasecmp(var->name, "Content")) {
  17456. if (ast_str_strlen(p->notify->content))
  17457. ast_str_append(&p->notify->content, 0, "\r\n");
  17458. ast_str_append(&p->notify->content, 0, "%s", buf);
  17459. } else if (!strcasecmp(var->name, "Content-Length")) {
  17460. ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
  17461. } else {
  17462. header->next = ast_variable_new(var->name, buf, "");
  17463. header = header->next;
  17464. }
  17465. }
  17466. /* Now that we have the peer's address, set our ip and change callid */
  17467. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  17468. build_via(p);
  17469. change_callid_pvt(p, NULL);
  17470. ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
  17471. sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
  17472. transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
  17473. dialog_unref(p, "bump down the count of p since we're done with it.");
  17474. }
  17475. return CLI_SUCCESS;
  17476. }
  17477. /*! \brief Enable/Disable SIP History logging (CLI) */
  17478. static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  17479. {
  17480. switch (cmd) {
  17481. case CLI_INIT:
  17482. e->command = "sip set history {on|off}";
  17483. e->usage =
  17484. "Usage: sip set history {on|off}\n"
  17485. " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
  17486. " Use 'sip show history' to view the history of a call number.\n";
  17487. return NULL;
  17488. case CLI_GENERATE:
  17489. return NULL;
  17490. }
  17491. if (a->argc != e->args)
  17492. return CLI_SHOWUSAGE;
  17493. if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
  17494. recordhistory = TRUE;
  17495. ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
  17496. } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
  17497. recordhistory = FALSE;
  17498. ast_cli(a->fd, "SIP History Recording Disabled\n");
  17499. } else {
  17500. return CLI_SHOWUSAGE;
  17501. }
  17502. return CLI_SUCCESS;
  17503. }
  17504. /*! \brief Authenticate for outbound registration */
  17505. static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
  17506. {
  17507. char *header, *respheader;
  17508. char digest[1024];
  17509. p->authtries++;
  17510. auth_headers(code, &header, &respheader);
  17511. memset(digest, 0, sizeof(digest));
  17512. if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
  17513. /* There's nothing to use for authentication */
  17514. /* No digest challenge in request */
  17515. if (sip_debug_test_pvt(p) && p->registry)
  17516. ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
  17517. /* No old challenge */
  17518. return -1;
  17519. }
  17520. if (p->do_history)
  17521. append_history(p, "RegistryAuth", "Try: %d", p->authtries);
  17522. if (sip_debug_test_pvt(p) && p->registry)
  17523. ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
  17524. return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
  17525. }
  17526. /*! \brief Add authentication on outbound SIP packet */
  17527. static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
  17528. {
  17529. char *header, *respheader;
  17530. char digest[1024];
  17531. if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
  17532. return -2;
  17533. p->authtries++;
  17534. auth_headers(code, &header, &respheader);
  17535. ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
  17536. memset(digest, 0, sizeof(digest));
  17537. if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
  17538. /* No way to authenticate */
  17539. return -1;
  17540. }
  17541. /* Now we have a reply digest */
  17542. p->options->auth = digest;
  17543. p->options->authheader = respheader;
  17544. return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
  17545. }
  17546. /*! \brief reply to authentication for outbound registrations
  17547. \return Returns -1 if we have no auth
  17548. \note This is used for register= servers in sip.conf, SIP proxies we register
  17549. with for receiving calls from. */
  17550. static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
  17551. {
  17552. char tmp[512];
  17553. char *c;
  17554. char oldnonce[256];
  17555. /* table of recognised keywords, and places where they should be copied */
  17556. const struct x {
  17557. const char *key;
  17558. const ast_string_field *field;
  17559. } *i, keys[] = {
  17560. { "realm=", &p->realm },
  17561. { "nonce=", &p->nonce },
  17562. { "opaque=", &p->opaque },
  17563. { "qop=", &p->qop },
  17564. { "domain=", &p->domain },
  17565. { NULL, 0 },
  17566. };
  17567. ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
  17568. if (ast_strlen_zero(tmp))
  17569. return -1;
  17570. if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
  17571. ast_log(LOG_WARNING, "missing Digest.\n");
  17572. return -1;
  17573. }
  17574. c = tmp + strlen("Digest ");
  17575. ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
  17576. while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
  17577. for (i = keys; i->key != NULL; i++) {
  17578. char *src, *separator;
  17579. if (strncasecmp(c, i->key, strlen(i->key)) != 0)
  17580. continue;
  17581. /* Found. Skip keyword, take text in quotes or up to the separator. */
  17582. c += strlen(i->key);
  17583. if (*c == '"') {
  17584. src = ++c;
  17585. separator = "\"";
  17586. } else {
  17587. src = c;
  17588. separator = ",";
  17589. }
  17590. strsep(&c, separator); /* clear separator and move ptr */
  17591. ast_string_field_ptr_set(p, i->field, src);
  17592. break;
  17593. }
  17594. if (i->key == NULL) /* not found, try ',' */
  17595. strsep(&c, ",");
  17596. }
  17597. /* Reset nonce count */
  17598. if (strcmp(p->nonce, oldnonce))
  17599. p->noncecount = 0;
  17600. /* Save auth data for following registrations */
  17601. if (p->registry) {
  17602. struct sip_registry *r = p->registry;
  17603. if (strcmp(r->nonce, p->nonce)) {
  17604. ast_string_field_set(r, realm, p->realm);
  17605. ast_string_field_set(r, nonce, p->nonce);
  17606. ast_string_field_set(r, authdomain, p->domain);
  17607. ast_string_field_set(r, opaque, p->opaque);
  17608. ast_string_field_set(r, qop, p->qop);
  17609. r->noncecount = 0;
  17610. }
  17611. }
  17612. return build_reply_digest(p, sipmethod, digest, digest_len);
  17613. }
  17614. /*! \brief Build reply digest
  17615. \return Returns -1 if we have no auth
  17616. \note Build digest challenge for authentication of registrations and calls
  17617. Also used for authentication of BYE
  17618. */
  17619. static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
  17620. {
  17621. char a1[256];
  17622. char a2[256];
  17623. char a1_hash[256];
  17624. char a2_hash[256];
  17625. char resp[256];
  17626. char resp_hash[256];
  17627. char uri[256];
  17628. char opaque[256] = "";
  17629. char cnonce[80];
  17630. const char *username;
  17631. const char *secret;
  17632. const char *md5secret;
  17633. struct sip_auth *auth; /* Realm authentication credential */
  17634. struct sip_auth_container *credentials;
  17635. if (!ast_strlen_zero(p->domain))
  17636. snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
  17637. else if (!ast_strlen_zero(p->uri))
  17638. ast_copy_string(uri, p->uri, sizeof(uri));
  17639. else
  17640. snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
  17641. snprintf(cnonce, sizeof(cnonce), "%08lx", (unsigned long)ast_random());
  17642. /* Check if we have peer credentials */
  17643. ao2_lock(p);
  17644. credentials = p->peerauth;
  17645. if (credentials) {
  17646. ao2_t_ref(credentials, +1, "Ref peer auth for digest");
  17647. }
  17648. ao2_unlock(p);
  17649. auth = find_realm_authentication(credentials, p->realm);
  17650. if (!auth) {
  17651. /* If not, check global credentials */
  17652. if (credentials) {
  17653. ao2_t_ref(credentials, -1, "Unref peer auth for digest");
  17654. }
  17655. ast_mutex_lock(&authl_lock);
  17656. credentials = authl;
  17657. if (credentials) {
  17658. ao2_t_ref(credentials, +1, "Ref global auth for digest");
  17659. }
  17660. ast_mutex_unlock(&authl_lock);
  17661. auth = find_realm_authentication(credentials, p->realm);
  17662. }
  17663. if (auth) {
  17664. ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
  17665. username = auth->username;
  17666. secret = auth->secret;
  17667. md5secret = auth->md5secret;
  17668. if (sipdebug)
  17669. ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
  17670. } else {
  17671. /* No authentication, use peer or register= config */
  17672. username = p->authname;
  17673. secret = p->relatedpeer
  17674. && !ast_strlen_zero(p->relatedpeer->remotesecret)
  17675. ? p->relatedpeer->remotesecret : p->peersecret;
  17676. md5secret = p->peermd5secret;
  17677. }
  17678. if (ast_strlen_zero(username)) {
  17679. /* We have no authentication */
  17680. if (credentials) {
  17681. ao2_t_ref(credentials, -1, "Unref auth for digest");
  17682. }
  17683. return -1;
  17684. }
  17685. /* Calculate SIP digest response */
  17686. snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
  17687. snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
  17688. if (!ast_strlen_zero(md5secret))
  17689. ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
  17690. else
  17691. ast_md5_hash(a1_hash, a1);
  17692. ast_md5_hash(a2_hash, a2);
  17693. p->noncecount++;
  17694. if (!ast_strlen_zero(p->qop))
  17695. snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, (unsigned)p->noncecount, cnonce, "auth", a2_hash);
  17696. else
  17697. snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
  17698. ast_md5_hash(resp_hash, resp);
  17699. /* only include the opaque string if it's set */
  17700. if (!ast_strlen_zero(p->opaque)) {
  17701. snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
  17702. }
  17703. /* XXX We hard code our qop to "auth" for now. XXX */
  17704. if (!ast_strlen_zero(p->qop))
  17705. 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);
  17706. else
  17707. 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);
  17708. append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
  17709. if (credentials) {
  17710. ao2_t_ref(credentials, -1, "Unref auth for digest");
  17711. }
  17712. return 0;
  17713. }
  17714. /*! \brief Read SIP header (dialplan function) */
  17715. static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
  17716. {
  17717. struct sip_pvt *p;
  17718. const char *content = NULL;
  17719. AST_DECLARE_APP_ARGS(args,
  17720. AST_APP_ARG(header);
  17721. AST_APP_ARG(number);
  17722. );
  17723. int i, number, start = 0;
  17724. if (!chan) {
  17725. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", function);
  17726. return -1;
  17727. }
  17728. if (ast_strlen_zero(data)) {
  17729. ast_log(LOG_WARNING, "This function requires a header name.\n");
  17730. return -1;
  17731. }
  17732. ast_channel_lock(chan);
  17733. if (!IS_SIP_TECH(chan->tech)) {
  17734. ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
  17735. ast_channel_unlock(chan);
  17736. return -1;
  17737. }
  17738. AST_STANDARD_APP_ARGS(args, data);
  17739. if (!args.number) {
  17740. number = 1;
  17741. } else {
  17742. sscanf(args.number, "%30d", &number);
  17743. if (number < 1)
  17744. number = 1;
  17745. }
  17746. p = chan->tech_pvt;
  17747. /* If there is no private structure, this channel is no longer alive */
  17748. if (!p) {
  17749. ast_channel_unlock(chan);
  17750. return -1;
  17751. }
  17752. for (i = 0; i < number; i++)
  17753. content = __get_header(&p->initreq, args.header, &start);
  17754. if (ast_strlen_zero(content)) {
  17755. ast_channel_unlock(chan);
  17756. return -1;
  17757. }
  17758. ast_copy_string(buf, content, len);
  17759. ast_channel_unlock(chan);
  17760. return 0;
  17761. }
  17762. static struct ast_custom_function sip_header_function = {
  17763. .name = "SIP_HEADER",
  17764. .read = func_header_read,
  17765. };
  17766. /*! \brief Dial plan function to check if domain is local */
  17767. static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  17768. {
  17769. if (ast_strlen_zero(data)) {
  17770. ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
  17771. return -1;
  17772. }
  17773. if (check_sip_domain(data, NULL, 0))
  17774. ast_copy_string(buf, data, len);
  17775. else
  17776. buf[0] = '\0';
  17777. return 0;
  17778. }
  17779. static struct ast_custom_function checksipdomain_function = {
  17780. .name = "CHECKSIPDOMAIN",
  17781. .read = func_check_sipdomain,
  17782. };
  17783. /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
  17784. static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  17785. {
  17786. struct sip_peer *peer;
  17787. char *colname;
  17788. if ((colname = strchr(data, ':'))) { /*! \todo Will be deprecated after 1.4 */
  17789. static int deprecation_warning = 0;
  17790. *colname++ = '\0';
  17791. if (deprecation_warning++ % 10 == 0)
  17792. ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
  17793. } else if ((colname = strchr(data, ',')))
  17794. *colname++ = '\0';
  17795. else
  17796. colname = "ip";
  17797. if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
  17798. return -1;
  17799. if (!strcasecmp(colname, "ip")) {
  17800. ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
  17801. } else if (!strcasecmp(colname, "port")) {
  17802. snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
  17803. } else if (!strcasecmp(colname, "status")) {
  17804. peer_status(peer, buf, len);
  17805. } else if (!strcasecmp(colname, "language")) {
  17806. ast_copy_string(buf, peer->language, len);
  17807. } else if (!strcasecmp(colname, "regexten")) {
  17808. ast_copy_string(buf, peer->regexten, len);
  17809. } else if (!strcasecmp(colname, "limit")) {
  17810. snprintf(buf, len, "%d", peer->call_limit);
  17811. } else if (!strcasecmp(colname, "busylevel")) {
  17812. snprintf(buf, len, "%d", peer->busy_level);
  17813. } else if (!strcasecmp(colname, "curcalls")) {
  17814. snprintf(buf, len, "%d", peer->inUse);
  17815. } else if (!strcasecmp(colname, "maxforwards")) {
  17816. snprintf(buf, len, "%d", peer->maxforwards);
  17817. } else if (!strcasecmp(colname, "accountcode")) {
  17818. ast_copy_string(buf, peer->accountcode, len);
  17819. } else if (!strcasecmp(colname, "callgroup")) {
  17820. ast_print_group(buf, len, peer->callgroup);
  17821. } else if (!strcasecmp(colname, "pickupgroup")) {
  17822. ast_print_group(buf, len, peer->pickupgroup);
  17823. } else if (!strcasecmp(colname, "useragent")) {
  17824. ast_copy_string(buf, peer->useragent, len);
  17825. } else if (!strcasecmp(colname, "mailbox")) {
  17826. struct ast_str *mailbox_str = ast_str_alloca(512);
  17827. peer_mailboxes_to_str(&mailbox_str, peer);
  17828. ast_copy_string(buf, ast_str_buffer(mailbox_str), len);
  17829. } else if (!strcasecmp(colname, "context")) {
  17830. ast_copy_string(buf, peer->context, len);
  17831. } else if (!strcasecmp(colname, "expire")) {
  17832. snprintf(buf, len, "%d", peer->expire);
  17833. } else if (!strcasecmp(colname, "dynamic")) {
  17834. ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
  17835. } else if (!strcasecmp(colname, "callerid_name")) {
  17836. ast_copy_string(buf, peer->cid_name, len);
  17837. } else if (!strcasecmp(colname, "callerid_num")) {
  17838. ast_copy_string(buf, peer->cid_num, len);
  17839. } else if (!strcasecmp(colname, "codecs")) {
  17840. ast_getformatname_multiple(buf, len -1, peer->capability);
  17841. } else if (!strcasecmp(colname, "encryption")) {
  17842. snprintf(buf, len, "%u", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
  17843. } else if (!strncasecmp(colname, "chanvar[", 8)) {
  17844. char *chanvar=colname + 8;
  17845. struct ast_variable *v;
  17846. chanvar = strsep(&chanvar, "]");
  17847. for (v = peer->chanvars ; v ; v = v->next) {
  17848. if (!strcasecmp(v->name, chanvar)) {
  17849. ast_copy_string(buf, v->value, len);
  17850. }
  17851. }
  17852. } else if (!strncasecmp(colname, "codec[", 6)) {
  17853. char *codecnum;
  17854. format_t codec = 0;
  17855. codecnum = colname + 6; /* move past the '[' */
  17856. codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
  17857. if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
  17858. ast_copy_string(buf, ast_getformatname(codec), len);
  17859. } else {
  17860. buf[0] = '\0';
  17861. }
  17862. } else {
  17863. buf[0] = '\0';
  17864. }
  17865. unref_peer(peer, "unref_peer from function_sippeer, just before return");
  17866. return 0;
  17867. }
  17868. /*! \brief Structure to declare a dialplan function: SIPPEER */
  17869. static struct ast_custom_function sippeer_function = {
  17870. .name = "SIPPEER",
  17871. .read = function_sippeer,
  17872. };
  17873. /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
  17874. static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  17875. {
  17876. struct sip_pvt *p;
  17877. static int deprecated = 0;
  17878. *buf = 0;
  17879. if (!chan) {
  17880. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
  17881. return -1;
  17882. }
  17883. if (!data) {
  17884. ast_log(LOG_WARNING, "This function requires a parameter name.\n");
  17885. return -1;
  17886. }
  17887. ast_channel_lock(chan);
  17888. if (!IS_SIP_TECH(chan->tech)) {
  17889. ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
  17890. ast_channel_unlock(chan);
  17891. return -1;
  17892. }
  17893. if (deprecated++ % 20 == 0) {
  17894. /* Deprecated in 1.6.1 */
  17895. ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
  17896. }
  17897. p = chan->tech_pvt;
  17898. /* If there is no private structure, this channel is no longer alive */
  17899. if (!p) {
  17900. ast_channel_unlock(chan);
  17901. return -1;
  17902. }
  17903. if (!strcasecmp(data, "peerip")) {
  17904. ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
  17905. } else if (!strcasecmp(data, "recvip")) {
  17906. ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
  17907. } else if (!strcasecmp(data, "from")) {
  17908. ast_copy_string(buf, p->from, len);
  17909. } else if (!strcasecmp(data, "uri")) {
  17910. ast_copy_string(buf, p->uri, len);
  17911. } else if (!strcasecmp(data, "useragent")) {
  17912. ast_copy_string(buf, p->useragent, len);
  17913. } else if (!strcasecmp(data, "peername")) {
  17914. ast_copy_string(buf, p->peername, len);
  17915. } else if (!strcasecmp(data, "t38passthrough")) {
  17916. if (p->t38.state == T38_DISABLED) {
  17917. ast_copy_string(buf, "0", len);
  17918. } else { /* T38 is offered or enabled in this call */
  17919. ast_copy_string(buf, "1", len);
  17920. }
  17921. } else {
  17922. ast_channel_unlock(chan);
  17923. return -1;
  17924. }
  17925. ast_channel_unlock(chan);
  17926. return 0;
  17927. }
  17928. /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
  17929. static struct ast_custom_function sipchaninfo_function = {
  17930. .name = "SIPCHANINFO",
  17931. .read = function_sipchaninfo_read,
  17932. };
  17933. /*! \brief update redirecting information for a channel based on headers
  17934. *
  17935. */
  17936. static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
  17937. struct ast_party_redirecting *redirecting,
  17938. struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
  17939. {
  17940. char *redirecting_from_name = NULL;
  17941. char *redirecting_from_number = NULL;
  17942. char *redirecting_to_name = NULL;
  17943. char *redirecting_to_number = NULL;
  17944. int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
  17945. int is_response = req->method == SIP_RESPONSE;
  17946. int res = 0;
  17947. res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
  17948. if (res == -1) {
  17949. if (is_response) {
  17950. get_name_and_number(get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
  17951. } else {
  17952. return;
  17953. }
  17954. }
  17955. /* At this point, all redirecting "from" info should be filled in appropriately
  17956. * on to the "to" info
  17957. */
  17958. if (is_response) {
  17959. parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
  17960. } else {
  17961. get_name_and_number(get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
  17962. }
  17963. if (!ast_strlen_zero(redirecting_from_number)) {
  17964. ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
  17965. update_redirecting->from.number = 1;
  17966. redirecting->from.number.valid = 1;
  17967. ast_free(redirecting->from.number.str);
  17968. redirecting->from.number.str = redirecting_from_number;
  17969. }
  17970. if (!ast_strlen_zero(redirecting_from_name)) {
  17971. ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
  17972. update_redirecting->from.name = 1;
  17973. redirecting->from.name.valid = 1;
  17974. ast_free(redirecting->from.name.str);
  17975. redirecting->from.name.str = redirecting_from_name;
  17976. }
  17977. if (!ast_strlen_zero(p->cid_tag)) {
  17978. ast_free(redirecting->from.tag);
  17979. redirecting->from.tag = ast_strdup(p->cid_tag);
  17980. ast_free(redirecting->to.tag);
  17981. redirecting->to.tag = ast_strdup(p->cid_tag);
  17982. }
  17983. if (!ast_strlen_zero(redirecting_to_number)) {
  17984. ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
  17985. update_redirecting->to.number = 1;
  17986. redirecting->to.number.valid = 1;
  17987. ast_free(redirecting->to.number.str);
  17988. redirecting->to.number.str = redirecting_to_number;
  17989. }
  17990. if (!ast_strlen_zero(redirecting_to_name)) {
  17991. ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
  17992. update_redirecting->to.name = 1;
  17993. redirecting->to.name.valid = 1;
  17994. ast_free(redirecting->to.name.str);
  17995. redirecting->to.name.str = redirecting_to_name;
  17996. }
  17997. redirecting->reason = reason;
  17998. }
  17999. /*! \brief Parse 302 Moved temporalily response
  18000. \todo XXX Doesn't redirect over TLS on sips: uri's.
  18001. If we get a redirect to a SIPS: uri, this needs to be going back to the
  18002. dialplan (this is a request for a secure signalling path).
  18003. Note that transport=tls is deprecated, but we need to support it on incoming requests.
  18004. */
  18005. static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
  18006. {
  18007. char contact[SIPBUFSIZE];
  18008. char *contact_name = NULL;
  18009. char *contact_number = NULL;
  18010. char *separator, *trans;
  18011. char *domain;
  18012. enum sip_transport transport = SIP_TRANSPORT_UDP;
  18013. ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
  18014. if ((separator = strchr(contact, ',')))
  18015. *separator = '\0';
  18016. contact_number = get_in_brackets(contact);
  18017. if ((trans = strcasestr(contact_number, ";transport="))) {
  18018. trans += 11;
  18019. if ((separator = strchr(trans, ';')))
  18020. *separator = '\0';
  18021. if (!strncasecmp(trans, "tcp", 3))
  18022. transport = SIP_TRANSPORT_TCP;
  18023. else if (!strncasecmp(trans, "tls", 3))
  18024. transport = SIP_TRANSPORT_TLS;
  18025. else {
  18026. if (strncasecmp(trans, "udp", 3))
  18027. ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
  18028. /* This will assume UDP for all unknown transports */
  18029. transport = SIP_TRANSPORT_UDP;
  18030. }
  18031. }
  18032. contact_number = remove_uri_parameters(contact_number);
  18033. if (p->socket.tcptls_session) {
  18034. ao2_ref(p->socket.tcptls_session, -1);
  18035. p->socket.tcptls_session = NULL;
  18036. }
  18037. set_socket_transport(&p->socket, transport);
  18038. if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
  18039. char *host = NULL;
  18040. if (!strncasecmp(contact_number, "sip:", 4))
  18041. contact_number += 4;
  18042. else if (!strncasecmp(contact_number, "sips:", 5))
  18043. contact_number += 5;
  18044. separator = strchr(contact_number, '/');
  18045. if (separator)
  18046. *separator = '\0';
  18047. if ((host = strchr(contact_number, '@'))) {
  18048. *host++ = '\0';
  18049. ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, get_transport(transport), host);
  18050. if (p->owner)
  18051. ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", contact_number, get_transport(transport), host);
  18052. } else {
  18053. ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), contact_number);
  18054. if (p->owner)
  18055. ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), contact_number);
  18056. }
  18057. } else {
  18058. separator = strchr(contact, '@');
  18059. if (separator) {
  18060. *separator++ = '\0';
  18061. domain = separator;
  18062. } else {
  18063. /* No username part */
  18064. domain = contact;
  18065. }
  18066. separator = strchr(contact, '/'); /* WHEN do we hae a forward slash in the URI? */
  18067. if (separator)
  18068. *separator = '\0';
  18069. if (!strncasecmp(contact_number, "sip:", 4))
  18070. contact_number += 4;
  18071. else if (!strncasecmp(contact_number, "sips:", 5))
  18072. contact_number += 5;
  18073. separator = strchr(contact_number, ';'); /* And username ; parameters? */
  18074. if (separator)
  18075. *separator = '\0';
  18076. ast_uri_decode(contact_number);
  18077. if (set_call_forward) {
  18078. ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
  18079. if (p->owner) {
  18080. pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
  18081. ast_string_field_set(p->owner, call_forward, contact_number);
  18082. }
  18083. }
  18084. }
  18085. /* We've gotten the number for the contact, now get the name */
  18086. if (*contact == '\"') {
  18087. contact_name = contact + 1;
  18088. if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
  18089. ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
  18090. }
  18091. *separator = '\0';
  18092. }
  18093. if (name && !ast_strlen_zero(contact_name)) {
  18094. *name = ast_strdup(contact_name);
  18095. }
  18096. if (number) {
  18097. *number = ast_strdup(contact_number);
  18098. }
  18099. }
  18100. /*! \brief Check pending actions on SIP call
  18101. *
  18102. * \note both sip_pvt and sip_pvt's owner channel (if present)
  18103. * must be locked for this function.
  18104. */
  18105. static void check_pendings(struct sip_pvt *p)
  18106. {
  18107. if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  18108. if (p->reinviteid > -1) {
  18109. /* Outstanding p->reinviteid timeout, so wait... */
  18110. return;
  18111. } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
  18112. /* if we can't BYE, then this is really a pending CANCEL */
  18113. p->invitestate = INV_CANCELLED;
  18114. transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
  18115. /* If the cancel occurred on an initial invite, cancel the pending BYE */
  18116. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
  18117. ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
  18118. }
  18119. /* Actually don't destroy us yet, wait for the 487 on our original
  18120. INVITE, but do set an autodestruct just in case we never get it. */
  18121. } else {
  18122. /* We have a pending outbound invite, don't send something
  18123. * new in-transaction, unless it is a pending reinvite, then
  18124. * by the time we are called here, we should probably just hang up. */
  18125. if (p->pendinginvite && !p->ongoing_reinvite)
  18126. return;
  18127. if (p->owner) {
  18128. ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
  18129. }
  18130. /* Perhaps there is an SD change INVITE outstanding */
  18131. transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
  18132. ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
  18133. }
  18134. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  18135. } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
  18136. /* if we can't REINVITE, hold it for later */
  18137. if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
  18138. ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
  18139. } else {
  18140. ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
  18141. /* Didn't get to reinvite yet, so do it now */
  18142. transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
  18143. ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
  18144. }
  18145. }
  18146. }
  18147. /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
  18148. to avoid race conditions between asterisk servers.
  18149. Called from the scheduler.
  18150. */
  18151. static int sip_reinvite_retry(const void *data)
  18152. {
  18153. struct sip_pvt *p = (struct sip_pvt *) data;
  18154. struct ast_channel *owner;
  18155. sip_pvt_lock(p); /* called from schedule thread which requires a lock */
  18156. while ((owner = p->owner) && ast_channel_trylock(owner)) {
  18157. sip_pvt_unlock(p);
  18158. usleep(1);
  18159. sip_pvt_lock(p);
  18160. }
  18161. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  18162. p->waitid = -1;
  18163. check_pendings(p);
  18164. sip_pvt_unlock(p);
  18165. if (owner) {
  18166. ast_channel_unlock(owner);
  18167. }
  18168. dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
  18169. return 0;
  18170. }
  18171. /*!
  18172. * \brief Handle authentication challenge for SIP UPDATE
  18173. *
  18174. * This function is only called upon the receipt of a 401/407 response to an UPDATE.
  18175. */
  18176. static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  18177. {
  18178. if (p->options) {
  18179. p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
  18180. }
  18181. if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
  18182. ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", get_header(&p->initreq, "From"));
  18183. }
  18184. }
  18185. static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
  18186. {
  18187. struct cc_epa_entry *cc_entry = epa_entry->instance_data;
  18188. struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
  18189. find_sip_monitor_instance_by_suspension_entry, epa_entry);
  18190. const char *min_expires;
  18191. if (!monitor_instance) {
  18192. ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
  18193. return;
  18194. }
  18195. if (resp != 423) {
  18196. ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
  18197. "Received error response to our PUBLISH");
  18198. ao2_ref(monitor_instance, -1);
  18199. return;
  18200. }
  18201. /* Allrighty, the other end doesn't like our Expires value. They think it's
  18202. * too small, so let's see if they've provided a more sensible value. If they
  18203. * haven't, then we'll just double our Expires value and see if they like that
  18204. * instead.
  18205. *
  18206. * XXX Ideally this logic could be placed into its own function so that SUBSCRIBE,
  18207. * PUBLISH, and REGISTER could all benefit from the same shared code.
  18208. */
  18209. min_expires = get_header(req, "Min-Expires");
  18210. if (ast_strlen_zero(min_expires)) {
  18211. pvt->expiry *= 2;
  18212. if (pvt->expiry < 0) {
  18213. /* You dork! You overflowed! */
  18214. ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
  18215. "PUBLISH expiry overflowed");
  18216. ao2_ref(monitor_instance, -1);
  18217. return;
  18218. }
  18219. } else if (sscanf(min_expires, "%d", &pvt->expiry) != 1) {
  18220. ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
  18221. "Min-Expires has non-numeric value");
  18222. ao2_ref(monitor_instance, -1);
  18223. return;
  18224. }
  18225. /* At this point, we have most certainly changed pvt->expiry, so try transmitting
  18226. * again
  18227. */
  18228. transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
  18229. ao2_ref(monitor_instance, -1);
  18230. }
  18231. static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  18232. {
  18233. struct sip_epa_entry *epa_entry = p->epa_entry;
  18234. const char *etag = get_header(req, "Sip-ETag");
  18235. ast_assert(epa_entry != NULL);
  18236. if (resp == 401 || resp == 407) {
  18237. ast_string_field_set(p, theirtag, NULL);
  18238. if (p->options) {
  18239. p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
  18240. }
  18241. if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
  18242. ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", get_header(&p->initreq, "From"));
  18243. pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
  18244. sip_alreadygone(p);
  18245. }
  18246. return;
  18247. }
  18248. if (resp == 501 || resp == 405) {
  18249. mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
  18250. }
  18251. if (resp == 200) {
  18252. p->authtries = 0;
  18253. /* If I've read section 6, item 6 of RFC 3903 correctly,
  18254. * an ESC will only generate a new etag when it sends a 200 OK
  18255. */
  18256. if (!ast_strlen_zero(etag)) {
  18257. ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
  18258. }
  18259. /* The nominal case. Everything went well. Everybody is happy.
  18260. * Each EPA will have a specific action to take as a result of this
  18261. * development, so ... callbacks!
  18262. */
  18263. if (epa_entry->static_data->handle_ok) {
  18264. epa_entry->static_data->handle_ok(p, req, epa_entry);
  18265. }
  18266. } else {
  18267. /* Rather than try to make individual callbacks for each error
  18268. * type, there is just a single error callback. The callback
  18269. * can distinguish between error messages and do what it needs to
  18270. */
  18271. if (epa_entry->static_data->handle_error) {
  18272. epa_entry->static_data->handle_error(p, resp, req, epa_entry);
  18273. }
  18274. }
  18275. }
  18276. /*!
  18277. * \internal
  18278. * \brief Set hangup source and cause.
  18279. *
  18280. * \param p SIP private.
  18281. * \param cause Hangup cause to queue. Zero if no cause.
  18282. *
  18283. * \pre p and p->owner are locked.
  18284. *
  18285. * \return Nothing
  18286. */
  18287. static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
  18288. {
  18289. struct ast_channel *owner = p->owner;
  18290. const char *name = ast_strdupa(owner->name);
  18291. /* Cannot hold any channel/private locks when calling. */
  18292. ast_channel_ref(owner);
  18293. ast_channel_unlock(owner);
  18294. sip_pvt_unlock(p);
  18295. ast_set_hangupsource(owner, name, 0);
  18296. if (cause) {
  18297. ast_queue_hangup_with_cause(owner, cause);
  18298. } else {
  18299. ast_queue_hangup(owner);
  18300. }
  18301. ast_channel_unref(owner);
  18302. /* Relock things. */
  18303. owner = sip_pvt_lock_full(p);
  18304. if (owner) {
  18305. ast_channel_unref(owner);
  18306. }
  18307. }
  18308. /*! \brief Handle SIP response to INVITE dialogue */
  18309. static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  18310. {
  18311. int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
  18312. int res = 0;
  18313. int xmitres = 0;
  18314. int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  18315. char *p_hdrval;
  18316. int rtn;
  18317. struct ast_party_connected_line connected;
  18318. struct ast_set_party_connected_line update_connected;
  18319. if (reinvite)
  18320. ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
  18321. else
  18322. ast_debug(4, "SIP response %d to standard invite\n", resp);
  18323. if (p->alreadygone) { /* This call is already gone */
  18324. ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
  18325. return;
  18326. }
  18327. /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
  18328. /* Don't auto congest anymore since we've gotten something useful back */
  18329. 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"));
  18330. /* RFC3261 says we must treat every 1xx response (but not 100)
  18331. that we don't recognize as if it was 183.
  18332. */
  18333. if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183)
  18334. resp = 183;
  18335. /* Any response between 100 and 199 is PROCEEDING */
  18336. if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
  18337. p->invitestate = INV_PROCEEDING;
  18338. /* Final response, not 200 ? */
  18339. if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
  18340. p->invitestate = INV_COMPLETED;
  18341. if ((resp >= 200 && reinvite)) {
  18342. p->ongoing_reinvite = 0;
  18343. if (p->reinviteid > -1) {
  18344. AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
  18345. }
  18346. }
  18347. /* Final response, clear out pending invite */
  18348. if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
  18349. p->pendinginvite = 0;
  18350. }
  18351. /* If this is a response to our initial INVITE, we need to set what we can use
  18352. * for this peer.
  18353. */
  18354. if (!reinvite) {
  18355. set_pvt_allowed_methods(p, req);
  18356. }
  18357. switch (resp) {
  18358. case 100: /* Trying */
  18359. case 101: /* Dialog establishment */
  18360. if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
  18361. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  18362. check_pendings(p);
  18363. break;
  18364. case 180: /* 180 Ringing */
  18365. case 182: /* 182 Queued */
  18366. if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
  18367. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  18368. /* Store Route-set from provisional SIP responses so
  18369. * early-dialog request can be routed properly
  18370. * */
  18371. parse_ok_contact(p, req);
  18372. if (!reinvite) {
  18373. build_route(p, req, 1, resp);
  18374. }
  18375. if (!req->ignore && p->owner) {
  18376. if (get_rpid(p, req)) {
  18377. /* Queue a connected line update */
  18378. ast_party_connected_line_init(&connected);
  18379. memset(&update_connected, 0, sizeof(update_connected));
  18380. update_connected.id.number = 1;
  18381. connected.id.number.valid = 1;
  18382. connected.id.number.str = (char *) p->cid_num;
  18383. connected.id.number.presentation = p->callingpres;
  18384. update_connected.id.name = 1;
  18385. connected.id.name.valid = 1;
  18386. connected.id.name.str = (char *) p->cid_name;
  18387. connected.id.name.presentation = p->callingpres;
  18388. connected.id.tag = (char *) p->cid_tag;
  18389. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  18390. ast_channel_queue_connected_line_update(p->owner, &connected,
  18391. &update_connected);
  18392. }
  18393. sip_handle_cc(p, req, AST_CC_CCNR);
  18394. ast_queue_control(p->owner, AST_CONTROL_RINGING);
  18395. if (p->owner->_state != AST_STATE_UP) {
  18396. ast_setstate(p->owner, AST_STATE_RINGING);
  18397. }
  18398. }
  18399. if (find_sdp(req)) {
  18400. if (p->invitestate != INV_CANCELLED)
  18401. p->invitestate = INV_EARLY_MEDIA;
  18402. res = process_sdp(p, req, SDP_T38_NONE);
  18403. if (!req->ignore && p->owner) {
  18404. /* Queue a progress frame only if we have SDP in 180 or 182 */
  18405. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  18406. }
  18407. ast_rtp_instance_activate(p->rtp);
  18408. }
  18409. check_pendings(p);
  18410. break;
  18411. case 181: /* Call Is Being Forwarded */
  18412. if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
  18413. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  18414. /* Store Route-set from provisional SIP responses so
  18415. * early-dialog request can be routed properly
  18416. * */
  18417. parse_ok_contact(p, req);
  18418. if (!reinvite) {
  18419. build_route(p, req, 1, resp);
  18420. }
  18421. if (!req->ignore && p->owner) {
  18422. struct ast_party_redirecting redirecting;
  18423. struct ast_set_party_redirecting update_redirecting;
  18424. ast_party_redirecting_init(&redirecting);
  18425. memset(&update_redirecting, 0, sizeof(update_redirecting));
  18426. change_redirecting_information(p, req, &redirecting, &update_redirecting,
  18427. FALSE);
  18428. ast_channel_queue_redirecting_update(p->owner, &redirecting,
  18429. &update_redirecting);
  18430. ast_party_redirecting_free(&redirecting);
  18431. sip_handle_cc(p, req, AST_CC_CCNR);
  18432. }
  18433. check_pendings(p);
  18434. break;
  18435. case 183: /* Session progress */
  18436. if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
  18437. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  18438. /* Store Route-set from provisional SIP responses so
  18439. * early-dialog request can be routed properly
  18440. * */
  18441. parse_ok_contact(p, req);
  18442. if (!reinvite) {
  18443. build_route(p, req, 1, resp);
  18444. }
  18445. if (!req->ignore && p->owner) {
  18446. if (get_rpid(p, req)) {
  18447. /* Queue a connected line update */
  18448. ast_party_connected_line_init(&connected);
  18449. memset(&update_connected, 0, sizeof(update_connected));
  18450. update_connected.id.number = 1;
  18451. connected.id.number.valid = 1;
  18452. connected.id.number.str = (char *) p->cid_num;
  18453. connected.id.number.presentation = p->callingpres;
  18454. update_connected.id.name = 1;
  18455. connected.id.name.valid = 1;
  18456. connected.id.name.str = (char *) p->cid_name;
  18457. connected.id.name.presentation = p->callingpres;
  18458. connected.id.tag = (char *) p->cid_tag;
  18459. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  18460. ast_channel_queue_connected_line_update(p->owner, &connected,
  18461. &update_connected);
  18462. }
  18463. sip_handle_cc(p, req, AST_CC_CCNR);
  18464. }
  18465. if (find_sdp(req)) {
  18466. if (p->invitestate != INV_CANCELLED)
  18467. p->invitestate = INV_EARLY_MEDIA;
  18468. res = process_sdp(p, req, SDP_T38_NONE);
  18469. if (!req->ignore && p->owner) {
  18470. /* Queue a progress frame */
  18471. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  18472. }
  18473. ast_rtp_instance_activate(p->rtp);
  18474. } else {
  18475. /* Alcatel PBXs are known to send 183s with no SDP after sending
  18476. * a 100 Trying response. We're just going to treat this sort of thing
  18477. * the same as we would treat a 180 Ringing
  18478. */
  18479. if (!req->ignore && p->owner) {
  18480. ast_queue_control(p->owner, AST_CONTROL_RINGING);
  18481. }
  18482. }
  18483. check_pendings(p);
  18484. break;
  18485. case 200: /* 200 OK on invite - someone's answering our call */
  18486. if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
  18487. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  18488. p->authtries = 0;
  18489. if (find_sdp(req)) {
  18490. if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore) {
  18491. if (!reinvite) {
  18492. /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
  18493. /* For re-invites, we try to recover */
  18494. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  18495. p->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  18496. if (p->owner) {
  18497. p->owner->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  18498. sip_queue_hangup_cause(p, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  18499. }
  18500. }
  18501. }
  18502. ast_rtp_instance_activate(p->rtp);
  18503. } else if (!reinvite) {
  18504. struct ast_sockaddr remote_address = {{0,}};
  18505. ast_rtp_instance_get_remote_address(p->rtp, &remote_address);
  18506. if (ast_sockaddr_isnull(&remote_address) || (!ast_strlen_zero(p->theirprovtag) && strcmp(p->theirtag, p->theirprovtag))) {
  18507. ast_log(LOG_WARNING, "Received response: \"200 OK\" from '%s' without SDP\n", p->relatedpeer->name);
  18508. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  18509. ast_rtp_instance_activate(p->rtp);
  18510. }
  18511. }
  18512. if (!req->ignore && p->owner) {
  18513. int rpid_changed;
  18514. rpid_changed = get_rpid(p, req);
  18515. if (rpid_changed || !reinvite) {
  18516. /* Queue a connected line update */
  18517. ast_party_connected_line_init(&connected);
  18518. memset(&update_connected, 0, sizeof(update_connected));
  18519. if (rpid_changed
  18520. || !ast_strlen_zero(p->cid_num)
  18521. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  18522. update_connected.id.number = 1;
  18523. connected.id.number.valid = 1;
  18524. connected.id.number.str = (char *) p->cid_num;
  18525. connected.id.number.presentation = p->callingpres;
  18526. }
  18527. if (rpid_changed
  18528. || !ast_strlen_zero(p->cid_name)
  18529. || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
  18530. update_connected.id.name = 1;
  18531. connected.id.name.valid = 1;
  18532. connected.id.name.str = (char *) p->cid_name;
  18533. connected.id.name.presentation = p->callingpres;
  18534. }
  18535. if (update_connected.id.number || update_connected.id.name) {
  18536. connected.id.tag = (char *) p->cid_tag;
  18537. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  18538. ast_channel_queue_connected_line_update(p->owner, &connected,
  18539. &update_connected);
  18540. }
  18541. }
  18542. }
  18543. /* Parse contact header for continued conversation */
  18544. /* When we get 200 OK, we know which device (and IP) to contact for this call */
  18545. /* This is important when we have a SIP proxy between us and the phone */
  18546. if (outgoing) {
  18547. update_call_counter(p, DEC_CALL_RINGING);
  18548. parse_ok_contact(p, req);
  18549. /* Save Record-Route for any later requests we make on this dialogue */
  18550. if (!reinvite) {
  18551. build_route(p, req, 1, resp);
  18552. }
  18553. if(set_address_from_contact(p)) {
  18554. /* Bad contact - we don't know how to reach this device */
  18555. /* We need to ACK, but then send a bye */
  18556. if (!p->route && !req->ignore)
  18557. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  18558. }
  18559. }
  18560. if (!req->ignore && p->owner) {
  18561. if (!reinvite && !res) {
  18562. ast_queue_control(p->owner, AST_CONTROL_ANSWER);
  18563. if (sip_cfg.callevents)
  18564. manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
  18565. "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
  18566. p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
  18567. } else { /* RE-invite */
  18568. if (p->t38.state == T38_DISABLED) {
  18569. ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
  18570. } else {
  18571. ast_queue_frame(p->owner, &ast_null_frame);
  18572. }
  18573. }
  18574. } else {
  18575. /* It's possible we're getting an 200 OK after we've tried to disconnect
  18576. by sending CANCEL */
  18577. /* First send ACK, then send bye */
  18578. if (!req->ignore)
  18579. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  18580. }
  18581. /* Check for Session-Timers related headers */
  18582. if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE) {
  18583. p_hdrval = (char*)get_header(req, "Session-Expires");
  18584. if (!ast_strlen_zero(p_hdrval)) {
  18585. /* UAS supports Session-Timers */
  18586. enum st_refresher_param st_ref_param;
  18587. int tmp_st_interval = 0;
  18588. rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
  18589. if (rtn != 0) {
  18590. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  18591. } else if (tmp_st_interval < st_get_se(p, FALSE)) {
  18592. ast_log(LOG_WARNING, "Got Session-Expires less than local Min-SE in 200 OK, tearing down call\n");
  18593. ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
  18594. }
  18595. if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
  18596. p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
  18597. } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
  18598. p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
  18599. } else {
  18600. ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
  18601. }
  18602. if (tmp_st_interval) {
  18603. p->stimer->st_interval = tmp_st_interval;
  18604. }
  18605. p->stimer->st_active = TRUE;
  18606. p->stimer->st_active_peer_ua = TRUE;
  18607. start_session_timer(p);
  18608. } else {
  18609. /* UAS doesn't support Session-Timers */
  18610. if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
  18611. p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
  18612. p->stimer->st_active_peer_ua = FALSE;
  18613. start_session_timer(p);
  18614. }
  18615. }
  18616. }
  18617. /* If I understand this right, the branch is different for a non-200 ACK only */
  18618. p->invitestate = INV_TERMINATED;
  18619. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  18620. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
  18621. check_pendings(p);
  18622. break;
  18623. case 407: /* Proxy authentication */
  18624. case 401: /* Www auth */
  18625. /* First we ACK */
  18626. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  18627. if (p->options)
  18628. p->options->auth_type = resp;
  18629. /* Then we AUTH */
  18630. ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
  18631. if (!req->ignore) {
  18632. if (p->authtries < MAX_AUTHTRIES)
  18633. p->invitestate = INV_CALLING;
  18634. if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
  18635. ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
  18636. pvt_set_needdestroy(p, "failed to authenticate on INVITE");
  18637. sip_alreadygone(p);
  18638. if (p->owner)
  18639. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  18640. }
  18641. }
  18642. break;
  18643. case 403: /* Forbidden */
  18644. /* First we ACK */
  18645. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  18646. ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
  18647. if (!req->ignore && p->owner) {
  18648. sip_queue_hangup_cause(p, hangup_sip2cause(resp));
  18649. }
  18650. break;
  18651. case 414: /* Bad request URI */
  18652. case 493: /* Undecipherable */
  18653. case 404: /* Not found */
  18654. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  18655. if (p->owner && !req->ignore) {
  18656. sip_queue_hangup_cause(p, hangup_sip2cause(resp));
  18657. }
  18658. break;
  18659. case 481: /* Call leg does not exist */
  18660. /* Could be REFER caused INVITE with replaces */
  18661. ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
  18662. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  18663. if (p->owner) {
  18664. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  18665. }
  18666. break;
  18667. case 422: /* Session-Timers: Session interval too small */
  18668. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  18669. ast_string_field_set(p, theirtag, NULL);
  18670. proc_422_rsp(p, req);
  18671. break;
  18672. case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
  18673. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  18674. append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
  18675. ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
  18676. if (p->owner && !req->ignore) {
  18677. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  18678. }
  18679. break;
  18680. case 487: /* Cancelled transaction */
  18681. /* We have sent CANCEL on an outbound INVITE
  18682. This transaction is already scheduled to be killed by sip_hangup().
  18683. */
  18684. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  18685. if (p->owner && !req->ignore) {
  18686. ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
  18687. append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
  18688. } else if (!req->ignore) {
  18689. update_call_counter(p, DEC_CALL_LIMIT);
  18690. append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
  18691. }
  18692. check_pendings(p);
  18693. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  18694. break;
  18695. case 415: /* Unsupported media type */
  18696. case 488: /* Not acceptable here */
  18697. case 606: /* Not Acceptable */
  18698. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  18699. if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
  18700. change_t38_state(p, T38_DISABLED);
  18701. /* Try to reset RTP timers */
  18702. //ast_rtp_set_rtptimers_onhold(p->rtp);
  18703. /* Trigger a reinvite back to audio */
  18704. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  18705. } else {
  18706. /* We can't set up this call, so give up */
  18707. if (p->owner && !req->ignore) {
  18708. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  18709. }
  18710. }
  18711. break;
  18712. case 491: /* Pending */
  18713. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  18714. if (p->owner && !req->ignore) {
  18715. if (p->owner->_state != AST_STATE_UP) {
  18716. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  18717. } else {
  18718. /* This is a re-invite that failed. */
  18719. /* Reset the flag after a while
  18720. */
  18721. int wait;
  18722. /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
  18723. * if not owner of call, wait 0 to 2 seconds */
  18724. if (p->outgoing_call) {
  18725. wait = 2100 + ast_random() % 2000;
  18726. } else {
  18727. wait = ast_random() % 2000;
  18728. }
  18729. 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."));
  18730. ast_debug(2, "Reinvite race. Scheduled sip_reinvite_retry in %d secs in handle_response_invite (waitid %d, dialog '%s')\n",
  18731. wait, p->waitid, p->callid);
  18732. }
  18733. }
  18734. break;
  18735. case 408: /* Request timeout */
  18736. case 405: /* Not allowed */
  18737. case 501: /* Not implemented */
  18738. xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  18739. if (p->owner) {
  18740. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  18741. }
  18742. break;
  18743. }
  18744. if (xmitres == XMIT_ERROR)
  18745. ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
  18746. }
  18747. /* \brief Handle SIP response in NOTIFY transaction
  18748. We've sent a NOTIFY, now handle responses to it
  18749. */
  18750. static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  18751. {
  18752. switch (resp) {
  18753. case 200: /* Notify accepted */
  18754. /* They got the notify, this is the end */
  18755. if (p->owner) {
  18756. if (p->refer) {
  18757. ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
  18758. } else {
  18759. ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
  18760. }
  18761. } else {
  18762. if (p->subscribed == NONE && !p->refer) {
  18763. ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
  18764. pvt_set_needdestroy(p, "received 200 response");
  18765. }
  18766. if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
  18767. /* Ready to send the next state we have on queue */
  18768. ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
  18769. cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
  18770. }
  18771. }
  18772. break;
  18773. case 401: /* Not www-authorized on SIP method */
  18774. case 407: /* Proxy auth */
  18775. if (!p->notify) {
  18776. break; /* Only device notify can use NOTIFY auth */
  18777. }
  18778. ast_string_field_set(p, theirtag, NULL);
  18779. if (ast_strlen_zero(p->authname)) {
  18780. 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));
  18781. pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
  18782. }
  18783. if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
  18784. ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
  18785. pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
  18786. }
  18787. break;
  18788. case 481: /* Call leg does not exist */
  18789. pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
  18790. break;
  18791. }
  18792. }
  18793. /* \brief Handle SIP response in SUBSCRIBE transaction */
  18794. static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  18795. {
  18796. if (p->subscribed == CALL_COMPLETION) {
  18797. struct sip_monitor_instance *monitor_instance;
  18798. if (resp < 300) {
  18799. return;
  18800. }
  18801. /* Final failure response received. */
  18802. monitor_instance = ao2_callback(sip_monitor_instances, 0,
  18803. find_sip_monitor_instance_by_subscription_pvt, p);
  18804. if (monitor_instance) {
  18805. ast_cc_monitor_failed(monitor_instance->core_id,
  18806. monitor_instance->device_name,
  18807. "Received error response to our SUBSCRIBE");
  18808. }
  18809. return;
  18810. }
  18811. if (p->subscribed != MWI_NOTIFICATION) {
  18812. return;
  18813. }
  18814. if (!p->mwi) {
  18815. return;
  18816. }
  18817. switch (resp) {
  18818. case 200: /* Subscription accepted */
  18819. ast_debug(3, "Got 200 OK on subscription for MWI\n");
  18820. set_pvt_allowed_methods(p, req);
  18821. if (p->options) {
  18822. if (p->options->outboundproxy) {
  18823. ao2_ref(p->options->outboundproxy, -1);
  18824. }
  18825. ast_free(p->options);
  18826. p->options = NULL;
  18827. }
  18828. p->mwi->subscribed = 1;
  18829. if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
  18830. ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
  18831. }
  18832. break;
  18833. case 401:
  18834. case 407:
  18835. ast_string_field_set(p, theirtag, NULL);
  18836. if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
  18837. ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
  18838. p->mwi->call = NULL;
  18839. ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
  18840. pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
  18841. }
  18842. break;
  18843. case 403:
  18844. transmit_response_with_date(p, "200 OK", req);
  18845. ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
  18846. p->mwi->call = NULL;
  18847. ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
  18848. pvt_set_needdestroy(p, "received 403 response");
  18849. sip_alreadygone(p);
  18850. break;
  18851. case 404:
  18852. ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
  18853. p->mwi->call = NULL;
  18854. ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
  18855. pvt_set_needdestroy(p, "received 404 response");
  18856. break;
  18857. case 481:
  18858. ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
  18859. p->mwi->call = NULL;
  18860. ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
  18861. pvt_set_needdestroy(p, "received 481 response");
  18862. break;
  18863. case 400: /* Bad Request */
  18864. case 414: /* Request URI too long */
  18865. case 493: /* Undecipherable */
  18866. case 500:
  18867. case 501:
  18868. ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
  18869. p->mwi->call = NULL;
  18870. ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
  18871. pvt_set_needdestroy(p, "received serious error (500/501/493/414/400) response");
  18872. break;
  18873. }
  18874. }
  18875. /* \brief Handle SIP response in REFER transaction
  18876. We've sent a REFER, now handle responses to it
  18877. */
  18878. static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  18879. {
  18880. enum ast_control_transfer message = AST_TRANSFER_FAILED;
  18881. /* If no refer structure exists, then do nothing */
  18882. if (!p->refer)
  18883. return;
  18884. switch (resp) {
  18885. case 202: /* Transfer accepted */
  18886. /* We need to do something here */
  18887. /* The transferee is now sending INVITE to target */
  18888. p->refer->status = REFER_ACCEPTED;
  18889. /* Now wait for next message */
  18890. ast_debug(3, "Got 202 accepted on transfer\n");
  18891. /* We should hang along, waiting for NOTIFY's here */
  18892. break;
  18893. case 401: /* Not www-authorized on SIP method */
  18894. case 407: /* Proxy auth */
  18895. if (ast_strlen_zero(p->authname)) {
  18896. ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
  18897. ast_sockaddr_stringify(&p->recv));
  18898. if (p->owner) {
  18899. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  18900. }
  18901. pvt_set_needdestroy(p, "unable to authenticate REFER");
  18902. }
  18903. if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
  18904. ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
  18905. p->refer->status = REFER_NOAUTH;
  18906. if (p->owner) {
  18907. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  18908. }
  18909. pvt_set_needdestroy(p, "failed to authenticate REFER");
  18910. }
  18911. break;
  18912. case 405: /* Method not allowed */
  18913. /* Return to the current call onhold */
  18914. /* Status flag needed to be reset */
  18915. ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
  18916. pvt_set_needdestroy(p, "received 405 response");
  18917. p->refer->status = REFER_FAILED;
  18918. if (p->owner) {
  18919. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  18920. }
  18921. break;
  18922. case 481: /* Call leg does not exist */
  18923. /* A transfer with Replaces did not work */
  18924. /* OEJ: We should Set flag, cancel the REFER, go back
  18925. to original call - but right now we can't */
  18926. ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
  18927. if (p->owner)
  18928. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  18929. pvt_set_needdestroy(p, "received 481 response");
  18930. break;
  18931. case 500: /* Server error */
  18932. case 501: /* Method not implemented */
  18933. /* Return to the current call onhold */
  18934. /* Status flag needed to be reset */
  18935. ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
  18936. pvt_set_needdestroy(p, "received 500/501 response");
  18937. p->refer->status = REFER_FAILED;
  18938. if (p->owner) {
  18939. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  18940. }
  18941. break;
  18942. case 603: /* Transfer declined */
  18943. ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
  18944. p->refer->status = REFER_FAILED;
  18945. pvt_set_needdestroy(p, "received 603 response");
  18946. if (p->owner) {
  18947. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  18948. }
  18949. break;
  18950. default:
  18951. /* We should treat unrecognized 9xx as 900. 400 is actually
  18952. specified as a possible response, but any 4-6xx is
  18953. theoretically possible. */
  18954. if (resp < 299) { /* 1xx cases don't get here */
  18955. ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
  18956. } else {
  18957. ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
  18958. }
  18959. p->refer->status = REFER_FAILED;
  18960. pvt_set_needdestroy(p, "received failure response");
  18961. if (p->owner) {
  18962. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  18963. }
  18964. break;
  18965. }
  18966. }
  18967. /*! \brief Handle responses on REGISTER to services */
  18968. static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  18969. {
  18970. int expires, expires_ms;
  18971. struct sip_registry *r;
  18972. r=p->registry;
  18973. switch (resp) {
  18974. case 401: /* Unauthorized */
  18975. if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
  18976. ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
  18977. pvt_set_needdestroy(p, "failed to authenticate REGISTER");
  18978. }
  18979. break;
  18980. case 403: /* Forbidden */
  18981. if (global_reg_retry_403) {
  18982. ast_log(LOG_NOTICE, "Treating 403 response to REGISTER as non-fatal for %s@%s\n",
  18983. p->registry->username, p->registry->hostname);
  18984. ast_string_field_set(r, nonce, "");
  18985. ast_string_field_set(p, nonce, "");
  18986. break;
  18987. }
  18988. ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
  18989. AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
  18990. r->regstate = REG_STATE_NOAUTH;
  18991. pvt_set_needdestroy(p, "received 403 response");
  18992. break;
  18993. case 404: /* Not found */
  18994. ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
  18995. pvt_set_needdestroy(p, "received 404 response");
  18996. if (r->call)
  18997. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
  18998. r->regstate = REG_STATE_REJECTED;
  18999. AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
  19000. break;
  19001. case 407: /* Proxy auth */
  19002. if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
  19003. ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
  19004. pvt_set_needdestroy(p, "failed to authenticate REGISTER");
  19005. }
  19006. break;
  19007. case 408: /* Request timeout */
  19008. /* Got a timeout response, so reset the counter of failed responses */
  19009. if (r) {
  19010. r->regattempts = 0;
  19011. } else {
  19012. ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
  19013. }
  19014. break;
  19015. case 423: /* Interval too brief */
  19016. r->expiry = atoi(get_header(req, "Min-Expires"));
  19017. 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);
  19018. AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
  19019. if (r->call) {
  19020. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
  19021. pvt_set_needdestroy(p, "received 423 response");
  19022. }
  19023. if (r->expiry > max_expiry) {
  19024. ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
  19025. r->expiry = r->configured_expiry;
  19026. r->regstate = REG_STATE_REJECTED;
  19027. } else {
  19028. r->regstate = REG_STATE_UNREGISTERED;
  19029. transmit_register(r, SIP_REGISTER, NULL, NULL);
  19030. }
  19031. manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
  19032. break;
  19033. case 400: /* Bad request */
  19034. case 414: /* Request URI too long */
  19035. case 493: /* Undecipherable */
  19036. case 479: /* Kamailio/OpenSIPS: Not able to process the URI - address is wrong in register*/
  19037. ast_log(LOG_WARNING, "Got error %d on register to %s@%s, giving up (check config)\n", resp, p->registry->username, p->registry->hostname);
  19038. pvt_set_needdestroy(p, "received 4xx response");
  19039. if (r->call)
  19040. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 4xx");
  19041. r->regstate = REG_STATE_REJECTED;
  19042. AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
  19043. break;
  19044. case 200: /* 200 OK */
  19045. if (!r) {
  19046. 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));
  19047. pvt_set_needdestroy(p, "received erroneous 200 response");
  19048. return 0;
  19049. }
  19050. r->regstate = REG_STATE_REGISTERED;
  19051. r->regtime = ast_tvnow(); /* Reset time of last successful registration */
  19052. manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
  19053. r->regattempts = 0;
  19054. ast_debug(1, "Registration successful\n");
  19055. if (r->timeout > -1) {
  19056. ast_debug(1, "Cancelling timeout %d\n", r->timeout);
  19057. }
  19058. AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
  19059. if (r->call)
  19060. r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
  19061. p->registry = registry_unref(p->registry, "unref registry entry p->registry");
  19062. /* destroy dialog now to avoid interference with next register */
  19063. pvt_set_needdestroy(p, "Registration successfull");
  19064. /* set us up for re-registering
  19065. * figure out how long we got registered for
  19066. * according to section 6.13 of RFC, contact headers override
  19067. * expires headers, so check those first */
  19068. expires = 0;
  19069. /* XXX todo: try to save the extra call */
  19070. if (!ast_strlen_zero(get_header(req, "Contact"))) {
  19071. const char *contact = NULL;
  19072. const char *tmptmp = NULL;
  19073. int start = 0;
  19074. for(;;) {
  19075. contact = __get_header(req, "Contact", &start);
  19076. /* this loop ensures we get a contact header about our register request */
  19077. if(!ast_strlen_zero(contact)) {
  19078. if( (tmptmp=strstr(contact, p->our_contact))) {
  19079. contact=tmptmp;
  19080. break;
  19081. }
  19082. } else
  19083. break;
  19084. }
  19085. tmptmp = strcasestr(contact, "expires=");
  19086. if (tmptmp) {
  19087. if (sscanf(tmptmp + 8, "%30d", &expires) != 1) {
  19088. expires = 0;
  19089. }
  19090. }
  19091. }
  19092. if (!expires)
  19093. expires=atoi(get_header(req, "expires"));
  19094. if (!expires)
  19095. expires=default_expiry;
  19096. expires_ms = expires * 1000;
  19097. if (expires <= EXPIRY_GUARD_LIMIT)
  19098. expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
  19099. else
  19100. expires_ms -= EXPIRY_GUARD_SECS * 1000;
  19101. if (sipdebug)
  19102. ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
  19103. r->refresh= (int) expires_ms / 1000;
  19104. /* Schedule re-registration before we expire */
  19105. AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
  19106. registry_unref(_data,"unref in REPLACE del fail"),
  19107. registry_unref(r,"unref in REPLACE add fail"),
  19108. registry_addref(r,"The Addition side of REPLACE"));
  19109. }
  19110. return 1;
  19111. }
  19112. /*! \brief Handle qualification responses (OPTIONS) */
  19113. static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
  19114. {
  19115. struct sip_peer *peer = /* ref_peer( */ p->relatedpeer /* , "bump refcount on p, as it is being used in this function(handle_response_peerpoke)")*/ ; /* hope this is already refcounted! */
  19116. int statechanged, is_reachable, was_reachable;
  19117. int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
  19118. /*
  19119. * Compute the response time to a ping (goes in peer->lastms.)
  19120. * -1 means did not respond, 0 means unknown,
  19121. * 1..maxms is a valid response, >maxms means late response.
  19122. */
  19123. if (pingtime < 1) { /* zero = unknown, so round up to 1 */
  19124. pingtime = 1;
  19125. }
  19126. if (!peer->maxms) { /* this should never happens */
  19127. pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
  19128. return;
  19129. }
  19130. /* Now determine new state and whether it has changed.
  19131. * Use some helper variables to simplify the writing
  19132. * of the expressions.
  19133. */
  19134. was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
  19135. is_reachable = pingtime <= peer->maxms;
  19136. statechanged = peer->lastms == 0 /* yes, unknown before */
  19137. || was_reachable != is_reachable;
  19138. peer->lastms = pingtime;
  19139. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  19140. if (statechanged) {
  19141. const char *s = is_reachable ? "Reachable" : "Lagged";
  19142. char str_lastms[20];
  19143. snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
  19144. ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
  19145. peer->name, s, pingtime, peer->maxms);
  19146. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  19147. if (sip_cfg.peer_rtupdate) {
  19148. ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
  19149. }
  19150. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
  19151. "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
  19152. peer->name, s, pingtime);
  19153. if (is_reachable && sip_cfg.regextenonqualify)
  19154. register_peer_exten(peer, TRUE);
  19155. }
  19156. pvt_set_needdestroy(p, "got OPTIONS response");
  19157. /* Try again eventually */
  19158. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
  19159. is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
  19160. sip_poke_peer_s, peer,
  19161. unref_peer(_data, "removing poke peer ref"),
  19162. unref_peer(peer, "removing poke peer ref"),
  19163. ref_peer(peer, "adding poke peer ref"));
  19164. }
  19165. /*!
  19166. * \internal
  19167. * \brief Handle responses to INFO messages
  19168. *
  19169. * \note The INFO method MUST NOT change the state of calls or
  19170. * related sessions (RFC 2976).
  19171. */
  19172. static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  19173. {
  19174. int sipmethod = SIP_INFO;
  19175. switch (resp) {
  19176. case 401: /* Not www-authorized on SIP method */
  19177. case 407: /* Proxy auth required */
  19178. ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
  19179. ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
  19180. break;
  19181. case 405: /* Method not allowed */
  19182. case 501: /* Not Implemented */
  19183. mark_method_unallowed(&p->allowed_methods, sipmethod);
  19184. if (p->relatedpeer) {
  19185. mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
  19186. }
  19187. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
  19188. ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
  19189. break;
  19190. default:
  19191. if (300 <= resp && resp < 700) {
  19192. ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
  19193. sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
  19194. }
  19195. break;
  19196. }
  19197. }
  19198. /*!
  19199. * \internal
  19200. * \brief Handle responses to MESSAGE messages
  19201. *
  19202. * \note The MESSAGE method should not change the state of calls
  19203. * or related sessions if associated with a dialog. (Implied by
  19204. * RFC 3428 Section 2).
  19205. */
  19206. static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  19207. {
  19208. int sipmethod = SIP_MESSAGE;
  19209. /* Out-of-dialog MESSAGE currently not supported. */
  19210. //int in_dialog = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  19211. switch (resp) {
  19212. case 401: /* Not www-authorized on SIP method */
  19213. case 407: /* Proxy auth required */
  19214. ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
  19215. ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
  19216. break;
  19217. case 405: /* Method not allowed */
  19218. case 501: /* Not Implemented */
  19219. mark_method_unallowed(&p->allowed_methods, sipmethod);
  19220. if (p->relatedpeer) {
  19221. mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
  19222. }
  19223. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
  19224. ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
  19225. break;
  19226. default:
  19227. if (100 <= resp && resp < 200) {
  19228. /* Must allow provisional responses for out-of-dialog requests. */
  19229. } else if (200 <= resp && resp < 300) {
  19230. p->authtries = 0; /* Reset authentication counter */
  19231. } else if (300 <= resp && resp < 700) {
  19232. ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
  19233. sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
  19234. }
  19235. break;
  19236. }
  19237. }
  19238. /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
  19239. static void stop_media_flows(struct sip_pvt *p)
  19240. {
  19241. /* Immediately stop RTP, VRTP and UDPTL as applicable */
  19242. if (p->rtp)
  19243. ast_rtp_instance_stop(p->rtp);
  19244. if (p->vrtp)
  19245. ast_rtp_instance_stop(p->vrtp);
  19246. if (p->trtp)
  19247. ast_rtp_instance_stop(p->trtp);
  19248. if (p->udptl)
  19249. ast_udptl_stop(p->udptl);
  19250. }
  19251. /*! \brief Handle SIP response in dialogue
  19252. \note only called by handle_incoming */
  19253. static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
  19254. {
  19255. struct ast_channel *owner;
  19256. int sipmethod;
  19257. const char *c = get_header(req, "Cseq");
  19258. /* 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 */
  19259. char *c_copy = ast_strdupa(c);
  19260. /* Skip the Cseq and its subsequent spaces */
  19261. const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
  19262. if (!msg)
  19263. msg = "";
  19264. sipmethod = find_sip_method(msg);
  19265. owner = p->owner;
  19266. if (owner) {
  19267. const char *rp = NULL, *rh = NULL;
  19268. owner->hangupcause = 0;
  19269. if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = get_header(req, "Reason"))) {
  19270. rh = ast_skip_blanks(rh);
  19271. if (!strncasecmp(rh, "Q.850", 5)) {
  19272. rp = strstr(rh, "cause=");
  19273. if (rp && sscanf(rp + 6, "%30d", &owner->hangupcause) == 1) {
  19274. owner->hangupcause &= 0x7f;
  19275. if (req->debug)
  19276. ast_verbose("Using Reason header for cause code: %d\n", owner->hangupcause);
  19277. }
  19278. }
  19279. }
  19280. if (!owner->hangupcause)
  19281. owner->hangupcause = hangup_sip2cause(resp);
  19282. }
  19283. if (p->socket.type == SIP_TRANSPORT_UDP) {
  19284. int ack_res = FALSE;
  19285. /* Acknowledge whatever it is destined for */
  19286. if ((resp >= 100) && (resp <= 199)) {
  19287. /* NON-INVITE messages do not ack a 1XX response. RFC 3261 section 17.1.2.2 */
  19288. if (sipmethod == SIP_INVITE) {
  19289. ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
  19290. }
  19291. } else {
  19292. ack_res = __sip_ack(p, seqno, 0, sipmethod);
  19293. }
  19294. if (ack_res == FALSE) {
  19295. /* RFC 3261 13.2.2.4 and 17.1.1.2 - We must re-send ACKs to re-transmitted final responses */
  19296. if (sipmethod == SIP_INVITE && resp >= 200) {
  19297. transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
  19298. }
  19299. append_history(p, "Ignore", "Ignoring this retransmit\n");
  19300. return;
  19301. }
  19302. }
  19303. /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
  19304. if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
  19305. p->pendinginvite = 0;
  19306. }
  19307. /* Get their tag if we haven't already */
  19308. if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
  19309. char tag[128];
  19310. gettag(req, "To", tag, sizeof(tag));
  19311. ast_string_field_set(p, theirtag, tag);
  19312. } else {
  19313. /* Store theirtag to track for changes when 200 responses to invites are received without SDP */
  19314. ast_string_field_set(p, theirprovtag, p->theirtag);
  19315. }
  19316. /* This needs to be configurable on a channel/peer level,
  19317. not mandatory for all communication. Sadly enough, NAT implementations
  19318. are not so stable so we can always rely on these headers.
  19319. Temporarily disabled, while waiting for fix.
  19320. Fix assigned to Rizzo :-)
  19321. */
  19322. /* check_via_response(p, req); */
  19323. /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
  19324. * in response to a BYE, then we should end the current dialog
  19325. * and session. It is known that at least one phone manufacturer
  19326. * potentially will send a 404 in response to a BYE, so we'll be
  19327. * liberal in what we accept and end the dialog and session if we
  19328. * receive any of those responses to a BYE.
  19329. */
  19330. if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
  19331. pvt_set_needdestroy(p, "received 4XX response to a BYE");
  19332. return;
  19333. }
  19334. if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
  19335. /* We don't really care what the response is, just that it replied back.
  19336. Well, as long as it's not a 100 response... since we might
  19337. need to hang around for something more "definitive" */
  19338. if (resp != 100)
  19339. handle_response_peerpoke(p, resp, req);
  19340. } else if (sipmethod == SIP_REFER && resp >= 200) {
  19341. handle_response_refer(p, resp, rest, req, seqno);
  19342. } else if (sipmethod == SIP_PUBLISH) {
  19343. /* SIP PUBLISH transcends this morass of doodoo and instead
  19344. * we just always call the response handler. Good gravy!
  19345. */
  19346. handle_response_publish(p, resp, rest, req, seqno);
  19347. } else if (sipmethod == SIP_INFO) {
  19348. /* More good gravy! */
  19349. handle_response_info(p, resp, rest, req, seqno);
  19350. } else if (sipmethod == SIP_MESSAGE) {
  19351. /* More good gravy! */
  19352. handle_response_message(p, resp, rest, req, seqno);
  19353. } else if (sipmethod == SIP_NOTIFY) {
  19354. /* The gravy train continues to roll */
  19355. handle_response_notify(p, resp, rest, req, seqno);
  19356. } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  19357. switch(resp) {
  19358. case 100: /* 100 Trying */
  19359. case 101: /* 101 Dialog establishment */
  19360. case 183: /* 183 Session Progress */
  19361. case 180: /* 180 Ringing */
  19362. case 182: /* 182 Queued */
  19363. case 181: /* 181 Call Is Being Forwarded */
  19364. if (sipmethod == SIP_INVITE)
  19365. handle_response_invite(p, resp, rest, req, seqno);
  19366. break;
  19367. case 200: /* 200 OK */
  19368. p->authtries = 0; /* Reset authentication counter */
  19369. if (sipmethod == SIP_INVITE) {
  19370. handle_response_invite(p, resp, rest, req, seqno);
  19371. } else if (sipmethod == SIP_REGISTER) {
  19372. handle_response_register(p, resp, rest, req, seqno);
  19373. } else if (sipmethod == SIP_SUBSCRIBE) {
  19374. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  19375. handle_response_subscribe(p, resp, rest, req, seqno);
  19376. } else if (sipmethod == SIP_BYE) { /* Ok, we're ready to go */
  19377. pvt_set_needdestroy(p, "received 200 response");
  19378. ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  19379. }
  19380. break;
  19381. case 401: /* Not www-authorized on SIP method */
  19382. case 407: /* Proxy auth required */
  19383. if (sipmethod == SIP_INVITE)
  19384. handle_response_invite(p, resp, rest, req, seqno);
  19385. else if (sipmethod == SIP_SUBSCRIBE)
  19386. handle_response_subscribe(p, resp, rest, req, seqno);
  19387. else if (p->registry && sipmethod == SIP_REGISTER)
  19388. handle_response_register(p, resp, rest, req, seqno);
  19389. else if (sipmethod == SIP_UPDATE) {
  19390. handle_response_update(p, resp, rest, req, seqno);
  19391. } else if (sipmethod == SIP_BYE) {
  19392. if (p->options)
  19393. p->options->auth_type = resp;
  19394. if (ast_strlen_zero(p->authname)) {
  19395. ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
  19396. msg, ast_sockaddr_stringify(&p->recv));
  19397. pvt_set_needdestroy(p, "unable to authenticate BYE");
  19398. } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
  19399. ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
  19400. pvt_set_needdestroy(p, "failed to authenticate BYE");
  19401. }
  19402. } else {
  19403. ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
  19404. pvt_set_needdestroy(p, "received 407 response");
  19405. }
  19406. break;
  19407. case 403: /* Forbidden - we failed authentication */
  19408. if (sipmethod == SIP_INVITE)
  19409. handle_response_invite(p, resp, rest, req, seqno);
  19410. else if (sipmethod == SIP_SUBSCRIBE)
  19411. handle_response_subscribe(p, resp, rest, req, seqno);
  19412. else if (p->registry && sipmethod == SIP_REGISTER)
  19413. handle_response_register(p, resp, rest, req, seqno);
  19414. else {
  19415. ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
  19416. pvt_set_needdestroy(p, "received 403 response");
  19417. }
  19418. break;
  19419. case 400: /* Bad Request */
  19420. case 414: /* Request URI too long */
  19421. case 493: /* Undecipherable */
  19422. case 404: /* Not found */
  19423. if (p->registry && sipmethod == SIP_REGISTER)
  19424. handle_response_register(p, resp, rest, req, seqno);
  19425. else if (sipmethod == SIP_INVITE)
  19426. handle_response_invite(p, resp, rest, req, seqno);
  19427. else if (sipmethod == SIP_SUBSCRIBE)
  19428. handle_response_subscribe(p, resp, rest, req, seqno);
  19429. else if (owner)
  19430. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  19431. break;
  19432. case 423: /* Interval too brief */
  19433. if (sipmethod == SIP_REGISTER)
  19434. handle_response_register(p, resp, rest, req, seqno);
  19435. break;
  19436. case 408: /* Request timeout - terminate dialog */
  19437. if (sipmethod == SIP_INVITE)
  19438. handle_response_invite(p, resp, rest, req, seqno);
  19439. else if (sipmethod == SIP_REGISTER)
  19440. handle_response_register(p, resp, rest, req, seqno);
  19441. else if (sipmethod == SIP_BYE) {
  19442. pvt_set_needdestroy(p, "received 408 response");
  19443. ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
  19444. } else {
  19445. if (owner)
  19446. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  19447. pvt_set_needdestroy(p, "received 408 response");
  19448. }
  19449. break;
  19450. case 428:
  19451. case 422: /* Session-Timers: Session Interval Too Small */
  19452. if (sipmethod == SIP_INVITE) {
  19453. handle_response_invite(p, resp, rest, req, seqno);
  19454. }
  19455. break;
  19456. case 481: /* Call leg does not exist */
  19457. if (sipmethod == SIP_INVITE) {
  19458. handle_response_invite(p, resp, rest, req, seqno);
  19459. } else if (sipmethod == SIP_SUBSCRIBE) {
  19460. handle_response_subscribe(p, resp, rest, req, seqno);
  19461. } else if (sipmethod == SIP_BYE) {
  19462. /* The other side has no transaction to bye,
  19463. just assume it's all right then */
  19464. ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
  19465. } else if (sipmethod == SIP_CANCEL) {
  19466. /* The other side has no transaction to cancel,
  19467. just assume it's all right then */
  19468. ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
  19469. } else {
  19470. ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
  19471. /* Guessing that this is not an important request */
  19472. }
  19473. break;
  19474. case 487:
  19475. if (sipmethod == SIP_INVITE)
  19476. handle_response_invite(p, resp, rest, req, seqno);
  19477. break;
  19478. case 415: /* Unsupported media type */
  19479. case 488: /* Not acceptable here - codec error */
  19480. case 606: /* Not Acceptable */
  19481. if (sipmethod == SIP_INVITE)
  19482. handle_response_invite(p, resp, rest, req, seqno);
  19483. break;
  19484. case 491: /* Pending */
  19485. if (sipmethod == SIP_INVITE)
  19486. handle_response_invite(p, resp, rest, req, seqno);
  19487. else {
  19488. ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
  19489. pvt_set_needdestroy(p, "received 491 response");
  19490. }
  19491. break;
  19492. case 405: /* Method not allowed */
  19493. case 501: /* Not Implemented */
  19494. mark_method_unallowed(&p->allowed_methods, sipmethod);
  19495. if (p->relatedpeer) {
  19496. mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
  19497. }
  19498. if (sipmethod == SIP_INVITE)
  19499. handle_response_invite(p, resp, rest, req, seqno);
  19500. else
  19501. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
  19502. break;
  19503. default:
  19504. if ((resp >= 300) && (resp < 700)) {
  19505. /* Fatal response */
  19506. if ((resp != 487))
  19507. ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
  19508. if (sipmethod == SIP_INVITE)
  19509. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  19510. /* XXX Locking issues?? XXX */
  19511. switch(resp) {
  19512. case 300: /* Multiple Choices */
  19513. case 301: /* Moved permanently */
  19514. case 302: /* Moved temporarily */
  19515. case 305: /* Use Proxy */
  19516. if (p->owner) {
  19517. struct ast_party_redirecting redirecting;
  19518. struct ast_set_party_redirecting update_redirecting;
  19519. ast_party_redirecting_init(&redirecting);
  19520. memset(&update_redirecting, 0, sizeof(update_redirecting));
  19521. change_redirecting_information(p, req, &redirecting,
  19522. &update_redirecting, TRUE);
  19523. ast_channel_set_redirecting(p->owner, &redirecting,
  19524. &update_redirecting);
  19525. ast_party_redirecting_free(&redirecting);
  19526. }
  19527. /* Fall through */
  19528. case 486: /* Busy here */
  19529. case 600: /* Busy everywhere */
  19530. case 603: /* Decline */
  19531. if (p->owner) {
  19532. sip_handle_cc(p, req, AST_CC_CCBS);
  19533. ast_queue_control(p->owner, AST_CONTROL_BUSY);
  19534. }
  19535. break;
  19536. case 482: /* Loop Detected */
  19537. case 480: /* Temporarily Unavailable */
  19538. case 404: /* Not Found */
  19539. case 410: /* Gone */
  19540. case 400: /* Bad Request */
  19541. case 500: /* Server error */
  19542. if (sipmethod == SIP_SUBSCRIBE) {
  19543. handle_response_subscribe(p, resp, rest, req, seqno);
  19544. break;
  19545. }
  19546. /* Fall through */
  19547. case 502: /* Bad gateway */
  19548. case 503: /* Service Unavailable */
  19549. case 504: /* Server Timeout */
  19550. if (owner)
  19551. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  19552. break;
  19553. case 484: /* Address Incomplete */
  19554. if (owner && sipmethod != SIP_BYE) {
  19555. switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
  19556. case SIP_PAGE2_ALLOWOVERLAP_YES:
  19557. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  19558. break;
  19559. default:
  19560. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
  19561. break;
  19562. }
  19563. }
  19564. break;
  19565. default:
  19566. /* Send hangup */
  19567. if (owner && sipmethod != SIP_BYE)
  19568. ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
  19569. break;
  19570. }
  19571. /* ACK on invite */
  19572. if (sipmethod == SIP_INVITE)
  19573. transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
  19574. sip_alreadygone(p);
  19575. if (!p->owner) {
  19576. pvt_set_needdestroy(p, "transaction completed");
  19577. }
  19578. } else if ((resp >= 100) && (resp < 200)) {
  19579. if (sipmethod == SIP_INVITE) {
  19580. if (!req->ignore && sip_cancel_destroy(p))
  19581. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  19582. if (find_sdp(req))
  19583. process_sdp(p, req, SDP_T38_NONE);
  19584. if (p->owner) {
  19585. /* Queue a progress frame */
  19586. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  19587. }
  19588. }
  19589. } else
  19590. ast_log(LOG_NOTICE, "Don't know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_sockaddr_stringify(&p->sa));
  19591. }
  19592. } else {
  19593. /* Responses to OUTGOING SIP requests on INCOMING calls
  19594. get handled here. As well as out-of-call message responses */
  19595. if (req->debug)
  19596. ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
  19597. if (sipmethod == SIP_INVITE && resp == 200) {
  19598. /* Tags in early session is replaced by the tag in 200 OK, which is
  19599. the final reply to our INVITE */
  19600. char tag[128];
  19601. gettag(req, "To", tag, sizeof(tag));
  19602. ast_string_field_set(p, theirtag, tag);
  19603. }
  19604. switch(resp) {
  19605. case 200:
  19606. if (sipmethod == SIP_INVITE) {
  19607. handle_response_invite(p, resp, rest, req, seqno);
  19608. } else if (sipmethod == SIP_CANCEL) {
  19609. ast_debug(1, "Got 200 OK on CANCEL\n");
  19610. /* Wait for 487, then destroy */
  19611. } else if (sipmethod == SIP_BYE) {
  19612. pvt_set_needdestroy(p, "transaction completed");
  19613. }
  19614. break;
  19615. case 401: /* www-auth */
  19616. case 407:
  19617. if (sipmethod == SIP_INVITE)
  19618. handle_response_invite(p, resp, rest, req, seqno);
  19619. else if (sipmethod == SIP_BYE) {
  19620. if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
  19621. ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
  19622. pvt_set_needdestroy(p, "failed to authenticate BYE");
  19623. }
  19624. }
  19625. break;
  19626. case 481: /* Call leg does not exist */
  19627. if (sipmethod == SIP_INVITE) {
  19628. /* Re-invite failed */
  19629. handle_response_invite(p, resp, rest, req, seqno);
  19630. } else if (sipmethod == SIP_BYE) {
  19631. pvt_set_needdestroy(p, "received 481 response");
  19632. } else if (sipdebug) {
  19633. ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
  19634. }
  19635. break;
  19636. case 501: /* Not Implemented */
  19637. if (sipmethod == SIP_INVITE)
  19638. handle_response_invite(p, resp, rest, req, seqno);
  19639. break;
  19640. default: /* Errors without handlers */
  19641. if ((resp >= 100) && (resp < 200)) {
  19642. if (sipmethod == SIP_INVITE) { /* re-invite */
  19643. if (!req->ignore && sip_cancel_destroy(p))
  19644. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  19645. }
  19646. }
  19647. if ((resp >= 300) && (resp < 700)) {
  19648. if ((resp != 487))
  19649. ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
  19650. switch(resp) {
  19651. case 415: /* Unsupported media type */
  19652. case 488: /* Not acceptable here - codec error */
  19653. case 603: /* Decline */
  19654. case 500: /* Server error */
  19655. case 502: /* Bad gateway */
  19656. case 503: /* Service Unavailable */
  19657. case 504: /* Server timeout */
  19658. /* re-invite failed */
  19659. if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
  19660. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  19661. break;
  19662. }
  19663. }
  19664. break;
  19665. }
  19666. }
  19667. }
  19668. /*! \brief Park SIP call support function
  19669. Starts in a new thread, then parks the call
  19670. XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
  19671. audio can't be heard before hangup
  19672. */
  19673. static void *sip_park_thread(void *stuff)
  19674. {
  19675. struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
  19676. struct sip_pvt *transferer_pvt;
  19677. struct sip_dual *d;
  19678. int ext;
  19679. int res;
  19680. d = stuff;
  19681. transferee = d->chan1;
  19682. transferer = d->chan2;
  19683. transferer_pvt = transferer->tech_pvt;
  19684. ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
  19685. res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
  19686. #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
  19687. if (res) {
  19688. transmit_message_with_text(transferer_pvt, "Unable to park call.\n");
  19689. } else {
  19690. /* Then tell the transferer what happened */
  19691. sprintf(buf, "Call parked on extension '%d'", ext);
  19692. transmit_message_with_text(transferer_pvt, buf);
  19693. }
  19694. #endif
  19695. /* Any way back to the current call??? */
  19696. /* Transmit response to the REFER request */
  19697. ast_set_flag(&transferer_pvt->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  19698. if (!res) {
  19699. /* Transfer succeeded */
  19700. append_history(transferer_pvt, "SIPpark", "Parked call on %d", ext);
  19701. transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "200 OK", TRUE);
  19702. transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
  19703. ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
  19704. } else {
  19705. transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "503 Service Unavailable", TRUE);
  19706. append_history(transferer_pvt, "SIPpark", "Parking failed\n");
  19707. ast_log(AST_LOG_NOTICE, "SIP Call parked failed for %s\n", transferee->name);
  19708. ast_hangup(transferee);
  19709. }
  19710. ast_hangup(transferer);
  19711. deinit_req(&d->req);
  19712. ast_free(d->park_exten);
  19713. ast_free(d->park_context);
  19714. ast_free(d);
  19715. return NULL;
  19716. }
  19717. /*! DO NOT hold any locks while calling sip_park */
  19718. static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context)
  19719. {
  19720. struct sip_dual *d;
  19721. struct ast_channel *transferee, *transferer;
  19722. pthread_t th;
  19723. transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
  19724. transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "SIPPeer/%s", chan2->name);
  19725. d = ast_calloc(1, sizeof(*d));
  19726. if (!transferee || !transferer || !d) {
  19727. if (transferee) {
  19728. ast_hangup(transferee);
  19729. }
  19730. if (transferer) {
  19731. ast_hangup(transferer);
  19732. }
  19733. ast_free(d);
  19734. return -1;
  19735. }
  19736. d->park_exten = ast_strdup(park_exten);
  19737. d->park_context = ast_strdup(park_context);
  19738. if (!d->park_exten || !d->park_context) {
  19739. ast_hangup(transferee);
  19740. ast_hangup(transferer);
  19741. ast_free(d->park_exten);
  19742. ast_free(d->park_context);
  19743. ast_free(d);
  19744. return -1;
  19745. }
  19746. /* Make formats okay */
  19747. transferee->readformat = chan1->readformat;
  19748. transferee->writeformat = chan1->writeformat;
  19749. /* Prepare for taking over the channel */
  19750. if (ast_channel_masquerade(transferee, chan1)) {
  19751. ast_hangup(transferee);
  19752. ast_hangup(transferer);
  19753. ast_free(d->park_exten);
  19754. ast_free(d->park_context);
  19755. ast_free(d);
  19756. return -1;
  19757. }
  19758. /* Setup the extensions and such */
  19759. ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
  19760. ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
  19761. transferee->priority = chan1->priority;
  19762. ast_do_masquerade(transferee);
  19763. /* We make a clone of the peer channel too, so we can play
  19764. back the announcement */
  19765. /* Make formats okay */
  19766. transferer->readformat = chan2->readformat;
  19767. transferer->writeformat = chan2->writeformat;
  19768. ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
  19769. /* Prepare for taking over the channel */
  19770. if (ast_channel_masquerade(transferer, chan2)) {
  19771. ast_hangup(transferee);
  19772. ast_hangup(transferer);
  19773. ast_free(d->park_exten);
  19774. ast_free(d->park_context);
  19775. ast_free(d);
  19776. return -1;
  19777. }
  19778. /* Setup the extensions and such */
  19779. ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
  19780. ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
  19781. transferer->priority = chan2->priority;
  19782. ast_do_masquerade(transferer);
  19783. /* Save original request for followup */
  19784. copy_request(&d->req, req);
  19785. d->chan1 = transferee; /* Transferee */
  19786. d->chan2 = transferer; /* Transferer */
  19787. d->seqno = seqno;
  19788. if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
  19789. /* Could not start thread */
  19790. ast_hangup(transferer);
  19791. ast_hangup(transferee);
  19792. deinit_req(&d->req);
  19793. ast_free(d->park_exten);
  19794. ast_free(d->park_context);
  19795. ast_free(d); /* We don't need it anymore. If thread is created, d will be free'd
  19796. by sip_park_thread() */
  19797. return -1;
  19798. }
  19799. return 0;
  19800. }
  19801. /*! \brief SIP pickup support function
  19802. * Starts in a new thread, then pickup the call
  19803. */
  19804. static void *sip_pickup_thread(void *stuff)
  19805. {
  19806. struct ast_channel *chan;
  19807. chan = stuff;
  19808. if (ast_pickup_call(chan)) {
  19809. chan->hangupcause = AST_CAUSE_CALL_REJECTED;
  19810. } else {
  19811. chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
  19812. }
  19813. ast_hangup(chan);
  19814. ast_channel_unref(chan);
  19815. chan = NULL;
  19816. return NULL;
  19817. }
  19818. /*! \brief Pickup a call using the subsystem in features.c
  19819. * This is executed in a separate thread
  19820. */
  19821. static int sip_pickup(struct ast_channel *chan)
  19822. {
  19823. pthread_t threadid;
  19824. ast_channel_ref(chan);
  19825. if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
  19826. ast_debug(1, "Unable to start Group pickup thread on channel %s\n", chan->name);
  19827. ast_channel_unref(chan);
  19828. return -1;
  19829. }
  19830. ast_debug(1, "Started Group pickup thread on channel %s\n", chan->name);
  19831. return 0;
  19832. }
  19833. /*! \brief Turn off generator data
  19834. XXX Does this function belong in the SIP channel?
  19835. */
  19836. static void ast_quiet_chan(struct ast_channel *chan)
  19837. {
  19838. if (chan && chan->_state == AST_STATE_UP) {
  19839. if (ast_test_flag(chan, AST_FLAG_MOH))
  19840. ast_moh_stop(chan);
  19841. else if (chan->generatordata)
  19842. ast_deactivate_generator(chan);
  19843. }
  19844. }
  19845. /*! \brief Attempt transfer of SIP call
  19846. This fix for attended transfers on a local PBX */
  19847. static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
  19848. {
  19849. int res = 0;
  19850. struct ast_channel *peera = NULL,
  19851. *peerb = NULL,
  19852. *peerc = NULL,
  19853. *peerd = NULL;
  19854. /* We will try to connect the transferee with the target and hangup
  19855. all channels to the transferer */
  19856. ast_debug(4, "Sip transfer:--------------------\n");
  19857. if (transferer->chan1)
  19858. ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
  19859. else
  19860. ast_debug(4, "-- No transferer first channel - odd??? \n");
  19861. if (target->chan1)
  19862. ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
  19863. else
  19864. ast_debug(4, "-- No target first channel ---\n");
  19865. if (transferer->chan2)
  19866. ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
  19867. else
  19868. ast_debug(4, "-- No bridged call to transferee\n");
  19869. if (target->chan2)
  19870. ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
  19871. else
  19872. ast_debug(4, "-- No target second channel ---\n");
  19873. ast_debug(4, "-- END Sip transfer:--------------------\n");
  19874. if (transferer->chan2) { /* We have a bridge on the transferer's channel */
  19875. peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
  19876. peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
  19877. peerc = transferer->chan2; /* Asterisk to Transferee */
  19878. peerd = target->chan2; /* Asterisk to Target */
  19879. ast_debug(3, "SIP transfer: Four channels to handle\n");
  19880. } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
  19881. peera = target->chan1; /* Transferer to PBX -> target channel */
  19882. peerb = transferer->chan1; /* Transferer to IVR*/
  19883. peerc = target->chan2; /* Asterisk to Target */
  19884. peerd = transferer->chan2; /* Nothing */
  19885. ast_debug(3, "SIP transfer: Three channels to handle\n");
  19886. }
  19887. if (peera && peerb && peerc && (peerb != peerc)) {
  19888. ast_quiet_chan(peera); /* Stop generators */
  19889. /* no need to quiet peerb since it should be hungup after the
  19890. transfer and the masquerade needs to be able to see if MOH is
  19891. playing on it */
  19892. ast_quiet_chan(peerc);
  19893. if (peerd)
  19894. ast_quiet_chan(peerd);
  19895. ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
  19896. if (ast_channel_masquerade(peerb, peerc)) {
  19897. ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
  19898. res = -1;
  19899. } else
  19900. ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
  19901. return res;
  19902. } else {
  19903. ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
  19904. if (transferer->chan1)
  19905. ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
  19906. if (target->chan1)
  19907. ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
  19908. return -1;
  19909. }
  19910. return 0;
  19911. }
  19912. /*! \brief Get tag from packet
  19913. *
  19914. * \return Returns the pointer to the provided tag buffer,
  19915. * or NULL if the tag was not found.
  19916. */
  19917. static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
  19918. {
  19919. const char *thetag;
  19920. if (!tagbuf)
  19921. return NULL;
  19922. tagbuf[0] = '\0'; /* reset the buffer */
  19923. thetag = get_header(req, header);
  19924. thetag = strcasestr(thetag, ";tag=");
  19925. if (thetag) {
  19926. thetag += 5;
  19927. ast_copy_string(tagbuf, thetag, tagbufsize);
  19928. return strsep(&tagbuf, ";");
  19929. }
  19930. return NULL;
  19931. }
  19932. static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
  19933. {
  19934. struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
  19935. find_sip_monitor_instance_by_subscription_pvt, pvt);
  19936. const char *status = get_body(req, "cc-state", ':');
  19937. struct cc_epa_entry *cc_entry;
  19938. char *uri;
  19939. if (!monitor_instance) {
  19940. transmit_response(pvt, "400 Bad Request", req);
  19941. return -1;
  19942. }
  19943. if (ast_strlen_zero(status)) {
  19944. ao2_ref(monitor_instance, -1);
  19945. transmit_response(pvt, "400 Bad Request", req);
  19946. return -1;
  19947. }
  19948. if (!strcmp(status, "queued")) {
  19949. /* We've been told that we're queued. This is the endpoint's way of telling
  19950. * us that it has accepted our CC request. We need to alert the core of this
  19951. * development
  19952. */
  19953. ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
  19954. transmit_response(pvt, "200 OK", req);
  19955. ao2_ref(monitor_instance, -1);
  19956. return 0;
  19957. }
  19958. /* It's open! Yay! */
  19959. uri = get_body(req, "cc-URI", ':');
  19960. if (ast_strlen_zero(uri)) {
  19961. uri = get_in_brackets((char *)get_header(req, "From"));
  19962. }
  19963. ast_string_field_set(monitor_instance, notify_uri, uri);
  19964. if (monitor_instance->suspension_entry) {
  19965. cc_entry = monitor_instance->suspension_entry->instance_data;
  19966. if (cc_entry->current_state == CC_CLOSED) {
  19967. /* If we've created a suspension entry and the current state is closed, then that means
  19968. * we got a notice from the CC core earlier to suspend monitoring, but because this particular
  19969. * call leg had not yet notified us that it was ready for recall, it meant that we
  19970. * could not yet send a PUBLISH. Now, however, we can.
  19971. */
  19972. construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
  19973. sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
  19974. transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
  19975. } else {
  19976. ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
  19977. }
  19978. } else {
  19979. ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
  19980. }
  19981. ao2_ref(monitor_instance, -1);
  19982. transmit_response(pvt, "200 OK", req);
  19983. return 0;
  19984. }
  19985. /*! \brief Handle incoming notifications */
  19986. static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
  19987. {
  19988. /* This is mostly a skeleton for future improvements */
  19989. /* Mostly created to return proper answers on notifications on outbound REFER's */
  19990. int res = 0;
  19991. const char *event = get_header(req, "Event");
  19992. char *sep;
  19993. if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
  19994. *sep++ = '\0';
  19995. }
  19996. if (sipdebug)
  19997. ast_debug(2, "Got NOTIFY Event: %s\n", event);
  19998. if (!strcmp(event, "refer")) {
  19999. /* Save nesting depth for now, since there might be other events we will
  20000. support in the future */
  20001. /* Handle REFER notifications */
  20002. char buf[1024];
  20003. char *cmd, *code;
  20004. int respcode;
  20005. int success = TRUE;
  20006. /* EventID for each transfer... EventID is basically the REFER cseq
  20007. We are getting notifications on a call that we transferred
  20008. We should hangup when we are getting a 200 OK in a sipfrag
  20009. Check if we have an owner of this event */
  20010. /* Check the content type */
  20011. if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
  20012. /* We need a sipfrag */
  20013. transmit_response(p, "400 Bad request", req);
  20014. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20015. return -1;
  20016. }
  20017. /* Get the text of the attachment */
  20018. if (get_msg_text(buf, sizeof(buf), req)) {
  20019. ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
  20020. transmit_response(p, "400 Bad request", req);
  20021. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20022. return -1;
  20023. }
  20024. /*
  20025. From the RFC...
  20026. A minimal, but complete, implementation can respond with a single
  20027. NOTIFY containing either the body:
  20028. SIP/2.0 100 Trying
  20029. if the subscription is pending, the body:
  20030. SIP/2.0 200 OK
  20031. if the reference was successful, the body:
  20032. SIP/2.0 503 Service Unavailable
  20033. if the reference failed, or the body:
  20034. SIP/2.0 603 Declined
  20035. if the REFER request was accepted before approval to follow the
  20036. reference could be obtained and that approval was subsequently denied
  20037. (see Section 2.4.7).
  20038. If there are several REFERs in the same dialog, we need to
  20039. match the ID of the event header...
  20040. */
  20041. ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
  20042. cmd = ast_skip_blanks(buf);
  20043. code = cmd;
  20044. /* We are at SIP/2.0 */
  20045. while(*code && (*code > 32)) { /* Search white space */
  20046. code++;
  20047. }
  20048. *code++ = '\0';
  20049. code = ast_skip_blanks(code);
  20050. sep = code;
  20051. sep++;
  20052. while(*sep && (*sep > 32)) { /* Search white space */
  20053. sep++;
  20054. }
  20055. *sep++ = '\0'; /* Response string */
  20056. respcode = atoi(code);
  20057. switch (respcode) {
  20058. case 200: /* OK: The new call is up, hangup this call */
  20059. /* Hangup the call that we are replacing */
  20060. break;
  20061. case 301: /* Moved permenantly */
  20062. case 302: /* Moved temporarily */
  20063. /* Do we get the header in the packet in this case? */
  20064. success = FALSE;
  20065. break;
  20066. case 503: /* Service Unavailable: The new call failed */
  20067. case 603: /* Declined: Not accepted */
  20068. /* Cancel transfer, continue the current call */
  20069. success = FALSE;
  20070. break;
  20071. case 0: /* Parse error */
  20072. /* Cancel transfer, continue the current call */
  20073. ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
  20074. success = FALSE;
  20075. break;
  20076. default:
  20077. if (respcode < 200) {
  20078. /* ignore provisional responses */
  20079. success = -1;
  20080. } else {
  20081. ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
  20082. success = FALSE;
  20083. }
  20084. break;
  20085. }
  20086. if (success == FALSE) {
  20087. ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
  20088. }
  20089. if (p->owner && success != -1) {
  20090. enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
  20091. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  20092. }
  20093. /* Confirm that we received this packet */
  20094. transmit_response(p, "200 OK", req);
  20095. } else if (!strcmp(event, "message-summary")) {
  20096. const char *mailbox = NULL;
  20097. char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
  20098. if (!p->mwi) {
  20099. struct sip_peer *peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
  20100. if (peer) {
  20101. mailbox = ast_strdupa(peer->unsolicited_mailbox);
  20102. unref_peer(peer, "removing unsolicited mwi ref");
  20103. }
  20104. } else {
  20105. mailbox = p->mwi->mailbox;
  20106. }
  20107. if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
  20108. char *old = strsep(&c, " ");
  20109. char *new = strsep(&old, "/");
  20110. struct ast_event *event;
  20111. if ((event = ast_event_new(AST_EVENT_MWI,
  20112. AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
  20113. AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
  20114. AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
  20115. AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
  20116. AST_EVENT_IE_END))) {
  20117. ast_event_queue_and_cache(event);
  20118. }
  20119. transmit_response(p, "200 OK", req);
  20120. } else {
  20121. transmit_response(p, "489 Bad event", req);
  20122. res = -1;
  20123. }
  20124. } else if (!strcmp(event, "keep-alive")) {
  20125. /* Used by Sipura/Linksys for NAT pinhole,
  20126. * just confirm that we received the packet. */
  20127. transmit_response(p, "200 OK", req);
  20128. } else if (!strcmp(event, "call-completion")) {
  20129. res = handle_cc_notify(p, req);
  20130. } else {
  20131. /* We don't understand this event. */
  20132. transmit_response(p, "489 Bad event", req);
  20133. res = -1;
  20134. }
  20135. if (!p->lastinvite)
  20136. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20137. return res;
  20138. }
  20139. /*! \brief Handle incoming OPTIONS request
  20140. An OPTIONS request should be answered like an INVITE from the same UA, including SDP
  20141. */
  20142. static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
  20143. {
  20144. const char *msg;
  20145. enum sip_get_dest_result gotdest;
  20146. int res;
  20147. if (p->lastinvite) {
  20148. /* if this is a request in an active dialog, just confirm that the dialog exists. */
  20149. transmit_response_with_allow(p, "200 OK", req, 0);
  20150. return 0;
  20151. }
  20152. if (sip_cfg.auth_options_requests) {
  20153. /* Do authentication if this OPTIONS request began the dialog */
  20154. copy_request(&p->initreq, req);
  20155. set_pvt_allowed_methods(p, req);
  20156. res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
  20157. if (res == AUTH_CHALLENGE_SENT) {
  20158. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20159. return 0;
  20160. }
  20161. if (res < 0) { /* Something failed in authentication */
  20162. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
  20163. transmit_response(p, "403 Forbidden", req);
  20164. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20165. return 0;
  20166. }
  20167. }
  20168. /* must go through authentication before getting here */
  20169. gotdest = get_destination(p, req, NULL);
  20170. build_contact(p);
  20171. if (ast_strlen_zero(p->context))
  20172. ast_string_field_set(p, context, sip_cfg.default_context);
  20173. if (ast_shutting_down()) {
  20174. msg = "503 Unavailable";
  20175. } else {
  20176. msg = "404 Not Found";
  20177. switch (gotdest) {
  20178. case SIP_GET_DEST_INVALID_URI:
  20179. msg = "416 Unsupported URI scheme";
  20180. break;
  20181. case SIP_GET_DEST_EXTEN_MATCHMORE:
  20182. case SIP_GET_DEST_REFUSED:
  20183. case SIP_GET_DEST_EXTEN_NOT_FOUND:
  20184. //msg = "404 Not Found";
  20185. break;
  20186. case SIP_GET_DEST_EXTEN_FOUND:
  20187. msg = "200 OK";
  20188. break;
  20189. }
  20190. }
  20191. transmit_response_with_allow(p, msg, req, 0);
  20192. /* Destroy if this OPTIONS was the opening request, but not if
  20193. it's in the middle of a normal call flow. */
  20194. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20195. return 0;
  20196. }
  20197. /*! \brief Handle the transfer part of INVITE with a replaces: header,
  20198. meaning a target pickup or an attended transfer.
  20199. Used only once.
  20200. XXX 'ignore' is unused.
  20201. \note this function is called by handle_request_invite(). Four locks
  20202. held at the beginning of this function, p, p->owner, p->refer->refer_call and
  20203. p->refere->refer_call->owner. only p's lock should remain at the end of this
  20204. function. p's lock as well as the channel p->owner's lock are held by
  20205. handle_request_do(), we unlock p->owner before the masq. By setting nounlock
  20206. we are indicating to handle_request_do() that we have already unlocked the owner.
  20207. */
  20208. static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock)
  20209. {
  20210. int earlyreplace = 0;
  20211. int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
  20212. struct ast_channel *c = p->owner; /* Our incoming call */
  20213. struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
  20214. struct ast_channel *targetcall; /* The bridge to the take-over target */
  20215. /* Check if we're in ring state */
  20216. if (replacecall->_state == AST_STATE_RING)
  20217. earlyreplace = 1;
  20218. /* Check if we have a bridge */
  20219. if (!(targetcall = ast_bridged_channel(replacecall))) {
  20220. /* We have no bridge */
  20221. if (!earlyreplace) {
  20222. ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
  20223. oneleggedreplace = 1;
  20224. }
  20225. }
  20226. if (targetcall && targetcall->_state == AST_STATE_RINGING)
  20227. ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
  20228. if (targetcall)
  20229. ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
  20230. else
  20231. ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
  20232. if (req->ignore) {
  20233. ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
  20234. /* We should answer something here. If we are here, the
  20235. call we are replacing exists, so an accepted
  20236. can't harm */
  20237. transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
  20238. /* Do something more clever here */
  20239. if (c) {
  20240. *nounlock = 1;
  20241. ast_channel_unlock(c);
  20242. }
  20243. ast_channel_unlock(replacecall);
  20244. sip_pvt_unlock(p->refer->refer_call);
  20245. return 1;
  20246. }
  20247. if (!c) {
  20248. /* What to do if no channel ??? */
  20249. ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
  20250. transmit_response_reliable(p, "503 Service Unavailable", req);
  20251. append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
  20252. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20253. ast_channel_unlock(replacecall);
  20254. sip_pvt_unlock(p->refer->refer_call);
  20255. return 1;
  20256. }
  20257. append_history(p, "Xfer", "INVITE/Replace received");
  20258. /* We have three channels to play with
  20259. channel c: New incoming call
  20260. targetcall: Call from PBX to target
  20261. p->refer->refer_call: SIP pvt dialog from transferer to pbx.
  20262. replacecall: The owner of the previous
  20263. We need to masq C into refer_call to connect to
  20264. targetcall;
  20265. If we are talking to internal audio stream, target call is null.
  20266. */
  20267. /* Fake call progress */
  20268. transmit_response(p, "100 Trying", req);
  20269. ast_setstate(c, AST_STATE_RING);
  20270. /* Masquerade the new call into the referred call to connect to target call
  20271. Targetcall is not touched by the masq */
  20272. /* Answer the incoming call and set channel to UP state */
  20273. transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
  20274. /* Is this a call pickup? */
  20275. if (earlyreplace || oneleggedreplace) {
  20276. /* Report pickup event, in this order: PICKUP, CHAN_UP, ANSWER */
  20277. ast_cel_report_event(replacecall, AST_CEL_PICKUP, NULL, NULL, c);
  20278. ast_setstate(c, AST_STATE_UP);
  20279. ast_cel_report_event(c, AST_CEL_ANSWER, NULL, NULL, NULL);
  20280. } else {
  20281. ast_setstate(c, AST_STATE_UP);
  20282. }
  20283. /* Stop music on hold and other generators */
  20284. ast_quiet_chan(replacecall);
  20285. ast_quiet_chan(targetcall);
  20286. ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
  20287. /* Make sure that the masq does not free our PVT for the old call */
  20288. if (! earlyreplace && ! oneleggedreplace )
  20289. ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
  20290. /* Prepare the masquerade - if this does not happen, we will be gone */
  20291. if(ast_channel_masquerade(replacecall, c))
  20292. ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
  20293. else
  20294. ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
  20295. /* C should now be in place of replacecall. all channel locks and pvt locks should be removed
  20296. * before issuing the masq. Since we are unlocking both the pvt (p) and its owner channel (c)
  20297. * it is possible for channel c to be destroyed on us. To prevent this, we must give c a reference
  20298. * before any unlocking takes place and remove it only once we are completely done with it */
  20299. ast_channel_ref(c);
  20300. ast_channel_unlock(replacecall);
  20301. ast_channel_unlock(c);
  20302. sip_pvt_unlock(p->refer->refer_call);
  20303. sip_pvt_unlock(p);
  20304. if (ast_do_masquerade(replacecall)) {
  20305. ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
  20306. }
  20307. if (earlyreplace || oneleggedreplace ) {
  20308. ast_channel_lock(c);
  20309. c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
  20310. ast_channel_unlock(c);
  20311. }
  20312. /* The call should be down with no ast_channel, so hang it up */
  20313. c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
  20314. /* c and c's tech pvt must be unlocked at this point for ast_hangup */
  20315. ast_hangup(c);
  20316. /* this indicates to handle_request_do that the owner channel has already been unlocked */
  20317. *nounlock = 1;
  20318. /* lock PVT structure again after hangup */
  20319. sip_pvt_lock(p);
  20320. ast_channel_unref(c);
  20321. return 0;
  20322. }
  20323. /*! \note No channel or pvt locks should be held while calling this function. */
  20324. static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
  20325. {
  20326. struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
  20327. struct ast_app *pickup = pbx_findapp("Pickup");
  20328. if (!pickup) {
  20329. ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
  20330. return -1;
  20331. }
  20332. ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
  20333. ast_debug(2, "About to call Pickup(%s)\n", ast_str_buffer(str));
  20334. /* There is no point in capturing the return value since pickup_exec
  20335. doesn't return anything meaningful unless the passed data is an empty
  20336. string (which in our case it will not be) */
  20337. pbx_exec(channel, pickup, ast_str_buffer(str));
  20338. return 0;
  20339. }
  20340. /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
  20341. static int sip_t38_abort(const void *data)
  20342. {
  20343. struct sip_pvt *p = (struct sip_pvt *) data;
  20344. sip_pvt_lock(p);
  20345. /* an application may have taken ownership of the T.38 negotiation on this
  20346. * channel while we were waiting to grab the lock... if it did, the scheduler
  20347. * id will have been reset to -1, which is our indication that we do *not*
  20348. * want to abort the negotiation process
  20349. */
  20350. if (p->t38id != -1) {
  20351. change_t38_state(p, T38_DISABLED);
  20352. transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
  20353. p->t38id = -1;
  20354. dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
  20355. }
  20356. sip_pvt_unlock(p);
  20357. return 0;
  20358. }
  20359. /*!
  20360. * \brief bare-bones support for SIP UPDATE
  20361. *
  20362. * XXX This is not even close to being RFC 3311-compliant. We don't advertise
  20363. * that we support the UPDATE method, so no one should ever try sending us
  20364. * an UPDATE anyway. However, Asterisk can send an UPDATE to change connected
  20365. * line information, so we need to be prepared to handle this. The way we distinguish
  20366. * such an UPDATE is through the X-Asterisk-rpid-update header.
  20367. *
  20368. * Actually updating the media session may be some future work.
  20369. */
  20370. static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
  20371. {
  20372. if (ast_strlen_zero(get_header(req, "X-Asterisk-rpid-update"))) {
  20373. transmit_response(p, "501 Method Not Implemented", req);
  20374. return 0;
  20375. }
  20376. if (!p->owner) {
  20377. transmit_response(p, "481 Call/Transaction Does Not Exist", req);
  20378. return 0;
  20379. }
  20380. if (get_rpid(p, req)) {
  20381. struct ast_party_connected_line connected;
  20382. struct ast_set_party_connected_line update_connected;
  20383. ast_party_connected_line_init(&connected);
  20384. memset(&update_connected, 0, sizeof(update_connected));
  20385. update_connected.id.number = 1;
  20386. connected.id.number.valid = 1;
  20387. connected.id.number.str = (char *) p->cid_num;
  20388. connected.id.number.presentation = p->callingpres;
  20389. update_connected.id.name = 1;
  20390. connected.id.name.valid = 1;
  20391. connected.id.name.str = (char *) p->cid_name;
  20392. connected.id.name.presentation = p->callingpres;
  20393. connected.id.tag = (char *) p->cid_tag;
  20394. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
  20395. ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
  20396. }
  20397. transmit_response(p, "200 OK", req);
  20398. return 0;
  20399. }
  20400. /*
  20401. * \internal \brief Check Session Timers for an INVITE request
  20402. *
  20403. * \retval 0 ok
  20404. * \retval -1 failure
  20405. */
  20406. static int handle_request_invite_st(struct sip_pvt *p, struct sip_request *req,
  20407. const char *required, int reinvite)
  20408. {
  20409. const char *p_uac_se_hdr; /* UAC's Session-Expires header string */
  20410. const char *p_uac_min_se; /* UAC's requested Min-SE interval (char string) */
  20411. int uac_max_se = -1; /* UAC's Session-Expires in integer format */
  20412. int uac_min_se = -1; /* UAC's Min-SE in integer format */
  20413. int st_active = FALSE; /* Session-Timer on/off boolean */
  20414. int st_interval = 0; /* Session-Timer negotiated refresh interval */
  20415. enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO; /* Session-Timer refresher */
  20416. int dlg_min_se = -1;
  20417. int dlg_max_se = global_max_se;
  20418. int rtn;
  20419. /* Session-Timers */
  20420. if ((p->sipoptions & SIP_OPT_TIMER)) {
  20421. enum st_refresher_param st_ref_param = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
  20422. /* The UAC has requested session-timers for this session. Negotiate
  20423. the session refresh interval and who will be the refresher */
  20424. ast_debug(2, "Incoming INVITE with 'timer' option supported\n");
  20425. /* Allocate Session-Timers struct w/in the dialog */
  20426. if (!p->stimer) {
  20427. sip_st_alloc(p);
  20428. }
  20429. /* Parse the Session-Expires header */
  20430. p_uac_se_hdr = get_header(req, "Session-Expires");
  20431. if (!ast_strlen_zero(p_uac_se_hdr)) {
  20432. ast_debug(2, "INVITE also has \"Session-Expires\" header.\n");
  20433. rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
  20434. tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
  20435. if (rtn != 0) {
  20436. transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
  20437. return -1;
  20438. }
  20439. }
  20440. /* Parse the Min-SE header */
  20441. p_uac_min_se = get_header(req, "Min-SE");
  20442. if (!ast_strlen_zero(p_uac_min_se)) {
  20443. ast_debug(2, "INVITE also has \"Min-SE\" header.\n");
  20444. rtn = parse_minse(p_uac_min_se, &uac_min_se);
  20445. if (rtn != 0) {
  20446. transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
  20447. return -1;
  20448. }
  20449. }
  20450. dlg_min_se = st_get_se(p, FALSE);
  20451. switch (st_get_mode(p, 1)) {
  20452. case SESSION_TIMER_MODE_ACCEPT:
  20453. case SESSION_TIMER_MODE_ORIGINATE:
  20454. if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
  20455. transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
  20456. return -1;
  20457. }
  20458. p->stimer->st_active_peer_ua = TRUE;
  20459. st_active = TRUE;
  20460. if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
  20461. tmp_st_ref = st_get_refresher(p);
  20462. }
  20463. dlg_max_se = st_get_se(p, TRUE);
  20464. if (uac_max_se > 0) {
  20465. if (dlg_max_se >= uac_min_se) {
  20466. st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
  20467. } else {
  20468. st_interval = uac_max_se;
  20469. }
  20470. } else if (uac_min_se > 0) {
  20471. st_interval = MAX(dlg_max_se, uac_min_se);
  20472. } else {
  20473. st_interval = dlg_max_se;
  20474. }
  20475. break;
  20476. case SESSION_TIMER_MODE_REFUSE:
  20477. if (p->reqsipoptions & SIP_OPT_TIMER) {
  20478. transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
  20479. ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
  20480. return -1;
  20481. }
  20482. break;
  20483. default:
  20484. ast_log(LOG_ERROR, "Internal Error %u at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
  20485. break;
  20486. }
  20487. } else {
  20488. /* The UAC did not request session-timers. Asterisk (UAS), will now decide
  20489. (based on session-timer-mode in sip.conf) whether to run session-timers for
  20490. this session or not. */
  20491. switch (st_get_mode(p, 1)) {
  20492. case SESSION_TIMER_MODE_ORIGINATE:
  20493. st_active = TRUE;
  20494. st_interval = st_get_se(p, TRUE);
  20495. tmp_st_ref = SESSION_TIMER_REFRESHER_US;
  20496. p->stimer->st_active_peer_ua = (p->sipoptions & SIP_OPT_TIMER) ? TRUE : FALSE;
  20497. break;
  20498. default:
  20499. break;
  20500. }
  20501. }
  20502. if (reinvite == 0) {
  20503. /* Session-Timers: Start session refresh timer based on negotiation/config */
  20504. if (st_active == TRUE) {
  20505. p->stimer->st_active = TRUE;
  20506. p->stimer->st_interval = st_interval;
  20507. p->stimer->st_ref = tmp_st_ref;
  20508. }
  20509. } else {
  20510. if (p->stimer->st_active == TRUE) {
  20511. /* Session-Timers: A re-invite request sent within a dialog will serve as
  20512. a refresh request, no matter whether the re-invite was sent for refreshing
  20513. the session or modifying it.*/
  20514. ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
  20515. /* The UAC may be adjusting the session-timers mid-session */
  20516. if (st_interval > 0) {
  20517. p->stimer->st_interval = st_interval;
  20518. p->stimer->st_ref = tmp_st_ref;
  20519. }
  20520. }
  20521. }
  20522. return 0;
  20523. }
  20524. /*!
  20525. * \brief Handle incoming INVITE request
  20526. * \note If the INVITE has a Replaces header, it is part of an
  20527. * attended transfer. If so, we do not go through the dial
  20528. * plan but try to find the active call and masquerade
  20529. * into it
  20530. */
  20531. static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock)
  20532. {
  20533. int res = 1;
  20534. int gotdest;
  20535. const char *p_replaces;
  20536. char *replace_id = NULL;
  20537. int refer_locked = 0;
  20538. const char *required;
  20539. unsigned int required_profile = 0;
  20540. struct ast_channel *c = NULL; /* New channel */
  20541. struct sip_peer *authpeer = NULL; /* Matching Peer */
  20542. int reinvite = 0;
  20543. struct ast_party_redirecting redirecting;
  20544. struct ast_set_party_redirecting update_redirecting;
  20545. int supported_start = 0;
  20546. int require_start = 0;
  20547. char unsupported[256] = { 0, };
  20548. struct {
  20549. char exten[AST_MAX_EXTENSION];
  20550. char context[AST_MAX_CONTEXT];
  20551. } pickup = {
  20552. .exten = "",
  20553. };
  20554. /* Find out what they support */
  20555. if (!p->sipoptions) {
  20556. const char *supported = NULL;
  20557. do {
  20558. supported = __get_header(req, "Supported", &supported_start);
  20559. if (!ast_strlen_zero(supported)) {
  20560. p->sipoptions |= parse_sip_options(supported, NULL, 0);
  20561. }
  20562. } while (!ast_strlen_zero(supported));
  20563. }
  20564. /* Find out what they require */
  20565. do {
  20566. required = __get_header(req, "Require", &require_start);
  20567. if (!ast_strlen_zero(required)) {
  20568. required_profile |= parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
  20569. }
  20570. } while (!ast_strlen_zero(required));
  20571. /* If there are any options required that we do not support,
  20572. * then send a 420 with only those unsupported options listed */
  20573. if (!ast_strlen_zero(unsupported)) {
  20574. transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
  20575. ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
  20576. p->invitestate = INV_COMPLETED;
  20577. if (!p->lastinvite) {
  20578. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20579. }
  20580. res = -1;
  20581. goto request_invite_cleanup;
  20582. }
  20583. /* The option tags may be present in Supported: or Require: headers.
  20584. Include the Require: option tags for further processing as well */
  20585. p->sipoptions |= required_profile;
  20586. p->reqsipoptions = required_profile;
  20587. /* Check if this is a loop */
  20588. if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED) && p->owner->_state != AST_STATE_UP) {
  20589. /* This is a call to ourself. Send ourselves an error code and stop
  20590. processing immediately, as SIP really has no good mechanism for
  20591. being able to call yourself */
  20592. /* If pedantic is on, we need to check the tags. If they're different, this is
  20593. in fact a forked call through a SIP proxy somewhere. */
  20594. int different;
  20595. const char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
  20596. const char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
  20597. if (sip_cfg.pedanticsipchecking)
  20598. different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
  20599. else
  20600. different = strcmp(initial_rlPart2, this_rlPart2);
  20601. if (!different) {
  20602. transmit_response(p, "482 Loop Detected", req);
  20603. p->invitestate = INV_COMPLETED;
  20604. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20605. res = 0;
  20606. goto request_invite_cleanup;
  20607. } else {
  20608. /*! This is a spiral. What we need to do is to just change the outgoing INVITE
  20609. * so that it now routes to the new Request URI. Since we created the INVITE ourselves
  20610. * that should be all we need to do.
  20611. *
  20612. * \todo XXX This needs to be reviewed. YOu don't change the request URI really, you route the packet
  20613. * correctly instead...
  20614. */
  20615. char *uri = ast_strdupa(this_rlPart2);
  20616. char *at = strchr(uri, '@');
  20617. char *peerorhost;
  20618. ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
  20619. transmit_response(p, "100 Trying", req);
  20620. if (at) {
  20621. *at = '\0';
  20622. }
  20623. /* Parse out "sip:" */
  20624. if ((peerorhost = strchr(uri, ':'))) {
  20625. *peerorhost++ = '\0';
  20626. }
  20627. ast_string_field_set(p, theirtag, NULL);
  20628. /* Treat this as if there were a call forward instead...
  20629. */
  20630. ast_string_field_set(p->owner, call_forward, peerorhost);
  20631. ast_queue_control(p->owner, AST_CONTROL_BUSY);
  20632. res = 0;
  20633. goto request_invite_cleanup;
  20634. }
  20635. }
  20636. if (!req->ignore && p->pendinginvite) {
  20637. if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
  20638. /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
  20639. * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
  20640. * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
  20641. * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
  20642. * credentials based on one we challenged earlier.
  20643. *
  20644. * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
  20645. * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
  20646. * from the previous transaction from the list of outstanding packets.
  20647. */
  20648. __sip_ack(p, p->pendinginvite, 1, 0);
  20649. } else {
  20650. /* We already have a pending invite. Sorry. You are on hold. */
  20651. p->glareinvite = seqno;
  20652. if (p->rtp && find_sdp(req)) {
  20653. struct ast_sockaddr addr;
  20654. if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
  20655. ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
  20656. } else {
  20657. ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
  20658. }
  20659. if (p->vrtp) {
  20660. if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
  20661. ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
  20662. } else {
  20663. ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
  20664. }
  20665. }
  20666. }
  20667. transmit_response_reliable(p, "491 Request Pending", req);
  20668. check_via(p, req);
  20669. ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
  20670. /* Don't destroy dialog here */
  20671. res = 0;
  20672. goto request_invite_cleanup;
  20673. }
  20674. }
  20675. p_replaces = get_header(req, "Replaces");
  20676. if (!ast_strlen_zero(p_replaces)) {
  20677. /* We have a replaces header */
  20678. char *ptr;
  20679. char *fromtag = NULL;
  20680. char *totag = NULL;
  20681. char *start, *to;
  20682. int error = 0;
  20683. if (p->owner) {
  20684. ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
  20685. transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
  20686. check_via(p, req);
  20687. copy_request(&p->initreq, req);
  20688. /* Do not destroy existing call */
  20689. res = -1;
  20690. goto request_invite_cleanup;
  20691. }
  20692. if (sipdebug)
  20693. ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
  20694. /* Create a buffer we can manipulate */
  20695. replace_id = ast_strdupa(p_replaces);
  20696. ast_uri_decode(replace_id);
  20697. if (!p->refer && !sip_refer_allocate(p)) {
  20698. transmit_response_reliable(p, "500 Server Internal Error", req);
  20699. append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
  20700. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20701. p->invitestate = INV_COMPLETED;
  20702. check_via(p, req);
  20703. copy_request(&p->initreq, req);
  20704. res = -1;
  20705. goto request_invite_cleanup;
  20706. }
  20707. /* Todo: (When we find phones that support this)
  20708. if the replaces header contains ";early-only"
  20709. we can only replace the call in early
  20710. stage, not after it's up.
  20711. If it's not in early mode, 486 Busy.
  20712. */
  20713. /* Skip leading whitespace */
  20714. replace_id = ast_skip_blanks(replace_id);
  20715. start = replace_id;
  20716. while ( (ptr = strsep(&start, ";")) ) {
  20717. ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
  20718. if ( (to = strcasestr(ptr, "to-tag=") ) )
  20719. totag = to + 7; /* skip the keyword */
  20720. else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
  20721. fromtag = to + 9; /* skip the keyword */
  20722. fromtag = strsep(&fromtag, "&"); /* trim what ? */
  20723. }
  20724. }
  20725. if (sipdebug)
  20726. ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
  20727. replace_id,
  20728. fromtag ? fromtag : "<no from tag>",
  20729. totag ? totag : "<no to tag>");
  20730. /* Try to find call that we are replacing.
  20731. If we have a Replaces header, we need to cancel that call if we succeed with this call.
  20732. First we cheat a little and look for a magic call-id from phones that support
  20733. dialog-info+xml so we can do technology independent pickup... */
  20734. if (strncmp(replace_id, "pickup-", 7) == 0) {
  20735. struct sip_pvt *subscription = NULL;
  20736. replace_id += 7; /* Worst case we are looking at \0 */
  20737. if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
  20738. ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
  20739. transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
  20740. error = 1;
  20741. } else {
  20742. ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
  20743. ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
  20744. ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
  20745. sip_pvt_unlock(subscription);
  20746. if (subscription->owner) {
  20747. ast_channel_unlock(subscription->owner);
  20748. }
  20749. subscription = dialog_unref(subscription, "unref dialog subscription");
  20750. }
  20751. }
  20752. /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
  20753. if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
  20754. ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
  20755. transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
  20756. error = 1;
  20757. } else {
  20758. refer_locked = 1;
  20759. }
  20760. /* The matched call is the call from the transferer to Asterisk .
  20761. We want to bridge the bridged part of the call to the
  20762. incoming invite, thus taking over the refered call */
  20763. if (p->refer->refer_call == p) {
  20764. ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
  20765. transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
  20766. error = 1;
  20767. }
  20768. if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
  20769. /* Oops, someting wrong anyway, no owner, no call */
  20770. ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
  20771. /* Check for better return code */
  20772. transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
  20773. error = 1;
  20774. }
  20775. if (!error && ast_strlen_zero(pickup.exten) && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP) {
  20776. ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
  20777. transmit_response_reliable(p, "603 Declined (Replaces)", req);
  20778. error = 1;
  20779. }
  20780. if (error) { /* Give up this dialog */
  20781. append_history(p, "Xfer", "INVITE/Replace Failed.");
  20782. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20783. sip_pvt_unlock(p);
  20784. if (p->refer->refer_call) {
  20785. sip_pvt_unlock(p->refer->refer_call);
  20786. if (p->refer->refer_call->owner) {
  20787. ast_channel_unlock(p->refer->refer_call->owner);
  20788. }
  20789. p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
  20790. }
  20791. refer_locked = 0;
  20792. p->invitestate = INV_COMPLETED;
  20793. check_via(p, req);
  20794. copy_request(&p->initreq, req);
  20795. res = -1;
  20796. goto request_invite_cleanup;
  20797. }
  20798. }
  20799. /* Check if this is an INVITE that sets up a new dialog or
  20800. a re-invite in an existing dialog */
  20801. if (!req->ignore) {
  20802. int newcall = (p->initreq.headers ? TRUE : FALSE);
  20803. if (sip_cancel_destroy(p))
  20804. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  20805. /* This also counts as a pending invite */
  20806. p->pendinginvite = seqno;
  20807. check_via(p, req);
  20808. copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
  20809. if (sipdebug)
  20810. ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  20811. if (!p->owner) { /* Not a re-invite */
  20812. if (debug)
  20813. ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
  20814. if (newcall)
  20815. append_history(p, "Invite", "New call: %s", p->callid);
  20816. parse_ok_contact(p, req);
  20817. } else { /* Re-invite on existing call */
  20818. ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
  20819. if (get_rpid(p, req)) {
  20820. struct ast_party_connected_line connected;
  20821. struct ast_set_party_connected_line update_connected;
  20822. ast_party_connected_line_init(&connected);
  20823. memset(&update_connected, 0, sizeof(update_connected));
  20824. update_connected.id.number = 1;
  20825. connected.id.number.valid = 1;
  20826. connected.id.number.str = (char *) p->cid_num;
  20827. connected.id.number.presentation = p->callingpres;
  20828. update_connected.id.name = 1;
  20829. connected.id.name.valid = 1;
  20830. connected.id.name.str = (char *) p->cid_name;
  20831. connected.id.name.presentation = p->callingpres;
  20832. connected.id.tag = (char *) p->cid_tag;
  20833. connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
  20834. ast_channel_queue_connected_line_update(p->owner, &connected,
  20835. &update_connected);
  20836. }
  20837. /* Handle SDP here if we already have an owner */
  20838. if (find_sdp(req)) {
  20839. if (process_sdp(p, req, SDP_T38_INITIATE)) {
  20840. if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
  20841. /* Asterisk does not yet support any Content-Encoding methods. Always
  20842. * attempt to process the sdp, but return a 415 if a Content-Encoding header
  20843. * was present after processing failed. */
  20844. transmit_response_reliable(p, "415 Unsupported Media type", req);
  20845. } else {
  20846. transmit_response_reliable(p, "488 Not acceptable here", req);
  20847. }
  20848. if (!p->lastinvite)
  20849. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20850. res = -1;
  20851. goto request_invite_cleanup;
  20852. }
  20853. ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
  20854. } else {
  20855. p->jointcapability = p->capability;
  20856. ast_debug(1, "Hm.... No sdp for the moment\n");
  20857. /* Some devices signal they want to be put off hold by sending a re-invite
  20858. *without* an SDP, which is supposed to mean "Go back to your state"
  20859. and since they put os on remote hold, we go back to off hold */
  20860. if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
  20861. ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
  20862. /* Activate a re-invite */
  20863. ast_queue_frame(p->owner, &ast_null_frame);
  20864. change_hold_state(p, req, FALSE, 0);
  20865. }
  20866. }
  20867. if (p->do_history) /* This is a response, note what it was for */
  20868. append_history(p, "ReInv", "Re-invite received");
  20869. }
  20870. } else if (debug)
  20871. ast_verbose("Ignoring this INVITE request\n");
  20872. if (!p->lastinvite && !req->ignore && !p->owner) {
  20873. /* This is a new invite */
  20874. /* Handle authentication if this is our first invite */
  20875. int cc_recall_core_id = -1;
  20876. set_pvt_allowed_methods(p, req);
  20877. res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
  20878. if (res == AUTH_CHALLENGE_SENT) {
  20879. p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
  20880. res = 0;
  20881. goto request_invite_cleanup;
  20882. }
  20883. if (res < 0) { /* Something failed in authentication */
  20884. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
  20885. transmit_response_reliable(p, "403 Forbidden", req);
  20886. p->invitestate = INV_COMPLETED;
  20887. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20888. res = 0;
  20889. goto request_invite_cleanup;
  20890. }
  20891. /* Successful authentication and peer matching so record the peer related to this pvt (for easy access to peer settings) */
  20892. if (p->relatedpeer) {
  20893. p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
  20894. }
  20895. if (authpeer) {
  20896. p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
  20897. }
  20898. req->authenticated = 1;
  20899. /* We have a successful authentication, process the SDP portion if there is one */
  20900. if (find_sdp(req)) {
  20901. if (process_sdp(p, req, SDP_T38_INITIATE)) {
  20902. /* Asterisk does not yet support any Content-Encoding methods. Always
  20903. * attempt to process the sdp, but return a 415 if a Content-Encoding header
  20904. * was present after processing fails. */
  20905. if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
  20906. transmit_response_reliable(p, "415 Unsupported Media type", req);
  20907. } else {
  20908. /* Unacceptable codecs */
  20909. transmit_response_reliable(p, "488 Not acceptable here", req);
  20910. }
  20911. p->invitestate = INV_COMPLETED;
  20912. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20913. ast_debug(1, "No compatible codecs for this SIP call.\n");
  20914. res = -1;
  20915. goto request_invite_cleanup;
  20916. }
  20917. } else { /* No SDP in invite, call control session */
  20918. p->jointcapability = p->capability;
  20919. ast_debug(2, "No SDP in Invite, third party call control\n");
  20920. }
  20921. /* Initialize the context if it hasn't been already */
  20922. if (ast_strlen_zero(p->context))
  20923. ast_string_field_set(p, context, sip_cfg.default_context);
  20924. /* Check number of concurrent calls -vs- incoming limit HERE */
  20925. ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
  20926. if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
  20927. if (res < 0) {
  20928. ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
  20929. transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
  20930. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20931. p->invitestate = INV_COMPLETED;
  20932. }
  20933. res = 0;
  20934. goto request_invite_cleanup;
  20935. }
  20936. gotdest = get_destination(p, NULL, &cc_recall_core_id); /* Get destination right away */
  20937. extract_uri(p, req); /* Get the Contact URI */
  20938. build_contact(p); /* Build our contact header */
  20939. if (p->rtp) {
  20940. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  20941. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
  20942. }
  20943. if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) { /* No matching extension found */
  20944. switch(gotdest) {
  20945. case SIP_GET_DEST_INVALID_URI:
  20946. transmit_response_reliable(p, "416 Unsupported URI scheme", req);
  20947. break;
  20948. case SIP_GET_DEST_EXTEN_MATCHMORE:
  20949. if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
  20950. == SIP_PAGE2_ALLOWOVERLAP_YES) {
  20951. transmit_response_reliable(p, "484 Address Incomplete", req);
  20952. break;
  20953. }
  20954. /*
  20955. * XXX We would have to implement collecting more digits in
  20956. * chan_sip for any other schemes of overlap dialing.
  20957. *
  20958. * For SIP_PAGE2_ALLOWOVERLAP_DTMF it is better to do this in
  20959. * the dialplan using the Incomplete application rather than
  20960. * having the channel driver do it.
  20961. */
  20962. /* Fall through */
  20963. case SIP_GET_DEST_EXTEN_NOT_FOUND:
  20964. {
  20965. char *decoded_exten = ast_strdupa(p->exten);
  20966. transmit_response_reliable(p, "404 Not Found", req);
  20967. ast_uri_decode(decoded_exten);
  20968. ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
  20969. " '%s' rejected because extension not found in context '%s'.\n",
  20970. S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
  20971. }
  20972. break;
  20973. case SIP_GET_DEST_REFUSED:
  20974. default:
  20975. transmit_response_reliable(p, "403 Forbidden", req);
  20976. } /* end switch */
  20977. p->invitestate = INV_COMPLETED;
  20978. update_call_counter(p, DEC_CALL_LIMIT);
  20979. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20980. res = 0;
  20981. goto request_invite_cleanup;
  20982. } else {
  20983. /* If no extension was specified, use the s one */
  20984. /* Basically for calling to IP/Host name only */
  20985. if (ast_strlen_zero(p->exten))
  20986. ast_string_field_set(p, exten, "s");
  20987. /* Initialize our tag */
  20988. make_our_tag(p);
  20989. if (handle_request_invite_st(p, req, required, reinvite)) {
  20990. p->invitestate = INV_COMPLETED;
  20991. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  20992. res = -1;
  20993. goto request_invite_cleanup;
  20994. }
  20995. /* First invitation - create the channel. Allocation
  20996. * failures are handled below. */
  20997. c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL);
  20998. if (cc_recall_core_id != -1) {
  20999. ast_setup_cc_recall_datastore(c, cc_recall_core_id);
  21000. ast_cc_agent_set_interfaces_chanvar(c);
  21001. }
  21002. *recount = 1;
  21003. /* Save Record-Route for any later requests we make on this dialogue */
  21004. build_route(p, req, 0, 0);
  21005. if (c) {
  21006. ast_party_redirecting_init(&redirecting);
  21007. memset(&update_redirecting, 0, sizeof(update_redirecting));
  21008. change_redirecting_information(p, req, &redirecting, &update_redirecting,
  21009. FALSE); /*Will return immediately if no Diversion header is present */
  21010. ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
  21011. ast_party_redirecting_free(&redirecting);
  21012. }
  21013. }
  21014. } else {
  21015. ast_party_redirecting_init(&redirecting);
  21016. memset(&update_redirecting, 0, sizeof(update_redirecting));
  21017. if (sipdebug) {
  21018. if (!req->ignore)
  21019. ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
  21020. else
  21021. ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
  21022. }
  21023. if (!req->ignore)
  21024. reinvite = 1;
  21025. if (handle_request_invite_st(p, req, required, reinvite)) {
  21026. p->invitestate = INV_COMPLETED;
  21027. if (!p->lastinvite) {
  21028. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21029. }
  21030. res = -1;
  21031. goto request_invite_cleanup;
  21032. }
  21033. c = p->owner;
  21034. change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE); /*Will return immediately if no Diversion header is present */
  21035. if (c) {
  21036. ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
  21037. }
  21038. ast_party_redirecting_free(&redirecting);
  21039. }
  21040. if (reinvite && p->stimer->st_active == TRUE) {
  21041. restart_session_timer(p);
  21042. }
  21043. if (!req->ignore && p)
  21044. p->lastinvite = seqno;
  21045. if (c && replace_id) { /* Attended transfer or call pickup - we're the target */
  21046. if (!ast_strlen_zero(pickup.exten)) {
  21047. append_history(p, "Xfer", "INVITE/Replace received");
  21048. /* Let the caller know we're giving it a shot */
  21049. transmit_response(p, "100 Trying", req);
  21050. p->invitestate = INV_PROCEEDING;
  21051. ast_setstate(c, AST_STATE_RING);
  21052. /* Do the pickup itself */
  21053. ast_channel_unlock(c);
  21054. *nounlock = 1;
  21055. /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
  21056. * magic pickup and ast_hangup. Both of these functions will attempt to lock
  21057. * p->owner again, which can cause a deadlock if we already hold a lock on p.
  21058. * Locking order is, channel then pvt. Dead lock avoidance must be used if
  21059. * called the other way around. */
  21060. sip_pvt_unlock(p);
  21061. do_magic_pickup(c, pickup.exten, pickup.context);
  21062. /* Now we're either masqueraded or we failed to pickup, in either case we... */
  21063. ast_hangup(c);
  21064. sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
  21065. res = 0;
  21066. goto request_invite_cleanup;
  21067. } else {
  21068. /* Go and take over the target call */
  21069. if (sipdebug)
  21070. ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
  21071. res = handle_invite_replaces(p, req, debug, seqno, addr, nounlock);
  21072. refer_locked = 0;
  21073. goto request_invite_cleanup;
  21074. }
  21075. }
  21076. if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
  21077. enum ast_channel_state c_state = c->_state;
  21078. if (c_state != AST_STATE_UP && reinvite &&
  21079. (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
  21080. /* If these conditions are true, and the channel is still in the 'ringing'
  21081. * state, then this likely means that we have a situation where the initial
  21082. * INVITE transaction has completed *but* the channel's state has not yet been
  21083. * changed to UP. The reason this could happen is if the reinvite is received
  21084. * on the SIP socket prior to an application calling ast_read on this channel
  21085. * to read the answer frame we earlier queued on it. In this case, the reinvite
  21086. * is completely legitimate so we need to handle this the same as if the channel
  21087. * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
  21088. */
  21089. c_state = AST_STATE_UP;
  21090. }
  21091. switch(c_state) {
  21092. case AST_STATE_DOWN:
  21093. ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
  21094. transmit_provisional_response(p, "100 Trying", req, 0);
  21095. p->invitestate = INV_PROCEEDING;
  21096. ast_setstate(c, AST_STATE_RING);
  21097. if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
  21098. enum ast_pbx_result result;
  21099. result = ast_pbx_start(c);
  21100. switch(result) {
  21101. case AST_PBX_FAILED:
  21102. ast_log(LOG_WARNING, "Failed to start PBX :(\n");
  21103. p->invitestate = INV_COMPLETED;
  21104. transmit_response_reliable(p, "503 Unavailable", req);
  21105. break;
  21106. case AST_PBX_CALL_LIMIT:
  21107. ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
  21108. p->invitestate = INV_COMPLETED;
  21109. transmit_response_reliable(p, "480 Temporarily Unavailable", req);
  21110. break;
  21111. case AST_PBX_SUCCESS:
  21112. /* nothing to do */
  21113. break;
  21114. }
  21115. if (result) {
  21116. /* Unlock locks so ast_hangup can do its magic */
  21117. ast_channel_unlock(c);
  21118. *nounlock = 1;
  21119. sip_pvt_unlock(p);
  21120. ast_hangup(c);
  21121. sip_pvt_lock(p);
  21122. c = NULL;
  21123. }
  21124. } else { /* Pickup call in call group */
  21125. if (sip_pickup(c)) {
  21126. ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", c->name);
  21127. transmit_response_reliable(p, "480 Temporarily Unavailable", req);
  21128. sip_alreadygone(p);
  21129. c->hangupcause = AST_CAUSE_FAILURE;
  21130. /* Unlock locks so ast_hangup can do its magic */
  21131. ast_channel_unlock(c);
  21132. *nounlock = 1;
  21133. p->invitestate = INV_COMPLETED;
  21134. sip_pvt_unlock(p);
  21135. ast_hangup(c);
  21136. sip_pvt_lock(p);
  21137. c = NULL;
  21138. }
  21139. }
  21140. break;
  21141. case AST_STATE_RING:
  21142. transmit_provisional_response(p, "100 Trying", req, 0);
  21143. p->invitestate = INV_PROCEEDING;
  21144. break;
  21145. case AST_STATE_RINGING:
  21146. transmit_provisional_response(p, "180 Ringing", req, 0);
  21147. p->invitestate = INV_PROCEEDING;
  21148. break;
  21149. case AST_STATE_UP:
  21150. ast_debug(2, "%s: This call is UP.... \n", c->name);
  21151. transmit_response(p, "100 Trying", req);
  21152. if (p->t38.state == T38_PEER_REINVITE) {
  21153. if (p->t38id > -1) {
  21154. /* reset t38 abort timer */
  21155. AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
  21156. }
  21157. 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."));
  21158. } else if (p->t38.state == T38_ENABLED) {
  21159. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  21160. transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
  21161. } else if (p->t38.state == T38_DISABLED) {
  21162. /* If this is not a re-invite or something to ignore - it's critical */
  21163. if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
  21164. ast_log(LOG_WARNING, "Target does not support required crypto\n");
  21165. transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
  21166. } else {
  21167. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  21168. transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
  21169. ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
  21170. }
  21171. }
  21172. p->invitestate = INV_TERMINATED;
  21173. break;
  21174. default:
  21175. ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %u\n", c->_state);
  21176. transmit_response(p, "100 Trying", req);
  21177. break;
  21178. }
  21179. } else {
  21180. if (!req->ignore && p && (p->autokillid == -1)) {
  21181. const char *msg;
  21182. if (!p->jointcapability)
  21183. msg = "488 Not Acceptable Here (codec error)";
  21184. else {
  21185. ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
  21186. msg = "503 Unavailable";
  21187. }
  21188. transmit_response_reliable(p, msg, req);
  21189. p->invitestate = INV_COMPLETED;
  21190. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21191. }
  21192. }
  21193. request_invite_cleanup:
  21194. if (refer_locked && p->refer && p->refer->refer_call) {
  21195. sip_pvt_unlock(p->refer->refer_call);
  21196. if (p->refer->refer_call->owner) {
  21197. ast_channel_unlock(p->refer->refer_call->owner);
  21198. }
  21199. p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
  21200. }
  21201. if (authpeer) {
  21202. authpeer = unref_peer(authpeer, "unref_peer, from handle_request_invite authpeer");
  21203. }
  21204. return res;
  21205. }
  21206. /*! \brief Find all call legs and bridge transferee with target
  21207. * called from handle_request_refer
  21208. *
  21209. * \note this function assumes two locks to begin with, sip_pvt transferer and current.chan1 (the pvt's owner)...
  21210. * 2 additional locks are held at the beginning of the function, targetcall_pvt, and targetcall_pvt's owner
  21211. * channel (which is stored in target.chan1). These 2 locks _MUST_ be let go by the end of the function. Do
  21212. * not be confused into thinking a pvt's owner is the same thing as the channels locked at the beginning of
  21213. * this function, after the masquerade this may not be true. Be consistent and unlock only the exact same
  21214. * pointers that were locked to begin with.
  21215. *
  21216. * If this function is successful, only the transferer pvt lock will remain on return. Setting nounlock indicates
  21217. * to handle_request_do() that the pvt's owner it locked does not require an unlock.
  21218. */
  21219. static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock)
  21220. {
  21221. struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
  21222. /* Chan 2: Call from Asterisk to target */
  21223. int res = 0;
  21224. struct sip_pvt *targetcall_pvt;
  21225. struct ast_party_connected_line connected_to_transferee;
  21226. struct ast_party_connected_line connected_to_target;
  21227. char transferer_linkedid[32];
  21228. struct ast_channel *chans[2];
  21229. /* Check if the call ID of the replaces header does exist locally */
  21230. if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
  21231. transferer->refer->replaces_callid_fromtag))) {
  21232. if (transferer->refer->localtransfer) {
  21233. /* We did not find the refered call. Sorry, can't accept then */
  21234. /* Let's fake a response from someone else in order
  21235. to follow the standard */
  21236. transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
  21237. append_history(transferer, "Xfer", "Refer failed");
  21238. ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
  21239. transferer->refer->status = REFER_FAILED;
  21240. return -1;
  21241. }
  21242. /* Fall through for remote transfers that we did not find locally */
  21243. ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
  21244. return 0;
  21245. }
  21246. /* Ok, we can accept this transfer */
  21247. append_history(transferer, "Xfer", "Refer accepted");
  21248. if (!targetcall_pvt->owner) { /* No active channel */
  21249. ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
  21250. /* Cancel transfer */
  21251. transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
  21252. append_history(transferer, "Xfer", "Refer failed");
  21253. ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
  21254. transferer->refer->status = REFER_FAILED;
  21255. sip_pvt_unlock(targetcall_pvt);
  21256. if (targetcall_pvt)
  21257. ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
  21258. return -1;
  21259. }
  21260. /* We have a channel, find the bridge */
  21261. target.chan1 = ast_channel_ref(targetcall_pvt->owner); /* Transferer to Asterisk */
  21262. target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
  21263. if (target.chan2) {
  21264. ast_channel_ref(target.chan2);
  21265. }
  21266. if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
  21267. /* Wrong state of new channel */
  21268. if (target.chan2)
  21269. ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
  21270. else if (target.chan1->_state != AST_STATE_RING)
  21271. ast_debug(4, "SIP attended transfer: Error: No target channel\n");
  21272. else
  21273. ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
  21274. }
  21275. /* Transfer */
  21276. if (sipdebug) {
  21277. if (current->chan2) /* We have two bridges */
  21278. ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
  21279. else /* One bridge, propably transfer of IVR/voicemail etc */
  21280. ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
  21281. }
  21282. ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
  21283. ast_copy_string(transferer_linkedid, transferer->owner->linkedid, sizeof(transferer_linkedid));
  21284. /* Perform the transfer */
  21285. chans[0] = transferer->owner;
  21286. chans[1] = target.chan1;
  21287. ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
  21288. "TransferMethod: SIP\r\n"
  21289. "TransferType: Attended\r\n"
  21290. "Channel: %s\r\n"
  21291. "Uniqueid: %s\r\n"
  21292. "SIP-Callid: %s\r\n"
  21293. "TargetChannel: %s\r\n"
  21294. "TargetUniqueid: %s\r\n",
  21295. transferer->owner->name,
  21296. transferer->owner->uniqueid,
  21297. transferer->callid,
  21298. target.chan1->name,
  21299. target.chan1->uniqueid);
  21300. ast_party_connected_line_init(&connected_to_transferee);
  21301. ast_party_connected_line_init(&connected_to_target);
  21302. /* No need to lock current->chan1 here since it was locked in sipsock_read */
  21303. ast_party_connected_line_copy(&connected_to_transferee, &current->chan1->connected);
  21304. /* No need to lock target.chan1 here since it was locked in get_sip_pvt_byid_locked */
  21305. ast_party_connected_line_copy(&connected_to_target, &target.chan1->connected);
  21306. connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
  21307. res = attempt_transfer(current, &target);
  21308. if (res) {
  21309. /* Failed transfer */
  21310. transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
  21311. append_history(transferer, "Xfer", "Refer failed");
  21312. ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
  21313. /* if transfer failed, go ahead and unlock targetcall_pvt and it's owner channel */
  21314. sip_pvt_unlock(targetcall_pvt);
  21315. ast_channel_unlock(target.chan1);
  21316. } else {
  21317. /* Transfer succeeded! */
  21318. const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
  21319. /* target.chan1 was locked in get_sip_pvt_byid_locked, do not unlock target.chan1 before this */
  21320. ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
  21321. /* Tell transferer that we're done. */
  21322. transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
  21323. append_history(transferer, "Xfer", "Refer succeeded");
  21324. transferer->refer->status = REFER_200OK;
  21325. if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
  21326. ast_waitstream(target.chan2, "");
  21327. }
  21328. /* By forcing the masquerade, we know that target.chan1 and target.chan2 are bridged. We then
  21329. * can queue connected line updates where they need to go.
  21330. *
  21331. * before a masquerade, all channel and pvt locks must be unlocked. Any recursive
  21332. * channel locks held before this function invalidates channel container locking order.
  21333. * Since we are unlocking both the pvt (transferer) and its owner channel (current.chan1)
  21334. * it is possible for current.chan1 to be destroyed in the pbx thread. To prevent this
  21335. * we must give c a reference before any unlocking takes place.
  21336. */
  21337. ast_channel_ref(current->chan1);
  21338. ast_channel_unlock(current->chan1); /* current.chan1 is p->owner before the masq, it was locked by socket_read()*/
  21339. ast_channel_unlock(target.chan1);
  21340. *nounlock = 1; /* we just unlocked the dialog's channel and have no plans of locking it again. */
  21341. sip_pvt_unlock(targetcall_pvt);
  21342. sip_pvt_unlock(transferer);
  21343. ast_do_masquerade(target.chan1);
  21344. if (target.chan2) {
  21345. ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
  21346. }
  21347. if (current->chan2 && current->chan2->_state == AST_STATE_RING) {
  21348. ast_indicate(target.chan1, AST_CONTROL_RINGING);
  21349. }
  21350. if (target.chan2) {
  21351. ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
  21352. ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
  21353. } else {
  21354. /* Since target.chan1 isn't actually connected to another channel, there is no way for us
  21355. * to queue a frame so that its connected line status will be updated.
  21356. *
  21357. * Instead, we use the somewhat hackish approach of using a special control frame type that
  21358. * instructs ast_read to perform a specific action. In this case, the frame we queue tells
  21359. * ast_read to call the connected line interception macro configured for target.chan1.
  21360. */
  21361. struct ast_control_read_action_payload *frame_payload;
  21362. int payload_size;
  21363. int frame_size;
  21364. unsigned char connected_line_data[1024];
  21365. payload_size = ast_connected_line_build_data(connected_line_data,
  21366. sizeof(connected_line_data), &connected_to_target, NULL);
  21367. frame_size = payload_size + sizeof(*frame_payload);
  21368. if (payload_size != -1) {
  21369. frame_payload = ast_alloca(frame_size);
  21370. frame_payload->payload_size = payload_size;
  21371. memcpy(frame_payload->payload, connected_line_data, payload_size);
  21372. frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
  21373. ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
  21374. }
  21375. /* In addition to queueing the read action frame so that target.chan1's connected line info
  21376. * will be updated, we also are going to queue a plain old connected line update on target.chan1. This
  21377. * way, either Dial or Queue can apply this connected line update to the outgoing ringing channel.
  21378. */
  21379. ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
  21380. }
  21381. sip_pvt_lock(transferer); /* the transferer pvt is expected to remain locked on return */
  21382. ast_channel_unref(current->chan1);
  21383. }
  21384. /* at this point if the transfer is successful only the transferer pvt should be locked. */
  21385. ast_party_connected_line_free(&connected_to_target);
  21386. ast_party_connected_line_free(&connected_to_transferee);
  21387. ast_channel_unref(target.chan1);
  21388. if (target.chan2) {
  21389. ast_channel_unref(target.chan2);
  21390. }
  21391. if (targetcall_pvt)
  21392. ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
  21393. return 1;
  21394. }
  21395. /*! \brief Handle incoming REFER request */
  21396. /*! \page SIP_REFER SIP transfer Support (REFER)
  21397. REFER is used for call transfer in SIP. We get a REFER
  21398. to place a new call with an INVITE somwhere and then
  21399. keep the transferor up-to-date of the transfer. If the
  21400. transfer fails, get back on line with the orginal call.
  21401. - REFER can be sent outside or inside of a dialog.
  21402. Asterisk only accepts REFER inside of a dialog.
  21403. - If we get a replaces header, it is an attended transfer
  21404. \par Blind transfers
  21405. The transferor provides the transferee
  21406. with the transfer targets contact. The signalling between
  21407. transferer or transferee should not be cancelled, so the
  21408. call is recoverable if the transfer target can not be reached
  21409. by the transferee.
  21410. In this case, Asterisk receives a TRANSFER from
  21411. the transferor, thus is the transferee. We should
  21412. try to set up a call to the contact provided
  21413. and if that fails, re-connect the current session.
  21414. If the new call is set up, we issue a hangup.
  21415. In this scenario, we are following section 5.2
  21416. in the SIP CC Transfer draft. (Transfer without
  21417. a GRUU)
  21418. \par Transfer with consultation hold
  21419. In this case, the transferor
  21420. talks to the transfer target before the transfer takes place.
  21421. This is implemented with SIP hold and transfer.
  21422. Note: The invite From: string could indicate a transfer.
  21423. (Section 6. Transfer with consultation hold)
  21424. The transferor places the transferee on hold, starts a call
  21425. with the transfer target to alert them to the impending
  21426. transfer, terminates the connection with the target, then
  21427. proceeds with the transfer (as in Blind transfer above)
  21428. \par Attended transfer
  21429. The transferor places the transferee
  21430. on hold, calls the transfer target to alert them,
  21431. places the target on hold, then proceeds with the transfer
  21432. using a Replaces header field in the Refer-to header. This
  21433. will force the transfee to send an Invite to the target,
  21434. with a replaces header that instructs the target to
  21435. hangup the call between the transferor and the target.
  21436. In this case, the Refer/to: uses the AOR address. (The same
  21437. URI that the transferee used to establish the session with
  21438. the transfer target (To: ). The Require: replaces header should
  21439. be in the INVITE to avoid the wrong UA in a forked SIP proxy
  21440. scenario to answer and have no call to replace with.
  21441. The referred-by header is *NOT* required, but if we get it,
  21442. can be copied into the INVITE to the transfer target to
  21443. inform the target about the transferor
  21444. "Any REFER request has to be appropriately authenticated.".
  21445. We can't destroy dialogs, since we want the call to continue.
  21446. */
  21447. static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock)
  21448. {
  21449. /*!
  21450. * Chan1: Call between asterisk and transferer
  21451. * Chan2: Call between asterisk and transferee
  21452. */
  21453. struct sip_dual current = { 0, };
  21454. struct ast_channel *chans[2] = { 0, };
  21455. char *refer_to = NULL;
  21456. char *refer_to_domain = NULL;
  21457. char *refer_to_context = NULL;
  21458. char *referred_by = NULL;
  21459. char *callid = NULL;
  21460. int localtransfer = 0;
  21461. int attendedtransfer = 0;
  21462. int res = 0;
  21463. if (req->debug) {
  21464. ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
  21465. p->callid,
  21466. ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
  21467. }
  21468. if (!p->owner) {
  21469. /* This is a REFER outside of an existing SIP dialog */
  21470. /* We can't handle that, so decline it */
  21471. ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
  21472. transmit_response(p, "603 Declined (No dialog)", req);
  21473. if (!req->ignore) {
  21474. append_history(p, "Xfer", "Refer failed. Outside of dialog.");
  21475. sip_alreadygone(p);
  21476. pvt_set_needdestroy(p, "outside of dialog");
  21477. }
  21478. res = 0;
  21479. goto handle_refer_cleanup;
  21480. }
  21481. /* Check if transfer is allowed from this device */
  21482. if (p->allowtransfer == TRANSFER_CLOSED ) {
  21483. /* Transfer not allowed, decline */
  21484. transmit_response(p, "603 Declined (policy)", req);
  21485. append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
  21486. /* Do not destroy SIP session */
  21487. res = 0;
  21488. goto handle_refer_cleanup;
  21489. }
  21490. if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
  21491. /* Already have a pending REFER */
  21492. transmit_response(p, "491 Request pending", req);
  21493. append_history(p, "Xfer", "Refer failed. Request pending.");
  21494. res = 0;
  21495. goto handle_refer_cleanup;
  21496. }
  21497. /* Allocate memory for call transfer data */
  21498. if (!p->refer && !sip_refer_allocate(p)) {
  21499. transmit_response(p, "500 Internal Server Error", req);
  21500. append_history(p, "Xfer", "Refer failed. Memory allocation error.");
  21501. res = -3;
  21502. goto handle_refer_cleanup;
  21503. }
  21504. res = get_refer_info(p, req); /* Extract headers */
  21505. p->refer->status = REFER_SENT;
  21506. if (res != 0) {
  21507. switch (res) {
  21508. case -2: /* Syntax error */
  21509. transmit_response(p, "400 Bad Request (Refer-to missing)", req);
  21510. append_history(p, "Xfer", "Refer failed. Refer-to missing.");
  21511. if (req->debug) {
  21512. ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
  21513. }
  21514. break;
  21515. case -3:
  21516. transmit_response(p, "603 Declined (Non sip: uri)", req);
  21517. append_history(p, "Xfer", "Refer failed. Non SIP uri");
  21518. if (req->debug) {
  21519. ast_debug(1, "SIP transfer to non-SIP uri denied\n");
  21520. }
  21521. break;
  21522. default:
  21523. /* Refer-to extension not found, fake a failed transfer */
  21524. transmit_response(p, "202 Accepted", req);
  21525. append_history(p, "Xfer", "Refer failed. Bad extension.");
  21526. transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
  21527. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  21528. if (req->debug) {
  21529. ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
  21530. }
  21531. break;
  21532. }
  21533. res = 0;
  21534. goto handle_refer_cleanup;
  21535. }
  21536. if (ast_strlen_zero(p->context)) {
  21537. ast_string_field_set(p, context, sip_cfg.default_context);
  21538. }
  21539. /* If we do not support SIP domains, all transfers are local */
  21540. if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
  21541. p->refer->localtransfer = 1;
  21542. if (sipdebug) {
  21543. ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
  21544. }
  21545. } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
  21546. /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
  21547. p->refer->localtransfer = 1;
  21548. } else if (sipdebug) {
  21549. ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
  21550. }
  21551. /* Is this a repeat of a current request? Ignore it */
  21552. /* Don't know what else to do right now. */
  21553. if (req->ignore) {
  21554. goto handle_refer_cleanup;
  21555. }
  21556. /* If this is a blind transfer, we have the following
  21557. channels to work with:
  21558. - chan1, chan2: The current call between transferer and transferee (2 channels)
  21559. - target_channel: A new call from the transferee to the target (1 channel)
  21560. We need to stay tuned to what happens in order to be able
  21561. to bring back the call to the transferer */
  21562. /* If this is a attended transfer, we should have all call legs within reach:
  21563. - chan1, chan2: The call between the transferer and transferee (2 channels)
  21564. - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
  21565. We want to bridge chan2 with targetcall_pvt!
  21566. The replaces call id in the refer message points
  21567. to the call leg between Asterisk and the transferer.
  21568. So we need to connect the target and the transferee channel
  21569. and hangup the two other channels silently
  21570. If the target is non-local, the call ID could be on a remote
  21571. machine and we need to send an INVITE with replaces to the
  21572. target. We basically handle this as a blind transfer
  21573. and let the sip_call function catch that we need replaces
  21574. header in the INVITE.
  21575. */
  21576. /* Get the transferer's channel */
  21577. chans[0] = current.chan1 = p->owner;
  21578. /* Find the other part of the bridge (2) - transferee */
  21579. chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
  21580. ast_channel_ref(current.chan1);
  21581. if (current.chan2) {
  21582. ast_channel_ref(current.chan2);
  21583. }
  21584. if (sipdebug) {
  21585. ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
  21586. p->refer->attendedtransfer ? "attended" : "blind",
  21587. current.chan1->name,
  21588. current.chan2 ? current.chan2->name : "<none>");
  21589. }
  21590. if (!current.chan2 && !p->refer->attendedtransfer) {
  21591. /* No bridged channel, propably IVR or echo or similar... */
  21592. /* Guess we should masquerade or something here */
  21593. /* Until we figure it out, refuse transfer of such calls */
  21594. if (sipdebug) {
  21595. ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
  21596. }
  21597. p->refer->status = REFER_FAILED;
  21598. append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
  21599. transmit_response(p, "603 Declined", req);
  21600. res = -1;
  21601. goto handle_refer_cleanup;
  21602. }
  21603. if (current.chan2) {
  21604. if (sipdebug) {
  21605. ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
  21606. }
  21607. ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
  21608. }
  21609. ast_set_flag(&p->flags[0], SIP_GOTREFER);
  21610. /* From here on failures will be indicated with NOTIFY requests */
  21611. transmit_response(p, "202 Accepted", req);
  21612. /* Attended transfer: Find all call legs and bridge transferee with target*/
  21613. if (p->refer->attendedtransfer) {
  21614. /* both p and p->owner _MUST_ be locked while calling local_attended_transfer */
  21615. if ((res = local_attended_transfer(p, &current, req, seqno, nounlock))) {
  21616. goto handle_refer_cleanup; /* We're done with the transfer */
  21617. }
  21618. /* Fall through for remote transfers that we did not find locally */
  21619. if (sipdebug) {
  21620. ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
  21621. }
  21622. /* Fallthrough if we can't find the call leg internally */
  21623. }
  21624. /* Copy data we can not safely access after letting the pvt lock go. */
  21625. refer_to = ast_strdupa(p->refer->refer_to);
  21626. refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
  21627. refer_to_context = ast_strdupa(p->refer->refer_to_context);
  21628. referred_by = ast_strdupa(p->refer->referred_by);
  21629. callid = ast_strdupa(p->callid);
  21630. localtransfer = p->refer->localtransfer;
  21631. attendedtransfer = p->refer->attendedtransfer;
  21632. if (!*nounlock) {
  21633. ast_channel_unlock(p->owner);
  21634. *nounlock = 1;
  21635. }
  21636. sip_pvt_unlock(p);
  21637. /* Parking a call. DO NOT hold any locks while calling ast_parking_ext_valid() */
  21638. if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, refer_to_context)) {
  21639. sip_pvt_lock(p);
  21640. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  21641. p->refer->status = REFER_200OK;
  21642. append_history(p, "Xfer", "REFER to call parking.");
  21643. sip_pvt_unlock(p);
  21644. ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
  21645. "TransferMethod: SIP\r\n"
  21646. "TransferType: Blind\r\n"
  21647. "Channel: %s\r\n"
  21648. "Uniqueid: %s\r\n"
  21649. "SIP-Callid: %s\r\n"
  21650. "TargetChannel: %s\r\n"
  21651. "TargetUniqueid: %s\r\n"
  21652. "TransferExten: %s\r\n"
  21653. "Transfer2Parking: Yes\r\n",
  21654. current.chan1->name,
  21655. current.chan1->uniqueid,
  21656. callid,
  21657. current.chan2->name,
  21658. current.chan2->uniqueid,
  21659. refer_to);
  21660. if (sipdebug) {
  21661. ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
  21662. }
  21663. /* DO NOT hold any locks while calling sip_park */
  21664. if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, refer_to_context)) {
  21665. sip_pvt_lock(p);
  21666. transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
  21667. } else {
  21668. sip_pvt_lock(p);
  21669. }
  21670. goto handle_refer_cleanup;
  21671. }
  21672. /* Blind transfers and remote attended xfers.
  21673. * Locks should not be held while calling pbx_builtin_setvar_helper. This function
  21674. * locks the channel being passed into it.*/
  21675. if (current.chan1 && current.chan2) {
  21676. ast_debug(3, "chan1->name: %s\n", current.chan1->name);
  21677. pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
  21678. }
  21679. if (current.chan2) {
  21680. pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
  21681. pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
  21682. pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
  21683. /* One for the new channel */
  21684. pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
  21685. /* Attended transfer to remote host, prepare headers for the INVITE */
  21686. if (!ast_strlen_zero(referred_by)) {
  21687. pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
  21688. }
  21689. }
  21690. sip_pvt_lock(p);
  21691. /* Generate a Replaces string to be used in the INVITE during attended transfer */
  21692. if (!ast_strlen_zero(p->refer->replaces_callid)) {
  21693. char tempheader[SIPBUFSIZE];
  21694. snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
  21695. p->refer->replaces_callid_totag ? ";to-tag=" : "",
  21696. p->refer->replaces_callid_totag,
  21697. p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
  21698. p->refer->replaces_callid_fromtag);
  21699. if (current.chan2) {
  21700. sip_pvt_unlock(p);
  21701. pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
  21702. sip_pvt_lock(p);
  21703. }
  21704. }
  21705. /* Connect the call */
  21706. /* FAKE ringing if not attended transfer */
  21707. if (!p->refer->attendedtransfer) {
  21708. transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
  21709. }
  21710. /* For blind transfer, this will lead to a new call */
  21711. /* For attended transfer to remote host, this will lead to
  21712. a new SIP call with a replaces header, if the dial plan allows it
  21713. */
  21714. if (!current.chan2) {
  21715. /* We have no bridge, so we're talking with Asterisk somehow */
  21716. /* We need to masquerade this call */
  21717. /* What to do to fix this situation:
  21718. * Set up the new call in a new channel
  21719. * Let the new channel masq into this channel
  21720. Please add that code here :-)
  21721. */
  21722. p->refer->status = REFER_FAILED;
  21723. transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
  21724. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  21725. append_history(p, "Xfer", "Refer failed (only bridged calls).");
  21726. res = -1;
  21727. goto handle_refer_cleanup;
  21728. }
  21729. ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
  21730. /* Do not hold the pvt lock during the indicate and async_goto. Those functions
  21731. * lock channels which will invalidate locking order if the pvt lock is held.*/
  21732. /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
  21733. * servers - generate an INVITE with Replaces. Either way, let the dial plan decided
  21734. * indicate before masquerade so the indication actually makes it to the real channel
  21735. * when using local channels with MOH passthru */
  21736. sip_pvt_unlock(p);
  21737. ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
  21738. res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
  21739. if (!res) {
  21740. ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
  21741. "TransferMethod: SIP\r\n"
  21742. "TransferType: Blind\r\n"
  21743. "Channel: %s\r\n"
  21744. "Uniqueid: %s\r\n"
  21745. "SIP-Callid: %s\r\n"
  21746. "TargetChannel: %s\r\n"
  21747. "TargetUniqueid: %s\r\n"
  21748. "TransferExten: %s\r\n"
  21749. "TransferContext: %s\r\n",
  21750. current.chan1->name,
  21751. current.chan1->uniqueid,
  21752. callid,
  21753. current.chan2->name,
  21754. current.chan2->uniqueid,
  21755. refer_to,
  21756. refer_to_context);
  21757. /* Success - we have a new channel */
  21758. ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
  21759. /* XXX - what to we put in CEL 'extra' for attended transfers to external systems? NULL for now */
  21760. ast_channel_lock(current.chan1);
  21761. ast_cel_report_event(current.chan1, p->refer->attendedtransfer? AST_CEL_ATTENDEDTRANSFER : AST_CEL_BLINDTRANSFER, NULL, p->refer->attendedtransfer ? NULL : p->refer->refer_to, current.chan2);
  21762. ast_channel_unlock(current.chan1);
  21763. sip_pvt_lock(p);
  21764. transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
  21765. if (p->refer->localtransfer) {
  21766. p->refer->status = REFER_200OK;
  21767. }
  21768. if (p->owner) {
  21769. p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
  21770. }
  21771. append_history(p, "Xfer", "Refer succeeded.");
  21772. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  21773. /* Do not hangup call, the other side do that when we say 200 OK */
  21774. /* We could possibly implement a timer here, auto congestion */
  21775. res = 0;
  21776. } else {
  21777. sip_pvt_lock(p);
  21778. ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
  21779. ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
  21780. append_history(p, "Xfer", "Refer failed.");
  21781. /* Failure of some kind */
  21782. p->refer->status = REFER_FAILED;
  21783. transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
  21784. ast_clear_flag(&p->flags[0], SIP_GOTREFER);
  21785. res = -1;
  21786. }
  21787. handle_refer_cleanup:
  21788. if (current.chan1) {
  21789. ast_channel_unref(current.chan1);
  21790. }
  21791. if (current.chan2) {
  21792. ast_channel_unref(current.chan2);
  21793. }
  21794. /* Make sure we exit with the pvt locked */
  21795. return res;
  21796. }
  21797. /*! \brief Handle incoming CANCEL request */
  21798. static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
  21799. {
  21800. check_via(p, req);
  21801. sip_alreadygone(p);
  21802. if (p->owner && p->owner->_state == AST_STATE_UP) {
  21803. /* This call is up, cancel is ignored, we need a bye */
  21804. transmit_response(p, "200 OK", req);
  21805. ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
  21806. return 0;
  21807. }
  21808. /* At this point, we could have cancelled the invite at the same time
  21809. as the other side sends a CANCEL. Our final reply with error code
  21810. might not have been received by the other side before the CANCEL
  21811. was sent, so let's just give up retransmissions and waiting for
  21812. ACK on our error code. The call is hanging up any way. */
  21813. if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
  21814. __sip_pretend_ack(p);
  21815. }
  21816. if (p->invitestate != INV_TERMINATED)
  21817. p->invitestate = INV_CANCELLED;
  21818. if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
  21819. update_call_counter(p, DEC_CALL_LIMIT);
  21820. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  21821. if (p->owner) {
  21822. sip_queue_hangup_cause(p, 0);
  21823. } else {
  21824. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  21825. }
  21826. if (ast_str_strlen(p->initreq.data) > 0) {
  21827. struct sip_pkt *pkt, *prev_pkt;
  21828. /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
  21829. * a reliable 487, then we don't want to schedule another one on top of the previous
  21830. * one.
  21831. *
  21832. * As odd as this may sound, we can't rely on the previously-transmitted "reliable"
  21833. * response in this situation. What if we've sent all of our reliable responses
  21834. * already and now all of a sudden, we get this second CANCEL?
  21835. *
  21836. * The only way to do this correctly is to cancel our previously-scheduled reliably-
  21837. * transmitted response and send a new one in its place.
  21838. */
  21839. for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
  21840. if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
  21841. AST_SCHED_DEL(sched, pkt->retransid);
  21842. UNLINK(pkt, p->packets, prev_pkt);
  21843. dialog_unref(pkt->owner, "unref packet->owner from dialog");
  21844. if (pkt->data) {
  21845. ast_free(pkt->data);
  21846. }
  21847. ast_free(pkt);
  21848. break;
  21849. }
  21850. }
  21851. transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
  21852. transmit_response(p, "200 OK", req);
  21853. return 1;
  21854. } else {
  21855. transmit_response(p, "481 Call Leg Does Not Exist", req);
  21856. return 0;
  21857. }
  21858. }
  21859. /*! \brief Handle incoming BYE request */
  21860. static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
  21861. {
  21862. struct ast_channel *c=NULL;
  21863. int res;
  21864. struct ast_channel *bridged_to;
  21865. const char *required;
  21866. /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
  21867. if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
  21868. transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
  21869. }
  21870. __sip_pretend_ack(p);
  21871. p->invitestate = INV_TERMINATED;
  21872. copy_request(&p->initreq, req);
  21873. if (sipdebug)
  21874. ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  21875. check_via(p, req);
  21876. sip_alreadygone(p);
  21877. /* Get RTCP quality before end of call */
  21878. if (p->do_history || p->owner) {
  21879. char quality_buf[AST_MAX_USER_FIELD], *quality;
  21880. struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
  21881. /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
  21882. * to lock the bridge. This may get hairy...
  21883. */
  21884. while (bridge && ast_channel_trylock(bridge)) {
  21885. ast_channel_unlock(p->owner);
  21886. do {
  21887. /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
  21888. sip_pvt_unlock(p);
  21889. usleep(1);
  21890. sip_pvt_lock(p);
  21891. } while (p->owner && ast_channel_trylock(p->owner));
  21892. bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
  21893. }
  21894. if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  21895. if (p->do_history) {
  21896. append_history(p, "RTCPaudio", "Quality:%s", quality);
  21897. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
  21898. append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
  21899. }
  21900. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
  21901. append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
  21902. }
  21903. if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
  21904. append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
  21905. }
  21906. }
  21907. if (p->owner) {
  21908. ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
  21909. }
  21910. }
  21911. if (bridge) {
  21912. struct sip_pvt *q = bridge->tech_pvt;
  21913. if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
  21914. ast_rtp_instance_set_stats_vars(bridge, q->rtp);
  21915. }
  21916. ast_channel_unlock(bridge);
  21917. }
  21918. if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  21919. if (p->do_history) {
  21920. append_history(p, "RTCPvideo", "Quality:%s", quality);
  21921. }
  21922. if (p->owner) {
  21923. pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
  21924. }
  21925. }
  21926. if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
  21927. if (p->do_history) {
  21928. append_history(p, "RTCPtext", "Quality:%s", quality);
  21929. }
  21930. if (p->owner) {
  21931. pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
  21932. }
  21933. }
  21934. }
  21935. stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
  21936. if (p->stimer) {
  21937. stop_session_timer(p); /* Stop Session-Timer */
  21938. }
  21939. if (!ast_strlen_zero(get_header(req, "Also"))) {
  21940. ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
  21941. ast_sockaddr_stringify(&p->recv));
  21942. if (ast_strlen_zero(p->context))
  21943. ast_string_field_set(p, context, sip_cfg.default_context);
  21944. res = get_also_info(p, req);
  21945. if (!res) {
  21946. c = p->owner;
  21947. if (c) {
  21948. bridged_to = ast_bridged_channel(c);
  21949. if (bridged_to) {
  21950. /* Don't actually hangup here... */
  21951. ast_queue_control(c, AST_CONTROL_UNHOLD);
  21952. ast_channel_unlock(c); /* async_goto can do a masquerade, no locks can be held during a masq */
  21953. ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
  21954. ast_channel_lock(c);
  21955. } else
  21956. ast_queue_hangup(p->owner);
  21957. }
  21958. } else {
  21959. ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
  21960. if (p->owner)
  21961. ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
  21962. }
  21963. } else if (p->owner) {
  21964. sip_queue_hangup_cause(p, 0);
  21965. sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
  21966. ast_debug(3, "Received bye, issuing owner hangup\n");
  21967. } else {
  21968. sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
  21969. ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
  21970. }
  21971. ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  21972. /* Find out what they require */
  21973. required = get_header(req, "Require");
  21974. if (!ast_strlen_zero(required)) {
  21975. char unsupported[256] = { 0, };
  21976. parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
  21977. /* If there are any options required that we do not support,
  21978. * then send a 420 with only those unsupported options listed */
  21979. if (!ast_strlen_zero(unsupported)) {
  21980. transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
  21981. ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
  21982. } else {
  21983. transmit_response(p, "200 OK", req);
  21984. }
  21985. } else {
  21986. transmit_response(p, "200 OK", req);
  21987. }
  21988. /* Destroy any pending invites so we won't try to do another
  21989. * scheduled reINVITE. */
  21990. AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "decrement refcount from sip_destroy because waitid won't be scheduled"));
  21991. return 1;
  21992. }
  21993. /*! \brief Handle incoming MESSAGE request */
  21994. static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
  21995. {
  21996. if (!req->ignore) {
  21997. if (req->debug)
  21998. ast_verbose("Receiving message!\n");
  21999. receive_message(p, req);
  22000. } else
  22001. transmit_response(p, "202 Accepted", req);
  22002. return 1;
  22003. }
  22004. 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)
  22005. {
  22006. int etag_present = !ast_strlen_zero(etag);
  22007. int body_present = req->lines > 0;
  22008. ast_assert(expires_int != NULL);
  22009. if (ast_strlen_zero(expires)) {
  22010. /* Section 6, item 4, second bullet point of RFC 3903 says to
  22011. * use a locally-configured default expiration if none is provided
  22012. * in the request
  22013. */
  22014. *expires_int = DEFAULT_PUBLISH_EXPIRES;
  22015. } else if (sscanf(expires, "%30d", expires_int) != 1) {
  22016. return SIP_PUBLISH_UNKNOWN;
  22017. }
  22018. if (*expires_int == 0) {
  22019. return SIP_PUBLISH_REMOVE;
  22020. } else if (!etag_present && body_present) {
  22021. return SIP_PUBLISH_INITIAL;
  22022. } else if (etag_present && !body_present) {
  22023. return SIP_PUBLISH_REFRESH;
  22024. } else if (etag_present && body_present) {
  22025. return SIP_PUBLISH_MODIFY;
  22026. }
  22027. return SIP_PUBLISH_UNKNOWN;
  22028. }
  22029. #ifdef HAVE_LIBXML2
  22030. static void get_pidf_body(struct sip_request *req, char *pidf_body, size_t size)
  22031. {
  22032. int i;
  22033. struct ast_str *str = ast_str_alloca(size);
  22034. for (i = 0; i < req->lines; ++i) {
  22035. ast_str_append(&str, 0, "%s", REQ_OFFSET_TO_STR(req, line[i]));
  22036. }
  22037. ast_copy_string(pidf_body, ast_str_buffer(str), size);
  22038. }
  22039. static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
  22040. {
  22041. const char *id;
  22042. int status_found = FALSE;
  22043. struct ast_xml_node *tuple_children;
  22044. struct ast_xml_node *tuple_children_iterator;
  22045. /* Tuples have to have an id attribute or they're invalid */
  22046. if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
  22047. ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
  22048. return FALSE;
  22049. }
  22050. /* We don't care what it actually is, just that it's there */
  22051. ast_xml_free_attr(id);
  22052. /* This is a tuple. It must have a status element */
  22053. if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
  22054. /* The tuple has no children. It sucks */
  22055. ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
  22056. return FALSE;
  22057. }
  22058. for (tuple_children_iterator = tuple_children; tuple_children_iterator;
  22059. tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
  22060. /* Similar to the wording used regarding tuples, the status element should appear
  22061. * first. However, we will once again relax things and accept the status at any
  22062. * position. We will enforce that only a single status element can be present.
  22063. */
  22064. if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
  22065. /* Not the status, we don't care */
  22066. continue;
  22067. }
  22068. if (status_found == TRUE) {
  22069. /* THERE CAN BE ONLY ONE!!! */
  22070. ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
  22071. return FALSE;
  22072. }
  22073. status_found = TRUE;
  22074. }
  22075. return status_found;
  22076. }
  22077. static int pidf_validate_presence(struct ast_xml_doc *doc)
  22078. {
  22079. struct ast_xml_node *presence_node = ast_xml_get_root(doc);
  22080. struct ast_xml_node *child_nodes;
  22081. struct ast_xml_node *node_iterator;
  22082. struct ast_xml_ns *ns;
  22083. const char *entity;
  22084. const char *namespace;
  22085. const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
  22086. if (!presence_node) {
  22087. ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
  22088. return FALSE;
  22089. }
  22090. /* Okay, we managed to open the document! YAY! Now, let's start making sure it's all PIDF-ified
  22091. * correctly.
  22092. */
  22093. if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
  22094. ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
  22095. return FALSE;
  22096. }
  22097. /* The presence element must have an entity attribute and an xmlns attribute. Furthermore
  22098. * the xmlns attribute must be "urn:ietf:params:xml:ns:pidf"
  22099. */
  22100. if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
  22101. ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
  22102. return FALSE;
  22103. }
  22104. /* We're not interested in what the entity is, just that it exists */
  22105. ast_xml_free_attr(entity);
  22106. if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
  22107. ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
  22108. return FALSE;
  22109. }
  22110. namespace = ast_xml_get_ns_href(ns);
  22111. if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
  22112. ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
  22113. return FALSE;
  22114. }
  22115. if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
  22116. ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
  22117. return FALSE;
  22118. }
  22119. /* Check for tuple elements. RFC 3863 says that PIDF documents can have any number of
  22120. * tuples, including 0. The big thing here is that if there are tuple elements present,
  22121. * they have to have a single status element within.
  22122. *
  22123. * The RFC is worded such that tuples should appear as the first elements as children of
  22124. * the presence element. However, we'll be accepting of documents which may place other elements
  22125. * before the tuple(s).
  22126. */
  22127. for (node_iterator = child_nodes; node_iterator;
  22128. node_iterator = ast_xml_node_get_next(node_iterator)) {
  22129. if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
  22130. /* Not a tuple. We don't give a rat's hind quarters */
  22131. continue;
  22132. }
  22133. if (pidf_validate_tuple(node_iterator) == FALSE) {
  22134. ast_log(LOG_WARNING, "Unable to validate tuple\n");
  22135. return FALSE;
  22136. }
  22137. }
  22138. return TRUE;
  22139. }
  22140. /*!
  22141. * \brief Makes sure that body is properly formatted PIDF
  22142. *
  22143. * Specifically, we check that the document has a "presence" element
  22144. * at the root and that within that, there is at least one "tuple" element
  22145. * that contains a "status" element.
  22146. *
  22147. * XXX This function currently assumes a default namespace is used. Of course
  22148. * if you're not using a default namespace, you're probably a stupid jerk anyway.
  22149. *
  22150. * \param req The SIP request to check
  22151. * \param[out] pidf_doc The validated PIDF doc.
  22152. * \retval FALSE The XML was malformed or the basic PIDF structure was marred
  22153. * \retval TRUE The PIDF document is of a valid format
  22154. */
  22155. static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
  22156. {
  22157. struct ast_xml_doc *doc;
  22158. int content_length;
  22159. const char *content_length_str = get_header(req, "Content-Length");
  22160. const char *content_type = get_header(req, "Content-Type");
  22161. char pidf_body[SIPBUFSIZE];
  22162. int res;
  22163. if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
  22164. ast_log(LOG_WARNING, "Content type is not PIDF\n");
  22165. return FALSE;
  22166. }
  22167. if (ast_strlen_zero(content_length_str)) {
  22168. ast_log(LOG_WARNING, "No content length. Can't determine bounds of PIDF document\n");
  22169. return FALSE;
  22170. }
  22171. if (sscanf(content_length_str, "%30d", &content_length) != 1) {
  22172. ast_log(LOG_WARNING, "Invalid content length provided\n");
  22173. return FALSE;
  22174. }
  22175. if (content_length > sizeof(pidf_body)) {
  22176. ast_log(LOG_WARNING, "Content length of PIDF document truncated to %d bytes\n", (int) sizeof(pidf_body));
  22177. content_length = sizeof(pidf_body);
  22178. }
  22179. get_pidf_body(req, pidf_body, content_length);
  22180. if (!(doc = ast_xml_read_memory(pidf_body, content_length))) {
  22181. ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
  22182. return FALSE;
  22183. }
  22184. res = pidf_validate_presence(doc);
  22185. if (res == TRUE) {
  22186. *pidf_doc = doc;
  22187. } else {
  22188. ast_xml_close(doc);
  22189. }
  22190. return res;
  22191. }
  22192. 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)
  22193. {
  22194. const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
  22195. struct ast_cc_agent *agent;
  22196. struct sip_cc_agent_pvt *agent_pvt;
  22197. struct ast_xml_doc *pidf_doc = NULL;
  22198. const char *basic_status = NULL;
  22199. struct ast_xml_node *presence_node;
  22200. struct ast_xml_node *presence_children;
  22201. struct ast_xml_node *tuple_node;
  22202. struct ast_xml_node *tuple_children;
  22203. struct ast_xml_node *status_node;
  22204. struct ast_xml_node *status_children;
  22205. struct ast_xml_node *basic_node;
  22206. int res = 0;
  22207. if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
  22208. ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
  22209. transmit_response(pvt, "412 Conditional Request Failed", req);
  22210. return -1;
  22211. }
  22212. agent_pvt = agent->private_data;
  22213. if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
  22214. res = -1;
  22215. goto cc_publish_cleanup;
  22216. }
  22217. /* It's important to note that the PIDF validation routine has no knowledge
  22218. * of what we specifically want in this instance. A valid PIDF document could
  22219. * have no tuples, or it could have tuples whose status element has no basic
  22220. * element contained within. While not violating the PIDF spec, these are
  22221. * insufficient for our needs in this situation
  22222. */
  22223. presence_node = ast_xml_get_root(pidf_doc);
  22224. if (!(presence_children = ast_xml_node_get_children(presence_node))) {
  22225. ast_log(LOG_WARNING, "No tuples within presence element.\n");
  22226. res = -1;
  22227. goto cc_publish_cleanup;
  22228. }
  22229. if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
  22230. ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
  22231. res = -1;
  22232. goto cc_publish_cleanup;
  22233. }
  22234. /* We already made sure that the tuple has a status node when we validated the PIDF
  22235. * document earlier. So there's no need to enclose this operation in an if statement.
  22236. */
  22237. tuple_children = ast_xml_node_get_children(tuple_node);
  22238. /* coverity[null_returns: FALSE] */
  22239. status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
  22240. if (!(status_children = ast_xml_node_get_children(status_node))) {
  22241. ast_log(LOG_WARNING, "No basic elements within status element.\n");
  22242. res = -1;
  22243. goto cc_publish_cleanup;
  22244. }
  22245. if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
  22246. ast_log(LOG_WARNING, "Couldn't find basic node?\n");
  22247. res = -1;
  22248. goto cc_publish_cleanup;
  22249. }
  22250. basic_status = ast_xml_get_text(basic_node);
  22251. if (ast_strlen_zero(basic_status)) {
  22252. ast_log(LOG_NOTICE, "NOthing in basic node?\n");
  22253. res = -1;
  22254. goto cc_publish_cleanup;
  22255. }
  22256. if (!strcmp(basic_status, "open")) {
  22257. agent_pvt->is_available = TRUE;
  22258. ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
  22259. agent->device_name);
  22260. } else if (!strcmp(basic_status, "closed")) {
  22261. agent_pvt->is_available = FALSE;
  22262. ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
  22263. agent->device_name);
  22264. } else {
  22265. ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
  22266. }
  22267. cc_publish_cleanup:
  22268. if (basic_status) {
  22269. ast_xml_free_text(basic_status);
  22270. }
  22271. if (pidf_doc) {
  22272. ast_xml_close(pidf_doc);
  22273. }
  22274. ao2_ref(agent, -1);
  22275. if (res) {
  22276. transmit_response(pvt, "400 Bad Request", req);
  22277. }
  22278. return res;
  22279. }
  22280. #endif /* HAVE_LIBXML2 */
  22281. static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
  22282. {
  22283. struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
  22284. int res = 0;
  22285. if (!esc_entry) {
  22286. transmit_response(p, "503 Internal Server Failure", req);
  22287. return -1;
  22288. }
  22289. if (esc->callbacks->initial_handler) {
  22290. res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
  22291. }
  22292. if (!res) {
  22293. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
  22294. }
  22295. ao2_ref(esc_entry, -1);
  22296. return res;
  22297. }
  22298. 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)
  22299. {
  22300. struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
  22301. int expires_ms = expires * 1000;
  22302. int res = 0;
  22303. if (!esc_entry) {
  22304. transmit_response(p, "412 Conditional Request Failed", req);
  22305. return -1;
  22306. }
  22307. AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
  22308. ao2_ref(_data, -1),
  22309. ao2_ref(esc_entry, -1),
  22310. ao2_ref(esc_entry, +1));
  22311. if (esc->callbacks->refresh_handler) {
  22312. res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
  22313. }
  22314. if (!res) {
  22315. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
  22316. }
  22317. ao2_ref(esc_entry, -1);
  22318. return res;
  22319. }
  22320. 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)
  22321. {
  22322. struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
  22323. int expires_ms = expires * 1000;
  22324. int res = 0;
  22325. if (!esc_entry) {
  22326. transmit_response(p, "412 Conditional Request Failed", req);
  22327. return -1;
  22328. }
  22329. AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
  22330. ao2_ref(_data, -1),
  22331. ao2_ref(esc_entry, -1),
  22332. ao2_ref(esc_entry, +1));
  22333. if (esc->callbacks->modify_handler) {
  22334. res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
  22335. }
  22336. if (!res) {
  22337. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
  22338. }
  22339. ao2_ref(esc_entry, -1);
  22340. return res;
  22341. }
  22342. static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
  22343. {
  22344. struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
  22345. int res = 0;
  22346. if (!esc_entry) {
  22347. transmit_response(p, "412 Conditional Request Failed", req);
  22348. return -1;
  22349. }
  22350. AST_SCHED_DEL(sched, esc_entry->sched_id);
  22351. /* Scheduler's ref of the esc_entry */
  22352. ao2_ref(esc_entry, -1);
  22353. if (esc->callbacks->remove_handler) {
  22354. res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
  22355. }
  22356. if (!res) {
  22357. transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
  22358. }
  22359. /* Ref from finding the esc_entry earlier in function */
  22360. ao2_unlink(esc->compositor, esc_entry);
  22361. ao2_ref(esc_entry, -1);
  22362. return res;
  22363. }
  22364. static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
  22365. {
  22366. const char *etag = get_header(req, "SIP-If-Match");
  22367. const char *event = get_header(req, "Event");
  22368. struct event_state_compositor *esc;
  22369. enum sip_publish_type publish_type;
  22370. const char *expires_str = get_header(req, "Expires");
  22371. int expires_int;
  22372. int auth_result;
  22373. int handler_result = -1;
  22374. if (ast_strlen_zero(event)) {
  22375. transmit_response(p, "489 Bad Event", req);
  22376. pvt_set_needdestroy(p, "missing Event: header");
  22377. return -1;
  22378. }
  22379. if (!(esc = get_esc(event))) {
  22380. transmit_response(p, "489 Bad Event", req);
  22381. pvt_set_needdestroy(p, "unknown event package in publish");
  22382. return -1;
  22383. }
  22384. auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_UNRELIABLE, addr);
  22385. if (auth_result == AUTH_CHALLENGE_SENT) {
  22386. p->lastinvite = seqno;
  22387. return 0;
  22388. } else if (auth_result < 0) {
  22389. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
  22390. transmit_response(p, "403 Forbidden", req);
  22391. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22392. ast_string_field_set(p, theirtag, NULL);
  22393. return 0;
  22394. } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
  22395. /* We need to stop retransmitting the 401 */
  22396. __sip_ack(p, p->lastinvite, 1, 0);
  22397. }
  22398. publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
  22399. if (expires_int > max_expiry) {
  22400. expires_int = max_expiry;
  22401. } else if (expires_int < min_expiry && expires_int > 0) {
  22402. transmit_response_with_minexpires(p, "423 Interval too small", req);
  22403. pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
  22404. return 0;
  22405. }
  22406. p->expiry = expires_int;
  22407. /* It is the responsibility of these handlers to formulate any response
  22408. * sent for a PUBLISH
  22409. */
  22410. switch (publish_type) {
  22411. case SIP_PUBLISH_UNKNOWN:
  22412. transmit_response(p, "400 Bad Request", req);
  22413. break;
  22414. case SIP_PUBLISH_INITIAL:
  22415. handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
  22416. break;
  22417. case SIP_PUBLISH_REFRESH:
  22418. handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
  22419. break;
  22420. case SIP_PUBLISH_MODIFY:
  22421. handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
  22422. break;
  22423. case SIP_PUBLISH_REMOVE:
  22424. handler_result = handle_sip_publish_remove(p, req, esc, etag);
  22425. break;
  22426. default:
  22427. transmit_response(p, "400 Impossible Condition", req);
  22428. break;
  22429. }
  22430. if (!handler_result && p->expiry > 0) {
  22431. sip_scheddestroy(p, (p->expiry + 10) * 1000);
  22432. } else {
  22433. pvt_set_needdestroy(p, "forcing expiration");
  22434. }
  22435. return handler_result;
  22436. }
  22437. /*! \internal \brief Subscribe to MWI events for the specified peer
  22438. * \note The peer cannot be locked during this method. sip_send_mwi_peer will
  22439. * attempt to lock the peer after the event subscription lock is held; if the peer is locked during
  22440. * this method then we will attempt to lock the event subscription lock but after the peer, creating
  22441. * a locking inversion.
  22442. */
  22443. static void add_peer_mwi_subs(struct sip_peer *peer)
  22444. {
  22445. struct sip_mailbox *mailbox;
  22446. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  22447. if (mailbox->event_sub) {
  22448. ast_event_unsubscribe(mailbox->event_sub);
  22449. }
  22450. mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
  22451. AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
  22452. AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
  22453. AST_EVENT_IE_END);
  22454. }
  22455. }
  22456. static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
  22457. {
  22458. const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
  22459. char *param_separator;
  22460. struct ast_cc_agent *agent;
  22461. struct sip_cc_agent_pvt *agent_pvt;
  22462. const char *expires_str = get_header(req, "Expires");
  22463. int expires = -1; /* Just need it to be non-zero */
  22464. if (!ast_strlen_zero(expires_str)) {
  22465. sscanf(expires_str, "%d", &expires);
  22466. }
  22467. if ((param_separator = strchr(uri, ';'))) {
  22468. *param_separator = '\0';
  22469. }
  22470. p->subscribed = CALL_COMPLETION;
  22471. if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
  22472. if (!expires) {
  22473. /* Typically, if a 0 Expires reaches us and we can't find
  22474. * the corresponding agent, it means that the CC transaction
  22475. * has completed and so the calling side is just trying to
  22476. * clean up its subscription. We'll just respond with a
  22477. * 200 OK and be done with it
  22478. */
  22479. transmit_response(p, "200 OK", req);
  22480. return 0;
  22481. }
  22482. ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
  22483. transmit_response(p, "404 Not Found", req);
  22484. return -1;
  22485. }
  22486. agent_pvt = agent->private_data;
  22487. if (!expires) {
  22488. /* We got sent a SUBSCRIBE and found an agent. This means that CC
  22489. * is being canceled.
  22490. */
  22491. ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
  22492. transmit_response(p, "200 OK", req);
  22493. ao2_ref(agent, -1);
  22494. return 0;
  22495. }
  22496. agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
  22497. ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
  22498. agent->device_name);
  22499. /* We don't send a response here. That is done in the agent's ack callback or in the
  22500. * agent destructor, should a failure occur before we have responded
  22501. */
  22502. ao2_ref(agent, -1);
  22503. return 0;
  22504. }
  22505. /*! \brief Handle incoming SUBSCRIBE request */
  22506. static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
  22507. {
  22508. int gotdest = 0;
  22509. int res = 0;
  22510. int firststate;
  22511. struct sip_peer *authpeer = NULL;
  22512. const char *eventheader = get_header(req, "Event"); /* Get Event package name */
  22513. int resubscribe = (p->subscribed != NONE) && !req->ignore;
  22514. char *event_end;
  22515. ptrdiff_t event_len = 0;
  22516. if (p->initreq.headers) {
  22517. /* We already have a dialog */
  22518. if (p->initreq.method != SIP_SUBSCRIBE) {
  22519. /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
  22520. /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
  22521. transmit_response(p, "403 Forbidden (within dialog)", req);
  22522. /* Do not destroy session, since we will break the call if we do */
  22523. 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);
  22524. return 0;
  22525. } else if (req->debug) {
  22526. if (resubscribe)
  22527. ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
  22528. else
  22529. ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
  22530. }
  22531. }
  22532. /* Check if we have a global disallow setting on subscriptions.
  22533. if so, we don't have to check peer settings after auth, which saves a lot of processing
  22534. */
  22535. if (!sip_cfg.allowsubscribe) {
  22536. transmit_response(p, "403 Forbidden (policy)", req);
  22537. pvt_set_needdestroy(p, "forbidden");
  22538. return 0;
  22539. }
  22540. if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
  22541. const char *to = get_header(req, "To");
  22542. char totag[128];
  22543. set_pvt_allowed_methods(p, req);
  22544. /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
  22545. if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
  22546. if (req->debug)
  22547. ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
  22548. transmit_response(p, "481 Subscription does not exist", req);
  22549. pvt_set_needdestroy(p, "subscription does not exist");
  22550. return 0;
  22551. }
  22552. /* Use this as the basis */
  22553. if (req->debug)
  22554. ast_verbose("Creating new subscription\n");
  22555. copy_request(&p->initreq, req);
  22556. if (sipdebug)
  22557. ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  22558. check_via(p, req);
  22559. build_route(p, req, 0, 0);
  22560. } else if (req->debug && req->ignore)
  22561. ast_verbose("Ignoring this SUBSCRIBE request\n");
  22562. /* Find parameters to Event: header value and remove them for now */
  22563. if (ast_strlen_zero(eventheader)) {
  22564. transmit_response(p, "489 Bad Event", req);
  22565. ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
  22566. pvt_set_needdestroy(p, "unknown event package in subscribe");
  22567. return 0;
  22568. }
  22569. event_end = strchr(eventheader, ';');
  22570. if (event_end) {
  22571. event_len = event_end - eventheader;
  22572. }
  22573. /* Handle authentication if we're new and not a retransmission. We can't just
  22574. * use if !req->ignore, because then we'll end up sending
  22575. * a 200 OK if someone retransmits without sending auth */
  22576. if (p->subscribed == NONE || resubscribe) {
  22577. res = check_user_full(p, req, SIP_SUBSCRIBE, e, XMIT_UNRELIABLE, addr, &authpeer);
  22578. /* if an authentication response was sent, we are done here */
  22579. if (res == AUTH_CHALLENGE_SENT) /* authpeer = NULL here */
  22580. return 0;
  22581. if (res != AUTH_SUCCESSFUL) {
  22582. ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
  22583. transmit_response(p, "403 Forbidden", req);
  22584. pvt_set_needdestroy(p, "authentication failed");
  22585. return 0;
  22586. }
  22587. }
  22588. /* At this point, we hold a reference to authpeer (if not NULL). It
  22589. * must be released when done.
  22590. */
  22591. /* Check if this device is allowed to subscribe at all */
  22592. if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
  22593. transmit_response(p, "403 Forbidden (policy)", req);
  22594. pvt_set_needdestroy(p, "subscription not allowed");
  22595. if (authpeer) {
  22596. unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
  22597. }
  22598. return 0;
  22599. }
  22600. if (strncmp(eventheader, "message-summary", MAX(event_len, 15)) && strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
  22601. /* Get destination right away */
  22602. gotdest = get_destination(p, NULL, NULL);
  22603. }
  22604. /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
  22605. parse_ok_contact(p, req);
  22606. build_contact(p);
  22607. if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
  22608. if (gotdest == SIP_GET_DEST_INVALID_URI) {
  22609. transmit_response(p, "416 Unsupported URI scheme", req);
  22610. } else {
  22611. transmit_response(p, "404 Not Found", req);
  22612. }
  22613. pvt_set_needdestroy(p, "subscription target not found");
  22614. if (authpeer) {
  22615. unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
  22616. }
  22617. return 0;
  22618. }
  22619. /* Initialize tag for new subscriptions */
  22620. if (ast_strlen_zero(p->tag))
  22621. make_our_tag(p);
  22622. if (!strncmp(eventheader, "presence", MAX(event_len, 8)) || !strncmp(eventheader, "dialog", MAX(event_len, 6))) { /* Presence, RFC 3842 */
  22623. unsigned int pidf_xml;
  22624. const char *accept;
  22625. int start = 0;
  22626. enum subscriptiontype subscribed = NONE;
  22627. const char *unknown_acceptheader = NULL;
  22628. /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
  22629. accept = __get_header(req, "Accept", &start);
  22630. while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
  22631. pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
  22632. /* Older versions of Polycom firmware will claim pidf+xml, but really
  22633. * they only support xpidf+xml. */
  22634. if (pidf_xml && strstr(p->useragent, "Polycom")) {
  22635. subscribed = XPIDF_XML;
  22636. } else if (pidf_xml) {
  22637. subscribed = PIDF_XML; /* RFC 3863 format */
  22638. } else if (strstr(accept, "application/dialog-info+xml")) {
  22639. subscribed = DIALOG_INFO_XML;
  22640. /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
  22641. } else if (strstr(accept, "application/cpim-pidf+xml")) {
  22642. subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
  22643. } else if (strstr(accept, "application/xpidf+xml")) {
  22644. subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
  22645. } else {
  22646. unknown_acceptheader = accept;
  22647. }
  22648. /* check to see if there is another Accept header present */
  22649. accept = __get_header(req, "Accept", &start);
  22650. }
  22651. if (!start) {
  22652. if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
  22653. transmit_response(p, "489 Bad Event", req);
  22654. ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
  22655. "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
  22656. "'%s', subscribeuri: '%s'\n",
  22657. p->stateid,
  22658. p->laststate,
  22659. p->dialogver,
  22660. p->subscribecontext,
  22661. p->subscribeuri);
  22662. pvt_set_needdestroy(p, "no Accept header");
  22663. if (authpeer) {
  22664. unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
  22665. }
  22666. return 0;
  22667. }
  22668. /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
  22669. so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
  22670. } else if (subscribed == NONE) {
  22671. /* Can't find a format for events that we know about */
  22672. char mybuf[200];
  22673. if (!ast_strlen_zero(unknown_acceptheader)) {
  22674. snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
  22675. } else {
  22676. snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
  22677. }
  22678. transmit_response(p, mybuf, req);
  22679. ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
  22680. "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
  22681. "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
  22682. unknown_acceptheader,
  22683. (int)p->subscribed,
  22684. p->stateid,
  22685. p->laststate,
  22686. p->dialogver,
  22687. p->subscribecontext,
  22688. p->subscribeuri);
  22689. pvt_set_needdestroy(p, "unrecognized format");
  22690. if (authpeer) {
  22691. unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
  22692. }
  22693. return 0;
  22694. } else {
  22695. p->subscribed = subscribed;
  22696. }
  22697. } else if (!strncmp(eventheader, "message-summary", MAX(event_len, 15))) {
  22698. int start = 0;
  22699. int found_supported = 0;
  22700. const char *acceptheader;
  22701. acceptheader = __get_header(req, "Accept", &start);
  22702. while (!found_supported && !ast_strlen_zero(acceptheader)) {
  22703. found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
  22704. if (!found_supported && (option_debug > 2)) {
  22705. ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
  22706. }
  22707. acceptheader = __get_header(req, "Accept", &start);
  22708. }
  22709. if (start && !found_supported) {
  22710. /* Format requested that we do not support */
  22711. transmit_response(p, "406 Not Acceptable", req);
  22712. ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
  22713. pvt_set_needdestroy(p, "unknown format");
  22714. if (authpeer) {
  22715. unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
  22716. }
  22717. return 0;
  22718. }
  22719. /* Looks like they actually want a mailbox status
  22720. This version of Asterisk supports mailbox subscriptions
  22721. The subscribed URI needs to exist in the dial plan
  22722. In most devices, this is configurable to the voicemailmain extension you use
  22723. */
  22724. if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
  22725. if (!authpeer) {
  22726. transmit_response(p, "404 Not found", req);
  22727. } else {
  22728. transmit_response(p, "404 Not found (no mailbox)", req);
  22729. ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
  22730. }
  22731. pvt_set_needdestroy(p, "received 404 response");
  22732. if (authpeer) {
  22733. unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
  22734. }
  22735. return 0;
  22736. }
  22737. p->subscribed = MWI_NOTIFICATION;
  22738. if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
  22739. ao2_unlock(p);
  22740. add_peer_mwi_subs(authpeer);
  22741. ao2_lock(p);
  22742. }
  22743. if (authpeer->mwipvt != p) { /* Destroy old PVT if this is a new one */
  22744. /* We only allow one subscription per peer */
  22745. if (authpeer->mwipvt) {
  22746. dialog_unlink_all(authpeer->mwipvt);
  22747. authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
  22748. }
  22749. authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
  22750. }
  22751. if (p->relatedpeer != authpeer) {
  22752. if (p->relatedpeer) {
  22753. unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
  22754. }
  22755. p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
  22756. }
  22757. /* Do not release authpeer here */
  22758. } else if (!strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
  22759. handle_cc_subscribe(p, req);
  22760. } else { /* At this point, Asterisk does not understand the specified event */
  22761. transmit_response(p, "489 Bad Event", req);
  22762. ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", eventheader);
  22763. pvt_set_needdestroy(p, "unknown event package");
  22764. if (authpeer) {
  22765. unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
  22766. }
  22767. return 0;
  22768. }
  22769. /* Add subscription for extension state from the PBX core */
  22770. if (p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION && !resubscribe) {
  22771. if (p->stateid != -1) {
  22772. ast_extension_state_del(p->stateid, cb_extensionstate);
  22773. }
  22774. dialog_ref(p, "copying dialog ptr into extension state struct");
  22775. p->stateid = ast_extension_state_add_destroy(p->context, p->exten,
  22776. cb_extensionstate, cb_extensionstate_destroy, p);
  22777. if (p->stateid == -1) {
  22778. dialog_unref(p, "copying dialog ptr into extension state struct failed");
  22779. }
  22780. }
  22781. if (!req->ignore) {
  22782. p->lastinvite = seqno;
  22783. }
  22784. if (!p->needdestroy) {
  22785. p->expiry = atoi(get_header(req, "Expires"));
  22786. /* check if the requested expiry-time is within the approved limits from sip.conf */
  22787. if (p->expiry > max_expiry) {
  22788. p->expiry = max_expiry;
  22789. } else if (p->expiry < min_expiry && p->expiry > 0) {
  22790. transmit_response_with_minexpires(p, "423 Interval too small", req);
  22791. ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
  22792. "with Expire header less that 'minexpire' limit. Received \"Expire: %d\" min is %d\n",
  22793. p->exten, p->context, p->expiry, min_expiry);
  22794. pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
  22795. if (authpeer) {
  22796. unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
  22797. }
  22798. return 0;
  22799. }
  22800. if (sipdebug) {
  22801. const char *action = p->expiry > 0 ? "Adding" : "Removing";
  22802. if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
  22803. ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
  22804. action, p->relatedpeer->name);
  22805. } else if (p->subscribed == CALL_COMPLETION) {
  22806. ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
  22807. } else {
  22808. ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
  22809. action, p->exten, p->context, p->username);
  22810. }
  22811. }
  22812. if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
  22813. ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
  22814. if (p->expiry > 0)
  22815. sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
  22816. if (p->subscribed == MWI_NOTIFICATION) {
  22817. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  22818. transmit_response(p, "200 OK", req);
  22819. if (p->relatedpeer) { /* Send first notification */
  22820. struct sip_peer *peer = p->relatedpeer;
  22821. ref_peer(peer, "ensure a peer ref is held during MWI sending");
  22822. ao2_unlock(p);
  22823. sip_send_mwi_to_peer(peer, 0);
  22824. ao2_lock(p);
  22825. unref_peer(peer, "release a peer ref now that MWI is sent");
  22826. }
  22827. } else if (p->subscribed != CALL_COMPLETION) {
  22828. sip_pvt_unlock(p);
  22829. firststate = ast_extension_state(NULL, p->context, p->exten);
  22830. sip_pvt_lock(p);
  22831. if (firststate < 0) {
  22832. 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));
  22833. transmit_response(p, "404 Not found", req);
  22834. pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
  22835. if (authpeer) {
  22836. unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
  22837. }
  22838. return 0;
  22839. }
  22840. ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
  22841. transmit_response(p, "200 OK", req);
  22842. transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
  22843. append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
  22844. /* hide the 'complete' exten/context in the refer_to field for later display */
  22845. ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
  22846. /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
  22847. }
  22848. if (!p->expiry) {
  22849. pvt_set_needdestroy(p, "forcing expiration");
  22850. }
  22851. }
  22852. if (authpeer) {
  22853. unref_peer(authpeer, "unref pointer into (*authpeer)");
  22854. }
  22855. return 1;
  22856. }
  22857. /*! \brief Handle incoming REGISTER request */
  22858. static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
  22859. {
  22860. enum check_auth_result res;
  22861. /* If this is not the intial request, and the initial request isn't
  22862. * a register, something screwy happened, so bail */
  22863. if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
  22864. ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
  22865. return -1;
  22866. }
  22867. /* Use this as the basis */
  22868. copy_request(&p->initreq, req);
  22869. if (sipdebug)
  22870. ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
  22871. check_via(p, req);
  22872. if ((res = register_verify(p, addr, req, e)) < 0) {
  22873. const char *reason;
  22874. switch (res) {
  22875. case AUTH_SECRET_FAILED:
  22876. reason = "Wrong password";
  22877. break;
  22878. case AUTH_USERNAME_MISMATCH:
  22879. reason = "Username/auth name mismatch";
  22880. break;
  22881. case AUTH_NOT_FOUND:
  22882. reason = "No matching peer found";
  22883. break;
  22884. case AUTH_UNKNOWN_DOMAIN:
  22885. reason = "Not a local domain";
  22886. break;
  22887. case AUTH_PEER_NOT_DYNAMIC:
  22888. reason = "Peer is not supposed to register";
  22889. break;
  22890. case AUTH_ACL_FAILED:
  22891. reason = "Device does not match ACL";
  22892. break;
  22893. case AUTH_BAD_TRANSPORT:
  22894. reason = "Device not configured to use this transport type";
  22895. break;
  22896. default:
  22897. reason = "Unknown failure";
  22898. break;
  22899. }
  22900. ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
  22901. get_header(req, "To"), ast_sockaddr_stringify(addr),
  22902. reason);
  22903. append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
  22904. } else {
  22905. req->authenticated = 1;
  22906. append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
  22907. }
  22908. if (res < 1) {
  22909. /* Destroy the session, but keep us around for just a bit in case they don't
  22910. get our 200 OK */
  22911. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  22912. }
  22913. return res;
  22914. }
  22915. /*!
  22916. * \brief Handle incoming SIP requests (methods)
  22917. * \note
  22918. * This is where all incoming requests go first.
  22919. * \note
  22920. * called with p and p->owner locked
  22921. */
  22922. static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
  22923. {
  22924. /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
  22925. relatively static */
  22926. const char *cmd;
  22927. const char *cseq;
  22928. const char *useragent;
  22929. const char *via;
  22930. const char *callid;
  22931. int via_pos = 0;
  22932. uint32_t seqno;
  22933. int len;
  22934. int respid;
  22935. int res = 0;
  22936. int debug = sip_debug_test_pvt(p);
  22937. const char *e;
  22938. int error = 0;
  22939. int oldmethod = p->method;
  22940. int acked = 0;
  22941. /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
  22942. * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
  22943. * so we can check to make sure these fields exist for all requests and responses */
  22944. cseq = get_header(req, "Cseq");
  22945. cmd = REQ_OFFSET_TO_STR(req, header[0]);
  22946. /* Save the via_pos so we can check later that responses only have 1 Via header */
  22947. via = __get_header(req, "Via", &via_pos);
  22948. /* This must exist already because we've called find_call by now */
  22949. callid = get_header(req, "Call-ID");
  22950. /* Must have Cseq */
  22951. if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
  22952. ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
  22953. error = 1;
  22954. }
  22955. if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
  22956. ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
  22957. error = 1;
  22958. }
  22959. if (error) {
  22960. if (!p->initreq.headers) { /* New call */
  22961. pvt_set_needdestroy(p, "no headers");
  22962. }
  22963. return -1;
  22964. }
  22965. /* Get the command XXX */
  22966. cmd = REQ_OFFSET_TO_STR(req, rlPart1);
  22967. e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
  22968. /* Save useragent of the client */
  22969. useragent = get_header(req, "User-Agent");
  22970. if (!ast_strlen_zero(useragent))
  22971. ast_string_field_set(p, useragent, useragent);
  22972. /* Find out SIP method for incoming request */
  22973. if (req->method == SIP_RESPONSE) { /* Response to our request */
  22974. /* ignore means "don't do anything with it" but still have to
  22975. * respond appropriately.
  22976. * But in this case this is a response already, so we really
  22977. * have nothing to do with this message, and even setting the
  22978. * ignore flag is pointless.
  22979. */
  22980. if (ast_strlen_zero(e)) {
  22981. return 0;
  22982. }
  22983. if (sscanf(e, "%30d %n", &respid, &len) != 1) {
  22984. ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
  22985. return 0;
  22986. }
  22987. if (respid <= 0) {
  22988. ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
  22989. return 0;
  22990. }
  22991. /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
  22992. * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
  22993. * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
  22994. if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
  22995. ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
  22996. return 0;
  22997. }
  22998. if (p->ocseq && (p->ocseq < seqno)) {
  22999. ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
  23000. return -1;
  23001. } else {
  23002. char causevar[256], causeval[256];
  23003. if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
  23004. extract_uri(p, req);
  23005. }
  23006. handle_response(p, respid, e + len, req, seqno);
  23007. if (global_store_sip_cause && p->owner) {
  23008. struct ast_channel *owner = p->owner;
  23009. snprintf(causevar, sizeof(causevar), "MASTER_CHANNEL(HASH(SIP_CAUSE,%s))", owner->name);
  23010. snprintf(causeval, sizeof(causeval), "SIP %s", REQ_OFFSET_TO_STR(req, rlPart2));
  23011. ast_channel_ref(owner);
  23012. sip_pvt_unlock(p);
  23013. ast_channel_unlock(owner);
  23014. *nounlock = 1;
  23015. pbx_builtin_setvar_helper(owner, causevar, causeval);
  23016. ast_channel_unref(owner);
  23017. sip_pvt_lock(p);
  23018. }
  23019. }
  23020. return 0;
  23021. }
  23022. /* New SIP request coming in
  23023. (could be new request in existing SIP dialog as well...)
  23024. */
  23025. p->method = req->method; /* Find out which SIP method they are using */
  23026. ast_debug(4, "**** Received %s (%u) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
  23027. if (p->icseq && (p->icseq > seqno) ) {
  23028. if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
  23029. ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
  23030. } else {
  23031. ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
  23032. if (req->method == SIP_INVITE) {
  23033. unsigned int ran = (ast_random() % 10) + 1;
  23034. char seconds[4];
  23035. snprintf(seconds, sizeof(seconds), "%u", ran);
  23036. 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 */
  23037. } else if (req->method != SIP_ACK) {
  23038. transmit_response(p, "500 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
  23039. }
  23040. return -1;
  23041. }
  23042. } else if (p->icseq &&
  23043. p->icseq == seqno &&
  23044. req->method != SIP_ACK &&
  23045. (p->method != SIP_CANCEL || p->alreadygone)) {
  23046. /* ignore means "don't do anything with it" but still have to
  23047. respond appropriately. We do this if we receive a repeat of
  23048. the last sequence number */
  23049. req->ignore = 1;
  23050. ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
  23051. }
  23052. /* RFC 3261 section 9. "CANCEL has no effect on a request to which a UAS has
  23053. * already given a final response." */
  23054. if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
  23055. transmit_response(p, "481 Call/Transaction Does Not Exist", req);
  23056. return res;
  23057. }
  23058. if (seqno >= p->icseq)
  23059. /* Next should follow monotonically (but not necessarily
  23060. incrementally -- thanks again to the genius authors of SIP --
  23061. increasing */
  23062. p->icseq = seqno;
  23063. /* Find their tag if we haven't got it */
  23064. if (ast_strlen_zero(p->theirtag)) {
  23065. char tag[128];
  23066. gettag(req, "From", tag, sizeof(tag));
  23067. ast_string_field_set(p, theirtag, tag);
  23068. }
  23069. snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
  23070. if (sip_cfg.pedanticsipchecking) {
  23071. /* If this is a request packet without a from tag, it's not
  23072. correct according to RFC 3261 */
  23073. /* Check if this a new request in a new dialog with a totag already attached to it,
  23074. RFC 3261 - section 12.2 - and we don't want to mess with recovery */
  23075. if (!p->initreq.headers && req->has_to_tag) {
  23076. /* If this is a first request and it got a to-tag, it is not for us */
  23077. if (!req->ignore && req->method == SIP_INVITE) {
  23078. /* Just because we think this is a dialog-starting INVITE with a to-tag
  23079. * doesn't mean it actually is. It could be a reinvite for an established, but
  23080. * unknown dialog. In such a case, we need to change our tag to the
  23081. * incoming INVITE's to-tag so that they will recognize the 481 we send and
  23082. * so that we will properly match their incoming ACK.
  23083. */
  23084. char totag[128];
  23085. gettag(req, "To", totag, sizeof(totag));
  23086. ast_string_field_set(p, tag, totag);
  23087. p->pendinginvite = p->icseq;
  23088. transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
  23089. /* Will cease to exist after ACK */
  23090. return res;
  23091. } else if (req->method != SIP_ACK) {
  23092. transmit_response(p, "481 Call/Transaction Does Not Exist", req);
  23093. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  23094. return res;
  23095. }
  23096. /* Otherwise, this is an ACK. It will always have a to-tag */
  23097. }
  23098. }
  23099. if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
  23100. transmit_response(p, "400 Bad request", req);
  23101. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  23102. return -1;
  23103. }
  23104. /* Handle various incoming SIP methods in requests */
  23105. switch (p->method) {
  23106. case SIP_OPTIONS:
  23107. res = handle_request_options(p, req, addr, e);
  23108. break;
  23109. case SIP_INVITE:
  23110. res = handle_request_invite(p, req, debug, seqno, addr, recount, e, nounlock);
  23111. break;
  23112. case SIP_REFER:
  23113. res = handle_request_refer(p, req, debug, seqno, nounlock);
  23114. break;
  23115. case SIP_CANCEL:
  23116. res = handle_request_cancel(p, req);
  23117. break;
  23118. case SIP_BYE:
  23119. res = handle_request_bye(p, req);
  23120. break;
  23121. case SIP_MESSAGE:
  23122. res = handle_request_message(p, req);
  23123. break;
  23124. case SIP_PUBLISH:
  23125. res = handle_request_publish(p, req, addr, seqno, e);
  23126. break;
  23127. case SIP_SUBSCRIBE:
  23128. res = handle_request_subscribe(p, req, addr, seqno, e);
  23129. break;
  23130. case SIP_REGISTER:
  23131. res = handle_request_register(p, req, addr, e);
  23132. break;
  23133. case SIP_INFO:
  23134. if (req->debug)
  23135. ast_verbose("Receiving INFO!\n");
  23136. if (!req->ignore)
  23137. handle_request_info(p, req);
  23138. else /* if ignoring, transmit response */
  23139. transmit_response(p, "200 OK", req);
  23140. break;
  23141. case SIP_NOTIFY:
  23142. res = handle_request_notify(p, req, addr, seqno, e);
  23143. break;
  23144. case SIP_UPDATE:
  23145. res = handle_request_update(p, req);
  23146. break;
  23147. case SIP_ACK:
  23148. /* Make sure we don't ignore this */
  23149. if (seqno == p->pendinginvite) {
  23150. p->invitestate = INV_TERMINATED;
  23151. p->pendinginvite = 0;
  23152. acked = __sip_ack(p, seqno, 1 /* response */, 0);
  23153. if (p->owner && find_sdp(req)) {
  23154. if (process_sdp(p, req, SDP_T38_NONE)) {
  23155. return -1;
  23156. }
  23157. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  23158. ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
  23159. }
  23160. }
  23161. check_pendings(p);
  23162. } else if (p->glareinvite == seqno) {
  23163. /* handle ack for the 491 pending sent for glareinvite */
  23164. p->glareinvite = 0;
  23165. acked = __sip_ack(p, seqno, 1, 0);
  23166. }
  23167. if (!acked) {
  23168. /* Got an ACK that did not match anything. Ignore
  23169. * silently and restore previous method */
  23170. p->method = oldmethod;
  23171. }
  23172. if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
  23173. pvt_set_needdestroy(p, "unmatched ACK");
  23174. }
  23175. break;
  23176. default:
  23177. transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
  23178. ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
  23179. cmd, ast_sockaddr_stringify(&p->sa));
  23180. /* If this is some new method, and we don't have a call, destroy it now */
  23181. if (!p->initreq.headers) {
  23182. pvt_set_needdestroy(p, "unimplemented method");
  23183. }
  23184. break;
  23185. }
  23186. return res;
  23187. }
  23188. /*! \brief Read data from SIP UDP socket
  23189. \note sipsock_read locks the owner channel while we are processing the SIP message
  23190. \return 1 on error, 0 on success
  23191. \note Successful messages is connected to SIP call and forwarded to handle_incoming()
  23192. */
  23193. static int sipsock_read(int *id, int fd, short events, void *ignore)
  23194. {
  23195. struct sip_request req;
  23196. struct ast_sockaddr addr;
  23197. int res;
  23198. static char readbuf[65535];
  23199. memset(&req, 0, sizeof(req));
  23200. res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
  23201. if (res < 0) {
  23202. #if !defined(__FreeBSD__)
  23203. if (errno == EAGAIN)
  23204. ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
  23205. else
  23206. #endif
  23207. if (errno != ECONNREFUSED)
  23208. ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
  23209. return 1;
  23210. }
  23211. readbuf[res] = '\0';
  23212. if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
  23213. return 1;
  23214. }
  23215. if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
  23216. return -1;
  23217. }
  23218. req.socket.fd = sipsock;
  23219. set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
  23220. req.socket.tcptls_session = NULL;
  23221. req.socket.port = htons(ast_sockaddr_port(&bindaddr));
  23222. handle_request_do(&req, &addr);
  23223. deinit_req(&req);
  23224. return 1;
  23225. }
  23226. /*! \brief Handle incoming SIP message - request or response
  23227. This is used for all transports (udp, tcp and tcp/tls)
  23228. */
  23229. static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
  23230. {
  23231. struct sip_pvt *p;
  23232. struct ast_channel *owner_chan_ref = NULL;
  23233. int recount = 0;
  23234. int nounlock = 0;
  23235. if (sip_debug_test_addr(addr)) /* Set the debug flag early on packet level */
  23236. req->debug = 1;
  23237. if (sip_cfg.pedanticsipchecking)
  23238. lws2sws(req->data); /* Fix multiline headers */
  23239. if (req->debug) {
  23240. ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
  23241. get_transport(req->socket.type), ast_sockaddr_stringify(addr), ast_str_buffer(req->data));
  23242. }
  23243. if (parse_request(req) == -1) { /* Bad packet, can't parse */
  23244. ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
  23245. return 1;
  23246. }
  23247. req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
  23248. if (req->debug)
  23249. ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
  23250. if (req->headers < 2) { /* Must have at least two headers */
  23251. ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
  23252. return 1;
  23253. }
  23254. /* Process request, with netlock held, and with usual deadlock avoidance */
  23255. ast_mutex_lock(&netlock);
  23256. /* Find the active SIP dialog or create a new one */
  23257. p = find_call(req, addr, req->method); /* returns p with a reference only. _NOT_ locked*/
  23258. if (p == NULL) {
  23259. ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
  23260. ast_mutex_unlock(&netlock);
  23261. return 1;
  23262. }
  23263. /* Lock both the pvt and the owner if owner is present. This will
  23264. * not fail. */
  23265. owner_chan_ref = sip_pvt_lock_full(p);
  23266. copy_socket_data(&p->socket, &req->socket);
  23267. ast_sockaddr_copy(&p->recv, addr);
  23268. /* if we have an owner, then this request has been authenticated */
  23269. if (p->owner) {
  23270. req->authenticated = 1;
  23271. }
  23272. if (p->do_history) /* This is a request or response, note what it was for */
  23273. append_history(p, "Rx", "%s / %s / %s", ast_str_buffer(req->data), get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
  23274. if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
  23275. /* Request failed */
  23276. ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
  23277. }
  23278. if (recount) {
  23279. ast_update_use_count();
  23280. }
  23281. if (p->owner && !nounlock) {
  23282. ast_channel_unlock(p->owner);
  23283. }
  23284. if (owner_chan_ref) {
  23285. ast_channel_unref(owner_chan_ref);
  23286. }
  23287. sip_pvt_unlock(p);
  23288. ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
  23289. ast_mutex_unlock(&netlock);
  23290. return 1;
  23291. }
  23292. /*! \brief Returns the port to use for this socket
  23293. *
  23294. * \param type The type of transport used
  23295. * \param port Port we are checking to see if it's the standard port.
  23296. * \note port is expected in host byte order
  23297. */
  23298. static int sip_standard_port(enum sip_transport type, int port)
  23299. {
  23300. if (type & SIP_TRANSPORT_TLS)
  23301. return port == STANDARD_TLS_PORT;
  23302. else
  23303. return port == STANDARD_SIP_PORT;
  23304. }
  23305. static int threadinfo_locate_cb(void *obj, void *arg, int flags)
  23306. {
  23307. struct sip_threadinfo *th = obj;
  23308. struct ast_sockaddr *s = arg;
  23309. if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
  23310. return CMP_MATCH | CMP_STOP;
  23311. }
  23312. return 0;
  23313. }
  23314. /*!
  23315. * \brief Find thread for TCP/TLS session (based on IP/Port
  23316. *
  23317. * \note This function returns an astobj2 reference
  23318. */
  23319. static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
  23320. {
  23321. struct sip_threadinfo *th;
  23322. struct ast_tcptls_session_instance *tcptls_instance = NULL;
  23323. if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
  23324. tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
  23325. ao2_t_ref(th, -1, "decrement ref from callback");
  23326. }
  23327. return tcptls_instance;
  23328. }
  23329. /*!
  23330. * \brief Helper for dns resolution to filter by address family.
  23331. *
  23332. * \note return 0 if addr is [::] else it returns addr's family.
  23333. */
  23334. int get_address_family_filter(unsigned int transport)
  23335. {
  23336. const struct ast_sockaddr *addr = NULL;
  23337. if ((transport == SIP_TRANSPORT_UDP) || !transport) {
  23338. addr = &bindaddr;
  23339. }
  23340. else if (transport == SIP_TRANSPORT_TCP) {
  23341. addr = &sip_tcp_desc.local_address;
  23342. }
  23343. else if (transport == SIP_TRANSPORT_TLS) {
  23344. addr = &sip_tls_desc.local_address;
  23345. }
  23346. if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
  23347. return 0;
  23348. }
  23349. return addr->ss.ss_family;
  23350. }
  23351. /*! \todo Get socket for dialog, prepare if needed, and return file handle */
  23352. static int sip_prepare_socket(struct sip_pvt *p)
  23353. {
  23354. struct sip_socket *s = &p->socket;
  23355. static const char name[] = "SIP socket";
  23356. struct sip_threadinfo *th = NULL;
  23357. struct ast_tcptls_session_instance *tcptls_session;
  23358. struct ast_tcptls_session_args *ca;
  23359. struct ast_sockaddr sa_tmp;
  23360. pthread_t launched;
  23361. /* check to see if a socket is already active */
  23362. if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
  23363. return s->fd;
  23364. }
  23365. if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
  23366. (s->tcptls_session) &&
  23367. (s->tcptls_session->fd != -1)) {
  23368. return s->tcptls_session->fd;
  23369. }
  23370. /*! \todo Check this... This might be wrong, depending on the proxy configuration
  23371. If proxy is in "force" mode its correct.
  23372. */
  23373. if (p->outboundproxy && p->outboundproxy->transport) {
  23374. s->type = p->outboundproxy->transport;
  23375. }
  23376. if (s->type == SIP_TRANSPORT_UDP) {
  23377. s->fd = sipsock;
  23378. return s->fd;
  23379. }
  23380. /* At this point we are dealing with a TCP/TLS connection
  23381. * 1. We need to check to see if a connection thread exists
  23382. * for this address, if so use that.
  23383. * 2. If a thread does not exist for this address, but the tcptls_session
  23384. * exists on the socket, the connection was closed.
  23385. * 3. If no tcptls_session thread exists for the address, and no tcptls_session
  23386. * already exists on the socket, create a new one and launch a new thread.
  23387. */
  23388. /* 1. check for existing threads */
  23389. ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
  23390. if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
  23391. s->fd = tcptls_session->fd;
  23392. if (s->tcptls_session) {
  23393. ao2_ref(s->tcptls_session, -1);
  23394. s->tcptls_session = NULL;
  23395. }
  23396. s->tcptls_session = tcptls_session;
  23397. return s->fd;
  23398. /* 2. Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
  23399. } else if (s->tcptls_session) {
  23400. return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
  23401. }
  23402. /* 3. Create a new TCP/TLS client connection */
  23403. /* create new session arguments for the client connection */
  23404. if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
  23405. !(ca->name = ast_strdup(name))) {
  23406. goto create_tcptls_session_fail;
  23407. }
  23408. ca->accept_fd = -1;
  23409. ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
  23410. /* if type is TLS, we need to create a tls cfg for this session arg */
  23411. if (s->type == SIP_TRANSPORT_TLS) {
  23412. if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
  23413. goto create_tcptls_session_fail;
  23414. }
  23415. memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
  23416. if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
  23417. !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
  23418. !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
  23419. !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
  23420. !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
  23421. goto create_tcptls_session_fail;
  23422. }
  23423. /* this host is used as the common name in ssl/tls */
  23424. if (!ast_strlen_zero(p->tohost)) {
  23425. ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
  23426. }
  23427. }
  23428. /* Create a client connection for address, this does not start the connection, just sets it up. */
  23429. if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
  23430. goto create_tcptls_session_fail;
  23431. }
  23432. s->fd = s->tcptls_session->fd;
  23433. /* client connections need to have the sip_threadinfo object created before
  23434. * the thread is detached. This ensures the alert_pipe is up before it will
  23435. * be used. Note that this function links the new threadinfo object into the
  23436. * threadt container. */
  23437. if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
  23438. goto create_tcptls_session_fail;
  23439. }
  23440. /* Give the new thread a reference to the tcptls_session */
  23441. ao2_ref(s->tcptls_session, +1);
  23442. if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
  23443. ast_debug(1, "Unable to launch '%s'.", ca->name);
  23444. ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
  23445. goto create_tcptls_session_fail;
  23446. }
  23447. return s->fd;
  23448. create_tcptls_session_fail:
  23449. if (ca) {
  23450. ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
  23451. }
  23452. if (s->tcptls_session) {
  23453. ast_tcptls_close_session_file(s->tcptls_session);
  23454. s->fd = -1;
  23455. ao2_ref(s->tcptls_session, -1);
  23456. s->tcptls_session = NULL;
  23457. }
  23458. if (th) {
  23459. ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
  23460. }
  23461. return -1;
  23462. }
  23463. /*!
  23464. * \brief Get cached MWI info
  23465. * \return TRUE if found MWI in cache
  23466. */
  23467. static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
  23468. {
  23469. struct sip_mailbox *mailbox;
  23470. int in_cache;
  23471. in_cache = 0;
  23472. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  23473. struct ast_event *event;
  23474. event = ast_event_get_cached(AST_EVENT_MWI,
  23475. AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
  23476. AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
  23477. AST_EVENT_IE_END);
  23478. if (!event)
  23479. continue;
  23480. *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
  23481. *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
  23482. ast_event_destroy(event);
  23483. in_cache = 1;
  23484. }
  23485. return in_cache;
  23486. }
  23487. /*! \brief Send message waiting indication to alert peer that they've got voicemail
  23488. * \note Both peer and associated sip_pvt must be unlocked prior to calling this function
  23489. */
  23490. static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
  23491. {
  23492. /* Called with peer lock, but releases it */
  23493. struct sip_pvt *p;
  23494. int newmsgs = 0, oldmsgs = 0;
  23495. const char *vmexten = NULL;
  23496. ao2_lock(peer);
  23497. if (peer->vmexten) {
  23498. vmexten = ast_strdupa(peer->vmexten);
  23499. }
  23500. if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
  23501. update_peer_lastmsgssent(peer, -1, 1);
  23502. ao2_unlock(peer);
  23503. return 0;
  23504. }
  23505. /* Do we have an IP address? If not, skip this peer */
  23506. if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
  23507. update_peer_lastmsgssent(peer, -1, 1);
  23508. ao2_unlock(peer);
  23509. return 0;
  23510. }
  23511. /* Attempt to use cached mwi to get message counts. */
  23512. if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
  23513. /* Fall back to manually checking the mailbox if not cache_only and get_cached_mwi failed */
  23514. struct ast_str *mailbox_str = ast_str_alloca(512);
  23515. peer_mailboxes_to_str(&mailbox_str, peer);
  23516. ao2_unlock(peer);
  23517. /* If there is no mailbox do nothing */
  23518. if (!ast_str_strlen(mailbox_str)) {
  23519. update_peer_lastmsgssent(peer, -1, 0);
  23520. return 0;
  23521. }
  23522. ast_app_inboxcount(ast_str_buffer(mailbox_str), &newmsgs, &oldmsgs);
  23523. ao2_lock(peer);
  23524. }
  23525. if (peer->mwipvt) {
  23526. /* Base message on subscription */
  23527. p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
  23528. ao2_unlock(peer);
  23529. } else {
  23530. ao2_unlock(peer);
  23531. /* Build temporary dialog for this message */
  23532. if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
  23533. update_peer_lastmsgssent(peer, -1, 0);
  23534. return -1;
  23535. }
  23536. /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
  23537. * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy
  23538. * the peer's socket information to the sip_pvt we just allocated
  23539. */
  23540. set_socket_transport(&p->socket, 0);
  23541. if (create_addr_from_peer(p, peer)) {
  23542. /* Maybe they're not registered, etc. */
  23543. dialog_unlink_all(p);
  23544. dialog_unref(p, "unref dialog p just created via sip_alloc");
  23545. update_peer_lastmsgssent(peer, -1, 0);
  23546. return 0;
  23547. }
  23548. /* Recalculate our side, and recalculate Call ID */
  23549. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  23550. build_via(p);
  23551. ao2_lock(peer);
  23552. if (!ast_strlen_zero(peer->mwi_from)) {
  23553. ast_string_field_set(p, mwi_from, peer->mwi_from);
  23554. } else if (!ast_strlen_zero(default_mwi_from)) {
  23555. ast_string_field_set(p, mwi_from, default_mwi_from);
  23556. }
  23557. ao2_unlock(peer);
  23558. /* Change the dialog callid. */
  23559. change_callid_pvt(p, NULL);
  23560. /* Destroy this session after 32 secs */
  23561. sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
  23562. }
  23563. /* 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,
  23564. we really need to have a lock on it */
  23565. sip_pvt_lock(p);
  23566. /* Send MWI */
  23567. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  23568. /* the following will decrement the refcount on p as it finishes */
  23569. transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
  23570. sip_pvt_unlock(p);
  23571. dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
  23572. update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
  23573. return 0;
  23574. }
  23575. /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
  23576. static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
  23577. {
  23578. /* If we have no RTP or no active owner, no need to check timers */
  23579. if (!dialog->rtp || !dialog->owner)
  23580. return;
  23581. /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
  23582. if (dialog->owner->_state != AST_STATE_UP || !ast_sockaddr_isnull(&dialog->redirip))
  23583. return;
  23584. /* If the call is involved in a T38 fax session do not check RTP timeout */
  23585. if (dialog->t38.state == T38_ENABLED)
  23586. return;
  23587. /* If we have no timers set, return now */
  23588. if (!ast_rtp_instance_get_keepalive(dialog->rtp) && !ast_rtp_instance_get_timeout(dialog->rtp) && !ast_rtp_instance_get_hold_timeout(dialog->rtp)) {
  23589. return;
  23590. }
  23591. /* Check AUDIO RTP keepalives */
  23592. if (dialog->lastrtptx && ast_rtp_instance_get_keepalive(dialog->rtp) &&
  23593. (t > dialog->lastrtptx + ast_rtp_instance_get_keepalive(dialog->rtp))) {
  23594. /* Need to send an empty RTP packet */
  23595. dialog->lastrtptx = time(NULL);
  23596. ast_rtp_instance_sendcng(dialog->rtp, 0);
  23597. }
  23598. /*! \todo Check video RTP keepalives
  23599. Do we need to move the lastrtptx to the RTP structure to have one for audio and one
  23600. for video? It really does belong to the RTP structure.
  23601. */
  23602. /* Check AUDIO RTP timers */
  23603. if (dialog->lastrtprx && (ast_rtp_instance_get_timeout(dialog->rtp) || ast_rtp_instance_get_hold_timeout(dialog->rtp)) && (t > dialog->lastrtprx + ast_rtp_instance_get_timeout(dialog->rtp))) {
  23604. if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_instance_get_hold_timeout(dialog->rtp) && (t > dialog->lastrtprx + ast_rtp_instance_get_hold_timeout(dialog->rtp)))) {
  23605. /* Needs a hangup */
  23606. if (ast_rtp_instance_get_timeout(dialog->rtp)) {
  23607. if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
  23608. /*
  23609. * Don't block, just try again later.
  23610. * If there was no owner, the call is dead already.
  23611. */
  23612. return;
  23613. }
  23614. ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
  23615. dialog->owner->name, (long) (t - dialog->lastrtprx));
  23616. /* Issue a softhangup */
  23617. ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
  23618. ast_channel_unlock(dialog->owner);
  23619. /* forget the timeouts for this call, since a hangup
  23620. has already been requested and we don't want to
  23621. repeatedly request hangups
  23622. */
  23623. ast_rtp_instance_set_timeout(dialog->rtp, 0);
  23624. ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
  23625. if (dialog->vrtp) {
  23626. ast_rtp_instance_set_timeout(dialog->vrtp, 0);
  23627. ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
  23628. }
  23629. }
  23630. }
  23631. }
  23632. }
  23633. /*! \brief The SIP monitoring thread
  23634. \note This thread monitors all the SIP sessions and peers that needs notification of mwi
  23635. (and thus do not have a separate thread) indefinitely
  23636. */
  23637. static void *do_monitor(void *data)
  23638. {
  23639. int res;
  23640. time_t t;
  23641. int reloading;
  23642. /* Add an I/O event to our SIP UDP socket */
  23643. if (sipsock > -1)
  23644. sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
  23645. /* From here on out, we die whenever asked */
  23646. for(;;) {
  23647. /* Check for a reload request */
  23648. ast_mutex_lock(&sip_reload_lock);
  23649. reloading = sip_reloading;
  23650. sip_reloading = FALSE;
  23651. ast_mutex_unlock(&sip_reload_lock);
  23652. if (reloading) {
  23653. ast_verb(1, "Reloading SIP\n");
  23654. sip_do_reload(sip_reloadreason);
  23655. /* Change the I/O fd of our UDP socket */
  23656. if (sipsock > -1) {
  23657. if (sipsock_read_id)
  23658. sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
  23659. else
  23660. sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
  23661. } else if (sipsock_read_id) {
  23662. ast_io_remove(io, sipsock_read_id);
  23663. sipsock_read_id = NULL;
  23664. }
  23665. }
  23666. /* Check for dialogs needing to be killed */
  23667. t = time(NULL);
  23668. /* don't scan the dialogs list if it hasn't been a reasonable period
  23669. of time since the last time we did it (when MWI is being sent, we can
  23670. get back to this point every millisecond or less)
  23671. */
  23672. /*
  23673. * We cannot hold the dialogs container lock when we destroy a
  23674. * dialog because of potential deadlocks. Instead we link the
  23675. * doomed dialog into dialogs_to_destroy and then iterate over
  23676. * that container destroying the dialogs.
  23677. */
  23678. ao2_t_callback(dialogs, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
  23679. "callback to monitor dialog status");
  23680. if (ao2_container_count(dialogs_to_destroy)) {
  23681. /* Now destroy the found dialogs that need to be destroyed. */
  23682. ao2_t_callback(dialogs_to_destroy, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
  23683. dialog_unlink_callback, NULL, "callback to dialog_unlink_all");
  23684. }
  23685. /* XXX TODO The scheduler usage in this module does not have sufficient
  23686. * synchronization being done between running the scheduler and places
  23687. * scheduling tasks. As it is written, any scheduled item may not run
  23688. * any sooner than about 1 second, regardless of whether a sooner time
  23689. * was asked for. */
  23690. pthread_testcancel();
  23691. /* Wait for sched or io */
  23692. res = ast_sched_wait(sched);
  23693. if ((res < 0) || (res > 1000))
  23694. res = 1000;
  23695. res = ast_io_wait(io, res);
  23696. if (res > 20)
  23697. ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
  23698. ast_mutex_lock(&monlock);
  23699. res = ast_sched_runq(sched);
  23700. if (res >= 20)
  23701. ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
  23702. if (global_store_sip_cause && res >= 100)
  23703. ast_log(LOG_WARNING, "scheduler delays detected, setting 'storesipcause' to 'no' in %s will improve performance\n", config);
  23704. ast_mutex_unlock(&monlock);
  23705. }
  23706. /* Never reached */
  23707. return NULL;
  23708. }
  23709. /*! \brief Start the channel monitor thread */
  23710. static int restart_monitor(void)
  23711. {
  23712. /* If we're supposed to be stopped -- stay stopped */
  23713. if (monitor_thread == AST_PTHREADT_STOP)
  23714. return 0;
  23715. ast_mutex_lock(&monlock);
  23716. if (monitor_thread == pthread_self()) {
  23717. ast_mutex_unlock(&monlock);
  23718. ast_log(LOG_WARNING, "Cannot kill myself\n");
  23719. return -1;
  23720. }
  23721. if (monitor_thread != AST_PTHREADT_NULL) {
  23722. /* Wake up the thread */
  23723. pthread_kill(monitor_thread, SIGURG);
  23724. } else {
  23725. /* Start a new monitor */
  23726. if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
  23727. ast_mutex_unlock(&monlock);
  23728. ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
  23729. return -1;
  23730. }
  23731. }
  23732. ast_mutex_unlock(&monlock);
  23733. return 0;
  23734. }
  23735. /*! \brief Session-Timers: Restart session timer */
  23736. static void restart_session_timer(struct sip_pvt *p)
  23737. {
  23738. if (p->stimer->st_active == TRUE) {
  23739. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  23740. AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
  23741. dialog_unref(p, "Removing session timer ref"));
  23742. start_session_timer(p);
  23743. }
  23744. }
  23745. /*! \brief Session-Timers: Stop session timer */
  23746. static void stop_session_timer(struct sip_pvt *p)
  23747. {
  23748. if (p->stimer->st_active == TRUE) {
  23749. p->stimer->st_active = FALSE;
  23750. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  23751. AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
  23752. dialog_unref(p, "removing session timer ref"));
  23753. }
  23754. }
  23755. /*! \brief Session-Timers: Start session timer */
  23756. static void start_session_timer(struct sip_pvt *p)
  23757. {
  23758. unsigned int timeout_ms;
  23759. if (p->stimer->st_schedid > -1) {
  23760. /* in the event a timer is already going, stop it */
  23761. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  23762. AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
  23763. dialog_unref(p, "unref stimer->st_schedid from dialog"));
  23764. }
  23765. /*
  23766. * RFC 4028 Section 10
  23767. * If the side not performing refreshes does not receive a
  23768. * session refresh request before the session expiration, it SHOULD send
  23769. * a BYE to terminate the session, slightly before the session
  23770. * expiration. The minimum of 32 seconds and one third of the session
  23771. * interval is RECOMMENDED.
  23772. */
  23773. timeout_ms = (1000 * p->stimer->st_interval);
  23774. if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
  23775. timeout_ms /= 2;
  23776. } else {
  23777. timeout_ms -= MIN(timeout_ms / 3, 32000);
  23778. }
  23779. p->stimer->st_schedid = ast_sched_add(sched, timeout_ms, proc_session_timer,
  23780. dialog_ref(p, "adding session timer ref"));
  23781. if (p->stimer->st_schedid < 0) {
  23782. dialog_unref(p, "removing session timer ref");
  23783. ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
  23784. } else {
  23785. p->stimer->st_active = TRUE;
  23786. ast_debug(2, "Session timer started: %d - %s %ums\n", p->stimer->st_schedid, p->callid, timeout_ms);
  23787. }
  23788. }
  23789. /*! \brief Session-Timers: Process session refresh timeout event */
  23790. static int proc_session_timer(const void *vp)
  23791. {
  23792. struct sip_pvt *p = (struct sip_pvt *) vp;
  23793. int res = 0;
  23794. if (!p->stimer) {
  23795. ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
  23796. goto return_unref;
  23797. }
  23798. ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
  23799. if (!p->owner) {
  23800. goto return_unref;
  23801. }
  23802. if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
  23803. goto return_unref;
  23804. }
  23805. if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
  23806. res = 1;
  23807. if (T38_ENABLED == p->t38.state) {
  23808. transmit_reinvite_with_sdp(p, TRUE, TRUE);
  23809. } else {
  23810. transmit_reinvite_with_sdp(p, FALSE, TRUE);
  23811. }
  23812. } else {
  23813. if (p->stimer->quit_flag) {
  23814. goto return_unref;
  23815. }
  23816. ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
  23817. sip_pvt_lock(p);
  23818. while (p->owner && ast_channel_trylock(p->owner)) {
  23819. sip_pvt_unlock(p);
  23820. usleep(1);
  23821. if (p->stimer && p->stimer->quit_flag) {
  23822. goto return_unref;
  23823. }
  23824. sip_pvt_lock(p);
  23825. }
  23826. ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
  23827. ast_channel_unlock(p->owner);
  23828. sip_pvt_unlock(p);
  23829. }
  23830. return_unref:
  23831. if (!res) {
  23832. /* An error occurred. Stop session timer processing */
  23833. if (p->stimer) {
  23834. ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
  23835. /* Don't pass go, don't collect $200.. we are the scheduled
  23836. * callback. We can rip ourself out here. */
  23837. p->stimer->st_schedid = -1;
  23838. /* Calling stop_session_timer is nice for consistent debug
  23839. * logs. */
  23840. stop_session_timer(p);
  23841. }
  23842. /* If we are not asking to be rescheduled, then we need to release our
  23843. * reference to the dialog. */
  23844. dialog_unref(p, "removing session timer ref");
  23845. }
  23846. return res;
  23847. }
  23848. /*! \brief Session-Timers: Function for parsing Min-SE header */
  23849. int parse_minse (const char *p_hdrval, int *const p_interval)
  23850. {
  23851. if (ast_strlen_zero(p_hdrval)) {
  23852. ast_log(LOG_WARNING, "Null Min-SE header\n");
  23853. return -1;
  23854. }
  23855. *p_interval = 0;
  23856. p_hdrval = ast_skip_blanks(p_hdrval);
  23857. if (!sscanf(p_hdrval, "%30d", p_interval)) {
  23858. ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
  23859. return -1;
  23860. }
  23861. ast_debug(2, "Received Min-SE: %d\n", *p_interval);
  23862. return 0;
  23863. }
  23864. /*! \brief Session-Timers: Function for parsing Session-Expires header */
  23865. int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
  23866. {
  23867. char *p_token;
  23868. int ref_idx;
  23869. char *p_se_hdr;
  23870. if (ast_strlen_zero(p_hdrval)) {
  23871. ast_log(LOG_WARNING, "Null Session-Expires header\n");
  23872. return -1;
  23873. }
  23874. *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
  23875. *p_interval = 0;
  23876. p_se_hdr = ast_strdupa(p_hdrval);
  23877. p_se_hdr = ast_skip_blanks(p_se_hdr);
  23878. while ((p_token = strsep(&p_se_hdr, ";"))) {
  23879. p_token = ast_skip_blanks(p_token);
  23880. if (!sscanf(p_token, "%30d", p_interval)) {
  23881. ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
  23882. return -1;
  23883. }
  23884. ast_debug(2, "Session-Expires: %d\n", *p_interval);
  23885. if (!p_se_hdr)
  23886. continue;
  23887. p_se_hdr = ast_skip_blanks(p_se_hdr);
  23888. ref_idx = strlen("refresher=");
  23889. if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
  23890. p_se_hdr += ref_idx;
  23891. p_se_hdr = ast_skip_blanks(p_se_hdr);
  23892. if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
  23893. *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
  23894. ast_debug(2, "Refresher: UAC\n");
  23895. } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
  23896. *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
  23897. ast_debug(2, "Refresher: UAS\n");
  23898. } else {
  23899. ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
  23900. return -1;
  23901. }
  23902. break;
  23903. }
  23904. }
  23905. return 0;
  23906. }
  23907. /*! \brief Handle 422 response to INVITE with session-timer requested
  23908. Session-Timers: An INVITE originated by Asterisk that asks for session-timers support
  23909. from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
  23910. server tells Asterisk that the session refresh interval offered by Asterisk is too low
  23911. for them. The proc_422_rsp() function handles a 422 response. It extracts the Min-SE
  23912. header that comes back in 422 and sends a new INVITE accordingly. */
  23913. static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
  23914. {
  23915. int rtn;
  23916. const char *p_hdrval;
  23917. int minse;
  23918. p_hdrval = get_header(rsp, "Min-SE");
  23919. if (ast_strlen_zero(p_hdrval)) {
  23920. ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
  23921. return;
  23922. }
  23923. rtn = parse_minse(p_hdrval, &minse);
  23924. if (rtn != 0) {
  23925. ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
  23926. return;
  23927. }
  23928. p->stimer->st_cached_min_se = minse;
  23929. if (p->stimer->st_interval < minse) {
  23930. p->stimer->st_interval = minse;
  23931. }
  23932. transmit_invite(p, SIP_INVITE, 1, 2, NULL);
  23933. }
  23934. /*! \brief Get Max or Min SE (session timer expiry)
  23935. * \param p pointer to the SIP dialog
  23936. * \param max if true, get max se, otherwise min se
  23937. */
  23938. int st_get_se(struct sip_pvt *p, int max)
  23939. {
  23940. if (max == TRUE) {
  23941. if (p->stimer->st_cached_max_se) {
  23942. return p->stimer->st_cached_max_se;
  23943. }
  23944. if (p->relatedpeer) {
  23945. p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
  23946. return (p->stimer->st_cached_max_se);
  23947. }
  23948. p->stimer->st_cached_max_se = global_max_se;
  23949. return (p->stimer->st_cached_max_se);
  23950. }
  23951. /* Find Min SE timer */
  23952. if (p->stimer->st_cached_min_se) {
  23953. return p->stimer->st_cached_min_se;
  23954. }
  23955. if (p->relatedpeer) {
  23956. p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
  23957. return (p->stimer->st_cached_min_se);
  23958. }
  23959. p->stimer->st_cached_min_se = global_min_se;
  23960. return (p->stimer->st_cached_min_se);
  23961. }
  23962. /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
  23963. * \note This is only called when processing an INVITE, so in that case Asterisk is
  23964. * always currently the UAS. If this is ever used to process responses, the
  23965. * function will have to be changed.
  23966. * \param p pointer to the SIP dialog
  23967. */
  23968. enum st_refresher st_get_refresher(struct sip_pvt *p)
  23969. {
  23970. if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
  23971. return p->stimer->st_cached_ref;
  23972. }
  23973. if (p->relatedpeer) {
  23974. p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
  23975. return p->stimer->st_cached_ref;
  23976. }
  23977. p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
  23978. return p->stimer->st_cached_ref;
  23979. }
  23980. /*!
  23981. * \brief Get the session-timer mode
  23982. * \param p pointer to the SIP dialog
  23983. * \param no_cached, set this to true in order to force a peername lookup on
  23984. * the session timer mode.
  23985. */
  23986. enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
  23987. {
  23988. if (!p->stimer) {
  23989. sip_st_alloc(p);
  23990. if (!p->stimer) {
  23991. return SESSION_TIMER_MODE_INVALID;
  23992. }
  23993. }
  23994. if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
  23995. return p->stimer->st_cached_mode;
  23996. if (p->relatedpeer) {
  23997. p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
  23998. return p->stimer->st_cached_mode;
  23999. }
  24000. p->stimer->st_cached_mode = global_st_mode;
  24001. return global_st_mode;
  24002. }
  24003. /*! \brief React to lack of answer to Qualify poke */
  24004. static int sip_poke_noanswer(const void *data)
  24005. {
  24006. struct sip_peer *peer = (struct sip_peer *)data;
  24007. peer->pokeexpire = -1;
  24008. if (peer->lastms > -1) {
  24009. ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
  24010. if (sip_cfg.peer_rtupdate) {
  24011. ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
  24012. }
  24013. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
  24014. if (sip_cfg.regextenonqualify) {
  24015. register_peer_exten(peer, FALSE);
  24016. }
  24017. }
  24018. if (peer->call) {
  24019. dialog_unlink_all(peer->call);
  24020. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  24021. /* peer->call = sip_destroy(peer->call);*/
  24022. }
  24023. /* Don't send a devstate change if nothing changed. */
  24024. if (peer->lastms > -1) {
  24025. peer->lastms = -1;
  24026. ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
  24027. }
  24028. /* Try again quickly */
  24029. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
  24030. DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
  24031. unref_peer(_data, "removing poke peer ref"),
  24032. unref_peer(peer, "removing poke peer ref"),
  24033. ref_peer(peer, "adding poke peer ref"));
  24034. /* Release the ref held by the running scheduler entry */
  24035. unref_peer(peer, "release peer poke noanswer ref");
  24036. return 0;
  24037. }
  24038. /*! \brief Check availability of peer, also keep NAT open
  24039. \note This is done with 60 seconds between each ping,
  24040. unless forced by cli or manager. If peer is unreachable,
  24041. we check every 10th second by default.
  24042. \note Do *not* hold a pvt lock while calling this function.
  24043. This function calls sip_alloc, which can cause a deadlock
  24044. if another sip_pvt is held.
  24045. */
  24046. static int sip_poke_peer(struct sip_peer *peer, int force)
  24047. {
  24048. struct sip_pvt *p;
  24049. int xmitres = 0;
  24050. if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
  24051. /* IF we have no IP, or this isn't to be monitored, return
  24052. immediately after clearing things out */
  24053. AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
  24054. unref_peer(peer, "removing poke peer ref"));
  24055. peer->lastms = 0;
  24056. if (peer->call) {
  24057. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  24058. }
  24059. return 0;
  24060. }
  24061. if (peer->call) {
  24062. if (sipdebug) {
  24063. ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
  24064. }
  24065. dialog_unlink_all(peer->call);
  24066. peer->call = dialog_unref(peer->call, "unref dialog peer->call");
  24067. /* peer->call = sip_destroy(peer->call); */
  24068. }
  24069. if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
  24070. return -1;
  24071. }
  24072. peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
  24073. p->sa = peer->addr;
  24074. p->recv = peer->addr;
  24075. copy_socket_data(&p->socket, &peer->socket);
  24076. ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
  24077. ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  24078. ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  24079. /* Get the outbound proxy information */
  24080. ref_proxy(p, obproxy_get(p, peer));
  24081. /* Send OPTIONs to peer's fullcontact */
  24082. if (!ast_strlen_zero(peer->fullcontact)) {
  24083. ast_string_field_set(p, fullcontact, peer->fullcontact);
  24084. }
  24085. if (!ast_strlen_zero(peer->fromuser)) {
  24086. ast_string_field_set(p, fromuser, peer->fromuser);
  24087. }
  24088. if (!ast_strlen_zero(peer->tohost)) {
  24089. ast_string_field_set(p, tohost, peer->tohost);
  24090. } else {
  24091. ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
  24092. }
  24093. /* Recalculate our side, and recalculate Call ID */
  24094. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  24095. build_via(p);
  24096. /* Change the dialog callid. */
  24097. change_callid_pvt(p, NULL);
  24098. AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
  24099. unref_peer(peer, "removing poke peer ref"));
  24100. if (p->relatedpeer)
  24101. p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
  24102. p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
  24103. ast_set_flag(&p->flags[0], SIP_OUTGOING);
  24104. #ifdef VOCAL_DATA_HACK
  24105. ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
  24106. xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL); /* sinks the p refcount */
  24107. #else
  24108. xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL); /* sinks the p refcount */
  24109. #endif
  24110. peer->ps = ast_tvnow();
  24111. if (xmitres == XMIT_ERROR) {
  24112. /* Immediately unreachable, network problems */
  24113. sip_poke_noanswer(ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
  24114. } else if (!force) {
  24115. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
  24116. unref_peer(_data, "removing poke peer ref"),
  24117. unref_peer(peer, "removing poke peer ref"),
  24118. ref_peer(peer, "adding poke peer ref"));
  24119. }
  24120. dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
  24121. return 0;
  24122. }
  24123. /*! \brief Part of PBX channel interface
  24124. \note
  24125. \par Return values:---
  24126. If we have qualify on and the device is not reachable, regardless of registration
  24127. state we return AST_DEVICE_UNAVAILABLE
  24128. For peers with call limit:
  24129. - not registered AST_DEVICE_UNAVAILABLE
  24130. - registered, no call AST_DEVICE_NOT_INUSE
  24131. - registered, active calls AST_DEVICE_INUSE
  24132. - registered, call limit reached AST_DEVICE_BUSY
  24133. - registered, onhold AST_DEVICE_ONHOLD
  24134. - registered, ringing AST_DEVICE_RINGING
  24135. For peers without call limit:
  24136. - not registered AST_DEVICE_UNAVAILABLE
  24137. - registered AST_DEVICE_NOT_INUSE
  24138. - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
  24139. Peers that does not have a known call and can't be reached by OPTIONS
  24140. - unreachable AST_DEVICE_UNAVAILABLE
  24141. If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
  24142. out a state by walking the channel list.
  24143. The queue system (\ref app_queue.c) treats a member as "active"
  24144. if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
  24145. When placing a call to the queue member, queue system sets a member to busy if
  24146. != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
  24147. */
  24148. static int sip_devicestate(void *data)
  24149. {
  24150. char *host;
  24151. char *tmp;
  24152. struct sip_peer *p;
  24153. int res = AST_DEVICE_INVALID;
  24154. /* make sure data is not null. Maybe unnecessary, but better be safe */
  24155. host = ast_strdupa(data ? data : "");
  24156. if ((tmp = strchr(host, '@')))
  24157. host = tmp + 1;
  24158. ast_debug(3, "Checking device state for peer %s\n", host);
  24159. /* If find_peer asks for a realtime peer, then this breaks rtautoclear. This
  24160. * is because when a peer tries to autoexpire, the last thing it does is to
  24161. * queue up an event telling the system that the devicestate has changed
  24162. * (presumably to unavailable). If we ask for a realtime peer here, this would
  24163. * load it BACK into memory, thus defeating the point of trying to clear dead
  24164. * hosts out of memory.
  24165. */
  24166. if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
  24167. if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
  24168. /* we have an address for the peer */
  24169. /* Check status in this order
  24170. - Hold
  24171. - Ringing
  24172. - Busy (enforced only by call limit)
  24173. - Inuse (we have a call)
  24174. - Unreachable (qualify)
  24175. If we don't find any of these state, report AST_DEVICE_NOT_INUSE
  24176. for registered devices */
  24177. if (p->onHold)
  24178. /* First check for hold or ring states */
  24179. res = AST_DEVICE_ONHOLD;
  24180. else if (p->inRinging) {
  24181. if (p->inRinging == p->inUse)
  24182. res = AST_DEVICE_RINGING;
  24183. else
  24184. res = AST_DEVICE_RINGINUSE;
  24185. } else if (p->call_limit && (p->inUse == p->call_limit))
  24186. /* check call limit */
  24187. res = AST_DEVICE_BUSY;
  24188. else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
  24189. /* We're forcing busy before we've reached the call limit */
  24190. res = AST_DEVICE_BUSY;
  24191. else if (p->call_limit && p->inUse)
  24192. /* Not busy, but we do have a call */
  24193. res = AST_DEVICE_INUSE;
  24194. else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
  24195. /* We don't have a call. Are we reachable at all? Requires qualify= */
  24196. res = AST_DEVICE_UNAVAILABLE;
  24197. else /* Default reply if we're registered and have no other data */
  24198. res = AST_DEVICE_NOT_INUSE;
  24199. } else {
  24200. /* there is no address, it's unavailable */
  24201. res = AST_DEVICE_UNAVAILABLE;
  24202. }
  24203. unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
  24204. }
  24205. return res;
  24206. }
  24207. /*! \brief PBX interface function -build SIP pvt structure
  24208. * SIP calls initiated by the PBX arrive here.
  24209. *
  24210. * \verbatim
  24211. * SIP Dial string syntax:
  24212. * SIP/devicename
  24213. * or SIP/username@domain (SIP uri)
  24214. * or SIP/username[:password[:md5secret[:authname[:transport]]]]@host[:port]
  24215. * or SIP/devicename/extension
  24216. * or SIP/devicename/extension/IPorHost
  24217. * or SIP/username@domain//IPorHost
  24218. * and there is an optional [!dnid] argument you can append to alter the
  24219. * To: header.
  24220. * \endverbatim
  24221. */
  24222. static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
  24223. {
  24224. struct sip_pvt *p;
  24225. struct ast_channel *tmpc = NULL;
  24226. char *ext = NULL, *host;
  24227. char tmp[256];
  24228. char *dest = data;
  24229. char *dnid;
  24230. char *secret = NULL;
  24231. char *md5secret = NULL;
  24232. char *authname = NULL;
  24233. char *trans = NULL;
  24234. char dialstring[256];
  24235. char *remote_address;
  24236. enum sip_transport transport = 0;
  24237. format_t oldformat = format;
  24238. AST_DECLARE_APP_ARGS(args,
  24239. AST_APP_ARG(peerorhost);
  24240. AST_APP_ARG(exten);
  24241. AST_APP_ARG(remote_address);
  24242. );
  24243. /* mask request with some set of allowed formats.
  24244. * XXX this needs to be fixed.
  24245. * The original code uses AST_FORMAT_AUDIO_MASK, but it is
  24246. * unclear what to use here. We have global_capabilities, which is
  24247. * configured from sip.conf, and sip_tech.capabilities, which is
  24248. * hardwired to all audio formats.
  24249. */
  24250. format &= AST_FORMAT_AUDIO_MASK;
  24251. if (!format) {
  24252. ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(sip_cfg.capability));
  24253. *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
  24254. return NULL;
  24255. }
  24256. ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
  24257. if (ast_strlen_zero(dest)) {
  24258. ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
  24259. *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
  24260. return NULL;
  24261. }
  24262. if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
  24263. ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
  24264. *cause = AST_CAUSE_SWITCH_CONGESTION;
  24265. return NULL;
  24266. }
  24267. p->outgoing_call = TRUE;
  24268. snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
  24269. ast_string_field_set(p, dialstring, dialstring);
  24270. if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
  24271. dialog_unlink_all(p);
  24272. dialog_unref(p, "unref dialog p from mem fail");
  24273. /* sip_destroy(p); */
  24274. ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
  24275. *cause = AST_CAUSE_SWITCH_CONGESTION;
  24276. return NULL;
  24277. }
  24278. /* Save the destination, the SIP dial string */
  24279. ast_copy_string(tmp, dest, sizeof(tmp));
  24280. /* Find DNID and take it away */
  24281. dnid = strchr(tmp, '!');
  24282. if (dnid != NULL) {
  24283. *dnid++ = '\0';
  24284. ast_string_field_set(p, todnid, dnid);
  24285. }
  24286. /* Divvy up the items separated by slashes */
  24287. AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
  24288. /* Find at sign - @ */
  24289. host = strchr(args.peerorhost, '@');
  24290. if (host) {
  24291. *host++ = '\0';
  24292. ext = args.peerorhost;
  24293. secret = strchr(ext, ':');
  24294. }
  24295. if (secret) {
  24296. *secret++ = '\0';
  24297. md5secret = strchr(secret, ':');
  24298. }
  24299. if (md5secret) {
  24300. *md5secret++ = '\0';
  24301. authname = strchr(md5secret, ':');
  24302. }
  24303. if (authname) {
  24304. *authname++ = '\0';
  24305. trans = strchr(authname, ':');
  24306. }
  24307. if (trans) {
  24308. *trans++ = '\0';
  24309. if (!strcasecmp(trans, "tcp"))
  24310. transport = SIP_TRANSPORT_TCP;
  24311. else if (!strcasecmp(trans, "tls"))
  24312. transport = SIP_TRANSPORT_TLS;
  24313. else {
  24314. if (strcasecmp(trans, "udp"))
  24315. ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
  24316. transport = SIP_TRANSPORT_UDP;
  24317. }
  24318. } else { /* use default */
  24319. transport = SIP_TRANSPORT_UDP;
  24320. }
  24321. if (!host) {
  24322. ext = args.exten;
  24323. host = args.peerorhost;
  24324. remote_address = args.remote_address;
  24325. } else {
  24326. remote_address = args.remote_address;
  24327. if (!ast_strlen_zero(args.exten)) {
  24328. ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
  24329. }
  24330. }
  24331. if (!ast_strlen_zero(remote_address)) {
  24332. p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
  24333. if (!p->options->outboundproxy) {
  24334. ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
  24335. }
  24336. }
  24337. set_socket_transport(&p->socket, transport);
  24338. /* We now have
  24339. host = peer name, DNS host name or DNS domain (for SRV)
  24340. ext = extension (user part of URI)
  24341. dnid = destination of the call (applies to the To: header)
  24342. */
  24343. if (create_addr(p, host, NULL, 1)) {
  24344. *cause = AST_CAUSE_UNREGISTERED;
  24345. ast_debug(3, "Cant create SIP call - target device not registered\n");
  24346. dialog_unlink_all(p);
  24347. dialog_unref(p, "unref dialog p UNREGISTERED");
  24348. /* sip_destroy(p); */
  24349. return NULL;
  24350. }
  24351. if (ast_strlen_zero(p->peername) && ext)
  24352. ast_string_field_set(p, peername, ext);
  24353. /* Recalculate our side, and recalculate Call ID */
  24354. ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
  24355. build_via(p);
  24356. /* Change the dialog callid. */
  24357. change_callid_pvt(p, NULL);
  24358. /* We have an extension to call, don't use the full contact here */
  24359. /* This to enable dialing registered peers with extension dialling,
  24360. like SIP/peername/extension
  24361. SIP/peername will still use the full contact
  24362. */
  24363. if (ext) {
  24364. ast_string_field_set(p, username, ext);
  24365. ast_string_field_set(p, fullcontact, NULL);
  24366. }
  24367. if (secret && !ast_strlen_zero(secret))
  24368. ast_string_field_set(p, peersecret, secret);
  24369. if (md5secret && !ast_strlen_zero(md5secret))
  24370. ast_string_field_set(p, peermd5secret, md5secret);
  24371. if (authname && !ast_strlen_zero(authname))
  24372. ast_string_field_set(p, authname, authname);
  24373. #if 0
  24374. printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
  24375. #endif
  24376. p->prefcodec = oldformat; /* Format for this call */
  24377. p->jointcapability = oldformat & p->capability;
  24378. sip_pvt_lock(p);
  24379. tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? requestor->linkedid : NULL); /* Place the call */
  24380. if (sip_cfg.callevents)
  24381. manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
  24382. "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
  24383. p->owner ? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
  24384. sip_pvt_unlock(p);
  24385. if (!tmpc) {
  24386. dialog_unlink_all(p);
  24387. /* sip_destroy(p); */
  24388. } else {
  24389. ast_channel_unlock(tmpc);
  24390. }
  24391. dialog_unref(p, "toss pvt ptr at end of sip_request_call");
  24392. ast_update_use_count();
  24393. restart_monitor();
  24394. return tmpc;
  24395. }
  24396. /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
  24397. static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
  24398. {
  24399. if (ast_strlen_zero(value))
  24400. return;
  24401. if (!ast_false(value)) {
  24402. char buf[64];
  24403. char *word, *next;
  24404. ast_copy_string(buf, value, sizeof(buf));
  24405. next = buf;
  24406. while ((word = strsep(&next, ","))) {
  24407. if (!strcasecmp(word, "port"))
  24408. ast_set_flag(&flags[0], SIP_INSECURE_PORT);
  24409. else if (!strcasecmp(word, "invite"))
  24410. ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
  24411. else
  24412. ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
  24413. }
  24414. }
  24415. }
  24416. /*!
  24417. \brief Handle T.38 configuration options common to users and peers
  24418. \returns non-zero if any config options were handled, zero otherwise
  24419. */
  24420. static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
  24421. unsigned int *maxdatagram)
  24422. {
  24423. int res = 1;
  24424. if (!strcasecmp(v->name, "t38pt_udptl")) {
  24425. char *buf = ast_strdupa(v->value);
  24426. char *word, *next = buf;
  24427. ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
  24428. while ((word = strsep(&next, ","))) {
  24429. if (ast_true(word) || !strcasecmp(word, "fec")) {
  24430. ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
  24431. ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
  24432. } else if (!strcasecmp(word, "redundancy")) {
  24433. ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
  24434. ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
  24435. } else if (!strcasecmp(word, "none")) {
  24436. ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
  24437. ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
  24438. } else if (!strncasecmp(word, "maxdatagram=", 12)) {
  24439. if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
  24440. ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
  24441. *maxdatagram = global_t38_maxdatagram;
  24442. }
  24443. }
  24444. }
  24445. } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
  24446. ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
  24447. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
  24448. } else {
  24449. res = 0;
  24450. }
  24451. return res;
  24452. }
  24453. /*!
  24454. \brief Handle flag-type options common to configuration of devices - peers
  24455. \param flags array of two struct ast_flags
  24456. \param mask array of two struct ast_flags
  24457. \param v linked list of config variables to process
  24458. \returns non-zero if any config options were handled, zero otherwise
  24459. */
  24460. static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
  24461. {
  24462. int res = 1;
  24463. if (!strcasecmp(v->name, "trustrpid")) {
  24464. ast_set_flag(&mask[0], SIP_TRUSTRPID);
  24465. ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
  24466. } else if (!strcasecmp(v->name, "sendrpid")) {
  24467. ast_set_flag(&mask[0], SIP_SENDRPID);
  24468. if (!strcasecmp(v->value, "pai")) {
  24469. ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
  24470. } else if (!strcasecmp(v->value, "rpid")) {
  24471. ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
  24472. } else if (ast_true(v->value)) {
  24473. ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
  24474. }
  24475. } else if (!strcasecmp(v->name, "rpid_update")) {
  24476. ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
  24477. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
  24478. } else if (!strcasecmp(v->name, "rpid_immediate")) {
  24479. ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
  24480. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
  24481. } else if (!strcasecmp(v->name, "trust_id_outbound")) {
  24482. ast_set_flag(&mask[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
  24483. ast_clear_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
  24484. if (!strcasecmp(v->value, "legacy")) {
  24485. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
  24486. } else if (ast_true(v->value)) {
  24487. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_YES);
  24488. } else if (ast_false(v->value)) {
  24489. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_NO);
  24490. } else {
  24491. ast_log(LOG_WARNING, "Unknown trust_id_outbound mode '%s' on line %d, using legacy\n", v->value, v->lineno);
  24492. ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
  24493. }
  24494. } else if (!strcasecmp(v->name, "g726nonstandard")) {
  24495. ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
  24496. ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
  24497. } else if (!strcasecmp(v->name, "useclientcode")) {
  24498. ast_set_flag(&mask[0], SIP_USECLIENTCODE);
  24499. ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
  24500. } else if (!strcasecmp(v->name, "dtmfmode")) {
  24501. ast_set_flag(&mask[0], SIP_DTMF);
  24502. ast_clear_flag(&flags[0], SIP_DTMF);
  24503. if (!strcasecmp(v->value, "inband"))
  24504. ast_set_flag(&flags[0], SIP_DTMF_INBAND);
  24505. else if (!strcasecmp(v->value, "rfc2833"))
  24506. ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
  24507. else if (!strcasecmp(v->value, "info"))
  24508. ast_set_flag(&flags[0], SIP_DTMF_INFO);
  24509. else if (!strcasecmp(v->value, "shortinfo"))
  24510. ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
  24511. else if (!strcasecmp(v->value, "auto"))
  24512. ast_set_flag(&flags[0], SIP_DTMF_AUTO);
  24513. else {
  24514. ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
  24515. ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
  24516. }
  24517. } else if (!strcasecmp(v->name, "nat")) {
  24518. ast_set_flag(&mask[0], SIP_NAT_FORCE_RPORT);
  24519. ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
  24520. if (!strcasecmp(v->value, "yes")) {
  24521. ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
  24522. ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
  24523. } else if (!strcasecmp(v->value, "force_rport")) {
  24524. ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
  24525. } else if (!strcasecmp(v->value, "comedia")) {
  24526. ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
  24527. }
  24528. } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
  24529. ast_set_flag(&mask[0], SIP_REINVITE);
  24530. ast_clear_flag(&flags[0], SIP_REINVITE);
  24531. if (ast_true(v->value)) {
  24532. ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
  24533. } else if (!ast_false(v->value)) {
  24534. char buf[64];
  24535. char *word, *next = buf;
  24536. ast_copy_string(buf, v->value, sizeof(buf));
  24537. while ((word = strsep(&next, ","))) {
  24538. if (!strcasecmp(word, "update")) {
  24539. ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
  24540. } else if (!strcasecmp(word, "nonat")) {
  24541. ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
  24542. ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
  24543. } else if (!strcasecmp(word, "outgoing")) {
  24544. ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
  24545. ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
  24546. ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
  24547. } else {
  24548. ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
  24549. }
  24550. }
  24551. }
  24552. } else if (!strcasecmp(v->name, "insecure")) {
  24553. ast_set_flag(&mask[0], SIP_INSECURE);
  24554. ast_clear_flag(&flags[0], SIP_INSECURE);
  24555. set_insecure_flags(&flags[0], v->value, v->lineno);
  24556. } else if (!strcasecmp(v->name, "progressinband")) {
  24557. ast_set_flag(&mask[0], SIP_PROG_INBAND);
  24558. ast_clear_flag(&flags[0], SIP_PROG_INBAND);
  24559. if (ast_true(v->value))
  24560. ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
  24561. else if (strcasecmp(v->value, "never"))
  24562. ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
  24563. } else if (!strcasecmp(v->name, "promiscredir")) {
  24564. ast_set_flag(&mask[0], SIP_PROMISCREDIR);
  24565. ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
  24566. } else if (!strcasecmp(v->name, "videosupport")) {
  24567. if (!strcasecmp(v->value, "always")) {
  24568. ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
  24569. ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
  24570. } else {
  24571. ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
  24572. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
  24573. }
  24574. } else if (!strcasecmp(v->name, "textsupport")) {
  24575. ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
  24576. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
  24577. res = 1;
  24578. } else if (!strcasecmp(v->name, "allowoverlap")) {
  24579. ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
  24580. ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
  24581. if (ast_true(v->value)) {
  24582. ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
  24583. } else if (!strcasecmp(v->value, "dtmf")){
  24584. ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
  24585. }
  24586. } else if (!strcasecmp(v->name, "allowsubscribe")) {
  24587. ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
  24588. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
  24589. } else if (!strcasecmp(v->name, "ignoresdpversion")) {
  24590. ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
  24591. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
  24592. } else if (!strcasecmp(v->name, "faxdetect")) {
  24593. ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
  24594. if (ast_true(v->value)) {
  24595. ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
  24596. } else if (ast_false(v->value)) {
  24597. ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
  24598. } else {
  24599. char *buf = ast_strdupa(v->value);
  24600. char *word, *next = buf;
  24601. while ((word = strsep(&next, ","))) {
  24602. if (!strcasecmp(word, "cng")) {
  24603. ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
  24604. } else if (!strcasecmp(word, "t38")) {
  24605. ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
  24606. } else {
  24607. ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
  24608. }
  24609. }
  24610. }
  24611. } else if (!strcasecmp(v->name, "rfc2833compensate")) {
  24612. ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
  24613. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
  24614. } else if (!strcasecmp(v->name, "buggymwi")) {
  24615. ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
  24616. ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
  24617. } else
  24618. res = 0;
  24619. return res;
  24620. }
  24621. /*! \brief Add SIP domain to list of domains we are responsible for */
  24622. static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
  24623. {
  24624. struct domain *d;
  24625. if (ast_strlen_zero(domain)) {
  24626. ast_log(LOG_WARNING, "Zero length domain.\n");
  24627. return 1;
  24628. }
  24629. if (!(d = ast_calloc(1, sizeof(*d))))
  24630. return 0;
  24631. ast_copy_string(d->domain, domain, sizeof(d->domain));
  24632. if (!ast_strlen_zero(context))
  24633. ast_copy_string(d->context, context, sizeof(d->context));
  24634. d->mode = mode;
  24635. AST_LIST_LOCK(&domain_list);
  24636. AST_LIST_INSERT_TAIL(&domain_list, d, list);
  24637. AST_LIST_UNLOCK(&domain_list);
  24638. if (sipdebug)
  24639. ast_debug(1, "Added local SIP domain '%s'\n", domain);
  24640. return 1;
  24641. }
  24642. /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
  24643. static int check_sip_domain(const char *domain, char *context, size_t len)
  24644. {
  24645. struct domain *d;
  24646. int result = 0;
  24647. AST_LIST_LOCK(&domain_list);
  24648. AST_LIST_TRAVERSE(&domain_list, d, list) {
  24649. if (strcasecmp(d->domain, domain)) {
  24650. continue;
  24651. }
  24652. if (len && !ast_strlen_zero(d->context))
  24653. ast_copy_string(context, d->context, len);
  24654. result = 1;
  24655. break;
  24656. }
  24657. AST_LIST_UNLOCK(&domain_list);
  24658. return result;
  24659. }
  24660. /*! \brief Clear our domain list (at reload) */
  24661. static void clear_sip_domains(void)
  24662. {
  24663. struct domain *d;
  24664. AST_LIST_LOCK(&domain_list);
  24665. while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
  24666. ast_free(d);
  24667. AST_LIST_UNLOCK(&domain_list);
  24668. }
  24669. /*!
  24670. * \internal
  24671. * \brief Realm authentication container destructor.
  24672. *
  24673. * \param obj Container object to destroy.
  24674. *
  24675. * \return Nothing
  24676. */
  24677. static void destroy_realm_authentication(void *obj)
  24678. {
  24679. struct sip_auth_container *credentials = obj;
  24680. struct sip_auth *auth;
  24681. while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
  24682. ast_free(auth);
  24683. }
  24684. }
  24685. /*!
  24686. * \internal
  24687. * \brief Add realm authentication to credentials.
  24688. *
  24689. * \param credentials Realm authentication container to create/add authentication credentials.
  24690. * \param configuration Credential configuration value.
  24691. * \param lineno Line number in config file.
  24692. *
  24693. * \return Nothing
  24694. */
  24695. static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
  24696. {
  24697. char *authcopy;
  24698. char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
  24699. struct sip_auth *auth;
  24700. if (ast_strlen_zero(configuration)) {
  24701. /* Nothing to add */
  24702. return;
  24703. }
  24704. ast_debug(1, "Auth config :: %s\n", configuration);
  24705. authcopy = ast_strdupa(configuration);
  24706. username = authcopy;
  24707. /* split user[:secret] and relm */
  24708. realm = strrchr(username, '@');
  24709. if (realm)
  24710. *realm++ = '\0';
  24711. if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
  24712. ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
  24713. return;
  24714. }
  24715. /* parse username at ':' for secret, or '#" for md5secret */
  24716. if ((secret = strchr(username, ':'))) {
  24717. *secret++ = '\0';
  24718. } else if ((md5secret = strchr(username, '#'))) {
  24719. *md5secret++ = '\0';
  24720. }
  24721. /* Create the continer if needed. */
  24722. if (!*credentials) {
  24723. *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
  24724. "Create realm auth container.");
  24725. if (!*credentials) {
  24726. /* Failed to create the credentials container. */
  24727. return;
  24728. }
  24729. }
  24730. /* Create the authentication credential entry. */
  24731. auth = ast_calloc(1, sizeof(*auth));
  24732. if (!auth) {
  24733. return;
  24734. }
  24735. ast_copy_string(auth->realm, realm, sizeof(auth->realm));
  24736. ast_copy_string(auth->username, username, sizeof(auth->username));
  24737. if (secret)
  24738. ast_copy_string(auth->secret, secret, sizeof(auth->secret));
  24739. if (md5secret)
  24740. ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
  24741. /* Add credential to container list. */
  24742. AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
  24743. ast_verb(3, "Added authentication for realm %s\n", realm);
  24744. }
  24745. /*!
  24746. * \internal
  24747. * \brief Find authentication for a specific realm.
  24748. *
  24749. * \param credentials Realm authentication container to search.
  24750. * \param realm Authentication realm to find.
  24751. *
  24752. * \return Found authentication credential or NULL.
  24753. */
  24754. static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
  24755. {
  24756. struct sip_auth *auth;
  24757. if (credentials) {
  24758. AST_LIST_TRAVERSE(&credentials->list, auth, node) {
  24759. if (!strcasecmp(auth->realm, realm)) {
  24760. break;
  24761. }
  24762. }
  24763. } else {
  24764. auth = NULL;
  24765. }
  24766. return auth;
  24767. }
  24768. /*! \brief
  24769. * implement the setvar config line
  24770. */
  24771. static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
  24772. {
  24773. struct ast_variable *tmpvar = NULL;
  24774. char *varname = ast_strdupa(buf), *varval = NULL;
  24775. if ((varval = strchr(varname, '='))) {
  24776. *varval++ = '\0';
  24777. if ((tmpvar = ast_variable_new(varname, varval, ""))) {
  24778. tmpvar->next = list;
  24779. list = tmpvar;
  24780. }
  24781. }
  24782. return list;
  24783. }
  24784. /*! \brief Set peer defaults before configuring specific configurations */
  24785. static void set_peer_defaults(struct sip_peer *peer)
  24786. {
  24787. if (peer->expire == 0) {
  24788. /* Don't reset expire or port time during reload
  24789. if we have an active registration
  24790. */
  24791. peer->expire = -1;
  24792. peer->pokeexpire = -1;
  24793. set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
  24794. }
  24795. peer->type = SIP_TYPE_PEER;
  24796. ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
  24797. ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
  24798. ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
  24799. ast_string_field_set(peer, context, sip_cfg.default_context);
  24800. ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
  24801. ast_string_field_set(peer, language, default_language);
  24802. ast_string_field_set(peer, mohinterpret, default_mohinterpret);
  24803. ast_string_field_set(peer, mohsuggest, default_mohsuggest);
  24804. ast_string_field_set(peer, engine, default_engine);
  24805. ast_sockaddr_setnull(&peer->addr);
  24806. ast_sockaddr_setnull(&peer->defaddr);
  24807. peer->capability = sip_cfg.capability;
  24808. peer->maxcallbitrate = default_maxcallbitrate;
  24809. peer->rtptimeout = global_rtptimeout;
  24810. peer->rtpholdtimeout = global_rtpholdtimeout;
  24811. peer->rtpkeepalive = global_rtpkeepalive;
  24812. peer->allowtransfer = sip_cfg.allowtransfer;
  24813. peer->autoframing = global_autoframing;
  24814. peer->t38_maxdatagram = global_t38_maxdatagram;
  24815. peer->qualifyfreq = global_qualifyfreq;
  24816. if (global_callcounter)
  24817. peer->call_limit=INT_MAX;
  24818. ast_string_field_set(peer, vmexten, default_vmexten);
  24819. ast_string_field_set(peer, secret, "");
  24820. ast_string_field_set(peer, remotesecret, "");
  24821. ast_string_field_set(peer, md5secret, "");
  24822. ast_string_field_set(peer, cid_num, "");
  24823. ast_string_field_set(peer, cid_name, "");
  24824. ast_string_field_set(peer, cid_tag, "");
  24825. ast_string_field_set(peer, fromdomain, "");
  24826. ast_string_field_set(peer, fromuser, "");
  24827. ast_string_field_set(peer, regexten, "");
  24828. peer->callgroup = 0;
  24829. peer->pickupgroup = 0;
  24830. peer->maxms = default_qualify;
  24831. peer->prefs = default_prefs;
  24832. peer->stimer.st_mode_oper = global_st_mode; /* Session-Timers */
  24833. peer->stimer.st_ref = global_st_refresher;
  24834. peer->stimer.st_min_se = global_min_se;
  24835. peer->stimer.st_max_se = global_max_se;
  24836. peer->timer_t1 = global_t1;
  24837. peer->timer_b = global_timer_b;
  24838. clear_peer_mailboxes(peer);
  24839. peer->disallowed_methods = sip_cfg.disallowed_methods;
  24840. peer->transports = default_transports;
  24841. peer->default_outbound_transport = default_primary_transport;
  24842. if (peer->outboundproxy) {
  24843. ao2_ref(peer->outboundproxy, -1);
  24844. peer->outboundproxy = NULL;
  24845. }
  24846. }
  24847. /*! \brief Create temporary peer (used in autocreatepeer mode) */
  24848. static struct sip_peer *temp_peer(const char *name)
  24849. {
  24850. struct sip_peer *peer;
  24851. if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
  24852. return NULL;
  24853. if (ast_string_field_init(peer, 512)) {
  24854. ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
  24855. return NULL;
  24856. }
  24857. if (!(peer->cc_params = ast_cc_config_params_init())) {
  24858. ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
  24859. return NULL;
  24860. }
  24861. ast_atomic_fetchadd_int(&apeerobjs, 1);
  24862. set_peer_defaults(peer);
  24863. ast_copy_string(peer->name, name, sizeof(peer->name));
  24864. peer->selfdestruct = TRUE;
  24865. peer->host_dynamic = TRUE;
  24866. peer->prefs = default_prefs;
  24867. reg_source_db(peer);
  24868. return peer;
  24869. }
  24870. /*! \todo document this function */
  24871. static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
  24872. {
  24873. char *next, *mbox, *context;
  24874. next = ast_strdupa(value);
  24875. while ((mbox = context = strsep(&next, ","))) {
  24876. struct sip_mailbox *mailbox;
  24877. int duplicate = 0;
  24878. /* remove leading/trailing whitespace from mailbox string */
  24879. mbox = ast_strip(mbox);
  24880. strsep(&context, "@");
  24881. if (ast_strlen_zero(mbox)) {
  24882. continue;
  24883. }
  24884. /* Check whether the mailbox is already in the list */
  24885. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  24886. if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
  24887. duplicate = 1;
  24888. break;
  24889. }
  24890. }
  24891. if (duplicate) {
  24892. continue;
  24893. }
  24894. if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
  24895. continue;
  24896. }
  24897. if (!ast_strlen_zero(context)) {
  24898. mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
  24899. strcpy(mailbox->context, context); /* SAFE */
  24900. }
  24901. strcpy(mailbox->mailbox, mbox); /* SAFE */
  24902. AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
  24903. }
  24904. }
  24905. /*! \brief Build peer from configuration (file or realtime static/dynamic) */
  24906. static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
  24907. {
  24908. struct sip_peer *peer = NULL;
  24909. struct ast_ha *oldha = NULL;
  24910. struct ast_ha *olddirectmediaha = NULL;
  24911. int found = 0;
  24912. int firstpass = 1;
  24913. uint16_t port = 0;
  24914. int format = 0; /* Ama flags */
  24915. int timerb_set = 0, timert1_set = 0;
  24916. time_t regseconds = 0;
  24917. struct ast_flags peerflags[3] = {{(0)}};
  24918. struct ast_flags mask[3] = {{(0)}};
  24919. char callback[256] = "";
  24920. struct sip_peer tmp_peer;
  24921. const char *srvlookup = NULL;
  24922. static int deprecation_warning = 1;
  24923. int alt_fullcontact = alt ? 1 : 0, headercount = 0;
  24924. struct ast_str *fullcontact = ast_str_alloca(512);
  24925. if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  24926. /* Note we do NOT use find_peer here, to avoid realtime recursion */
  24927. /* We also use a case-sensitive comparison (unlike find_peer) so
  24928. that case changes made to the peer name will be properly handled
  24929. during reload
  24930. */
  24931. ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
  24932. peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
  24933. }
  24934. if (peer) {
  24935. /* Already in the list, remove it and it will be added back (or FREE'd) */
  24936. found++;
  24937. /* we've unlinked the peer from the peers container but not unlinked from the peers_by_ip container yet
  24938. this leads to a wrong refcounter and the peer object is never destroyed */
  24939. if (!ast_sockaddr_isnull(&peer->addr)) {
  24940. ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
  24941. }
  24942. if (!(peer->the_mark))
  24943. firstpass = 0;
  24944. } else {
  24945. if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
  24946. return NULL;
  24947. if (ast_string_field_init(peer, 512)) {
  24948. ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
  24949. return NULL;
  24950. }
  24951. if (!(peer->cc_params = ast_cc_config_params_init())) {
  24952. ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
  24953. return NULL;
  24954. }
  24955. if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
  24956. ast_atomic_fetchadd_int(&rpeerobjs, 1);
  24957. ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
  24958. } else
  24959. ast_atomic_fetchadd_int(&speerobjs, 1);
  24960. }
  24961. /* Note that our peer HAS had its reference count increased */
  24962. if (firstpass) {
  24963. peer->lastmsgssent = -1;
  24964. oldha = peer->ha;
  24965. peer->ha = NULL;
  24966. olddirectmediaha = peer->directmediaha;
  24967. peer->directmediaha = NULL;
  24968. set_peer_defaults(peer); /* Set peer defaults */
  24969. peer->type = 0;
  24970. }
  24971. /* in case the case of the peer name has changed, update the name */
  24972. ast_copy_string(peer->name, name, sizeof(peer->name));
  24973. /* If we have channel variables, remove them (reload) */
  24974. if (peer->chanvars) {
  24975. ast_variables_destroy(peer->chanvars);
  24976. peer->chanvars = NULL;
  24977. /* XXX should unregister ? */
  24978. }
  24979. if (found)
  24980. peer->portinuri = 0;
  24981. /* If we have realm authentication information, remove them (reload) */
  24982. ao2_lock(peer);
  24983. if (peer->auth) {
  24984. ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
  24985. peer->auth = NULL;
  24986. }
  24987. ao2_unlock(peer);
  24988. /* clear the transport information. We will detect if a default value is required after parsing the config */
  24989. peer->default_outbound_transport = 0;
  24990. peer->transports = 0;
  24991. if (!devstate_only) {
  24992. struct sip_mailbox *mailbox;
  24993. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  24994. mailbox->delme = 1;
  24995. }
  24996. }
  24997. for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
  24998. if (!devstate_only) {
  24999. if (handle_common_options(&peerflags[0], &mask[0], v)) {
  25000. continue;
  25001. }
  25002. if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
  25003. continue;
  25004. }
  25005. if (!strcasecmp(v->name, "transport")) {
  25006. char *val = ast_strdupa(v->value);
  25007. char *trans;
  25008. peer->transports = peer->default_outbound_transport = 0;
  25009. while ((trans = strsep(&val, ","))) {
  25010. trans = ast_skip_blanks(trans);
  25011. if (!strncasecmp(trans, "udp", 3)) {
  25012. peer->transports |= SIP_TRANSPORT_UDP;
  25013. } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
  25014. peer->transports |= SIP_TRANSPORT_TCP;
  25015. } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
  25016. peer->transports |= SIP_TRANSPORT_TLS;
  25017. } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
  25018. 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);
  25019. } else {
  25020. 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);
  25021. }
  25022. if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
  25023. peer->default_outbound_transport = peer->transports;
  25024. }
  25025. }
  25026. } else if (realtime && !strcasecmp(v->name, "regseconds")) {
  25027. ast_get_time_t(v->value, &regseconds, 0, NULL);
  25028. } else if (realtime && !strcasecmp(v->name, "name")) {
  25029. ast_copy_string(peer->name, v->value, sizeof(peer->name));
  25030. } else if (realtime && !strcasecmp(v->name, "useragent")) {
  25031. ast_string_field_set(peer, useragent, v->value);
  25032. } else if (!strcasecmp(v->name, "type")) {
  25033. if (!strcasecmp(v->value, "peer")) {
  25034. peer->type |= SIP_TYPE_PEER;
  25035. } else if (!strcasecmp(v->value, "user")) {
  25036. peer->type |= SIP_TYPE_USER;
  25037. } else if (!strcasecmp(v->value, "friend")) {
  25038. peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
  25039. }
  25040. } else if (!strcasecmp(v->name, "remotesecret")) {
  25041. ast_string_field_set(peer, remotesecret, v->value);
  25042. } else if (!strcasecmp(v->name, "secret")) {
  25043. ast_string_field_set(peer, secret, v->value);
  25044. } else if (!strcasecmp(v->name, "md5secret")) {
  25045. ast_string_field_set(peer, md5secret, v->value);
  25046. } else if (!strcasecmp(v->name, "auth")) {
  25047. add_realm_authentication(&peer->auth, v->value, v->lineno);
  25048. } else if (!strcasecmp(v->name, "callerid")) {
  25049. char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
  25050. ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
  25051. ast_string_field_set(peer, cid_name, cid_name);
  25052. ast_string_field_set(peer, cid_num, cid_num);
  25053. } else if (!strcasecmp(v->name, "mwi_from")) {
  25054. ast_string_field_set(peer, mwi_from, v->value);
  25055. } else if (!strcasecmp(v->name, "fullname")) {
  25056. ast_string_field_set(peer, cid_name, v->value);
  25057. } else if (!strcasecmp(v->name, "trunkname")) {
  25058. /* This is actually for a trunk, so we don't want to override callerid */
  25059. ast_string_field_set(peer, cid_name, "");
  25060. } else if (!strcasecmp(v->name, "cid_number")) {
  25061. ast_string_field_set(peer, cid_num, v->value);
  25062. } else if (!strcasecmp(v->name, "cid_tag")) {
  25063. ast_string_field_set(peer, cid_tag, v->value);
  25064. } else if (!strcasecmp(v->name, "context")) {
  25065. ast_string_field_set(peer, context, v->value);
  25066. ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
  25067. } else if (!strcasecmp(v->name, "subscribecontext")) {
  25068. ast_string_field_set(peer, subscribecontext, v->value);
  25069. } else if (!strcasecmp(v->name, "fromdomain")) {
  25070. char *fromdomainport;
  25071. ast_string_field_set(peer, fromdomain, v->value);
  25072. if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
  25073. *fromdomainport++ = '\0';
  25074. if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
  25075. ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
  25076. }
  25077. } else {
  25078. peer->fromdomainport = STANDARD_SIP_PORT;
  25079. }
  25080. } else if (!strcasecmp(v->name, "usereqphone")) {
  25081. ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
  25082. } else if (!strcasecmp(v->name, "fromuser")) {
  25083. ast_string_field_set(peer, fromuser, v->value);
  25084. } else if (!strcasecmp(v->name, "outboundproxy")) {
  25085. struct sip_proxy *proxy;
  25086. if (ast_strlen_zero(v->value)) {
  25087. ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
  25088. continue;
  25089. }
  25090. proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
  25091. if (!proxy) {
  25092. ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
  25093. continue;
  25094. }
  25095. peer->outboundproxy = proxy;
  25096. } else if (!strcasecmp(v->name, "host")) {
  25097. if (!strcasecmp(v->value, "dynamic")) {
  25098. /* They'll register with us */
  25099. if ((!found && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) || !peer->host_dynamic) {
  25100. /* Initialize stuff if this is a new peer, or if it used to
  25101. * not be dynamic before the reload. */
  25102. ast_sockaddr_setnull(&peer->addr);
  25103. }
  25104. peer->host_dynamic = TRUE;
  25105. } else {
  25106. /* Non-dynamic. Make sure we become that way if we're not */
  25107. AST_SCHED_DEL_UNREF(sched, peer->expire,
  25108. unref_peer(peer, "removing register expire ref"));
  25109. peer->host_dynamic = FALSE;
  25110. srvlookup = v->value;
  25111. }
  25112. } else if (!strcasecmp(v->name, "defaultip")) {
  25113. if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
  25114. unref_peer(peer, "unref_peer: from build_peer defaultip");
  25115. return NULL;
  25116. }
  25117. } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
  25118. int ha_error = 0;
  25119. if (!ast_strlen_zero(v->value)) {
  25120. peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
  25121. }
  25122. if (ha_error) {
  25123. ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  25124. }
  25125. } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
  25126. int ha_error = 0;
  25127. if (!ast_strlen_zero(v->value)) {
  25128. peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
  25129. }
  25130. if (ha_error) {
  25131. ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  25132. }
  25133. } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny")) {
  25134. int ha_error = 0;
  25135. peer->directmediaha = ast_append_ha(v->name + 11, v->value, peer->directmediaha, &ha_error);
  25136. if (ha_error) {
  25137. ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  25138. }
  25139. } else if (!strcasecmp(v->name, "port")) {
  25140. peer->portinuri = 1;
  25141. if (!(port = port_str2int(v->value, 0))) {
  25142. if (realtime) {
  25143. /* If stored as integer, could be 0 for some DBs (notably MySQL) */
  25144. peer->portinuri = 0;
  25145. } else {
  25146. ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
  25147. }
  25148. }
  25149. } else if (!strcasecmp(v->name, "callingpres")) {
  25150. peer->callingpres = ast_parse_caller_presentation(v->value);
  25151. if (peer->callingpres == -1) {
  25152. peer->callingpres = atoi(v->value);
  25153. }
  25154. } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) { /* "username" is deprecated */
  25155. ast_string_field_set(peer, username, v->value);
  25156. if (!strcasecmp(v->name, "username")) {
  25157. if (deprecation_warning) {
  25158. ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
  25159. deprecation_warning = 0;
  25160. }
  25161. peer->deprecated_username = 1;
  25162. }
  25163. } else if (!strcasecmp(v->name, "language")) {
  25164. ast_string_field_set(peer, language, v->value);
  25165. } else if (!strcasecmp(v->name, "regexten")) {
  25166. ast_string_field_set(peer, regexten, v->value);
  25167. } else if (!strcasecmp(v->name, "callbackextension")) {
  25168. ast_copy_string(callback, v->value, sizeof(callback));
  25169. } else if (!strcasecmp(v->name, "amaflags")) {
  25170. format = ast_cdr_amaflags2int(v->value);
  25171. if (format < 0) {
  25172. ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
  25173. } else {
  25174. peer->amaflags = format;
  25175. }
  25176. } else if (!strcasecmp(v->name, "maxforwards")) {
  25177. if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
  25178. || peer->maxforwards < 1 || 255 < peer->maxforwards) {
  25179. ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
  25180. peer->maxforwards = sip_cfg.default_max_forwards;
  25181. }
  25182. } else if (!strcasecmp(v->name, "accountcode")) {
  25183. ast_string_field_set(peer, accountcode, v->value);
  25184. } else if (!strcasecmp(v->name, "mohinterpret")) {
  25185. ast_string_field_set(peer, mohinterpret, v->value);
  25186. } else if (!strcasecmp(v->name, "mohsuggest")) {
  25187. ast_string_field_set(peer, mohsuggest, v->value);
  25188. } else if (!strcasecmp(v->name, "parkinglot")) {
  25189. ast_string_field_set(peer, parkinglot, v->value);
  25190. } else if (!strcasecmp(v->name, "rtp_engine")) {
  25191. ast_string_field_set(peer, engine, v->value);
  25192. } else if (!strcasecmp(v->name, "mailbox")) {
  25193. add_peer_mailboxes(peer, v->value);
  25194. } else if (!strcasecmp(v->name, "hasvoicemail")) {
  25195. /* People expect that if 'hasvoicemail' is set, that the mailbox will
  25196. * be also set, even if not explicitly specified. */
  25197. if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
  25198. add_peer_mailboxes(peer, name);
  25199. }
  25200. } else if (!strcasecmp(v->name, "subscribemwi")) {
  25201. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
  25202. } else if (!strcasecmp(v->name, "vmexten")) {
  25203. ast_string_field_set(peer, vmexten, v->value);
  25204. } else if (!strcasecmp(v->name, "callgroup")) {
  25205. peer->callgroup = ast_get_group(v->value);
  25206. } else if (!strcasecmp(v->name, "allowtransfer")) {
  25207. peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
  25208. } else if (!strcasecmp(v->name, "pickupgroup")) {
  25209. peer->pickupgroup = ast_get_group(v->value);
  25210. } else if (!strcasecmp(v->name, "allow")) {
  25211. int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
  25212. if (error) {
  25213. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  25214. }
  25215. } else if (!strcasecmp(v->name, "disallow")) {
  25216. int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
  25217. if (error) {
  25218. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  25219. }
  25220. } else if (!strcasecmp(v->name, "preferred_codec_only")) {
  25221. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
  25222. } else if (!strcasecmp(v->name, "autoframing")) {
  25223. peer->autoframing = ast_true(v->value);
  25224. } else if (!strcasecmp(v->name, "rtptimeout")) {
  25225. if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
  25226. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  25227. peer->rtptimeout = global_rtptimeout;
  25228. }
  25229. } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
  25230. if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
  25231. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  25232. peer->rtpholdtimeout = global_rtpholdtimeout;
  25233. }
  25234. } else if (!strcasecmp(v->name, "rtpkeepalive")) {
  25235. if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
  25236. ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
  25237. peer->rtpkeepalive = global_rtpkeepalive;
  25238. }
  25239. } else if (!strcasecmp(v->name, "timert1")) {
  25240. if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
  25241. ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
  25242. peer->timer_t1 = global_t1min;
  25243. }
  25244. timert1_set = 1;
  25245. } else if (!strcasecmp(v->name, "timerb")) {
  25246. if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
  25247. ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
  25248. peer->timer_b = global_timer_b;
  25249. }
  25250. timerb_set = 1;
  25251. } else if (!strcasecmp(v->name, "setvar")) {
  25252. peer->chanvars = add_var(v->value, peer->chanvars);
  25253. } else if (!strcasecmp(v->name, "header")) {
  25254. char tmp[4096];
  25255. snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
  25256. peer->chanvars = add_var(tmp, peer->chanvars);
  25257. } else if (!strcasecmp(v->name, "qualifyfreq")) {
  25258. int i;
  25259. if (sscanf(v->value, "%30d", &i) == 1) {
  25260. peer->qualifyfreq = i * 1000;
  25261. } else {
  25262. ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
  25263. peer->qualifyfreq = global_qualifyfreq;
  25264. }
  25265. } else if (!strcasecmp(v->name, "maxcallbitrate")) {
  25266. peer->maxcallbitrate = atoi(v->value);
  25267. if (peer->maxcallbitrate < 0) {
  25268. peer->maxcallbitrate = default_maxcallbitrate;
  25269. }
  25270. } else if (!strcasecmp(v->name, "session-timers")) {
  25271. int i = (int) str2stmode(v->value);
  25272. if (i < 0) {
  25273. ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
  25274. peer->stimer.st_mode_oper = global_st_mode;
  25275. } else {
  25276. peer->stimer.st_mode_oper = i;
  25277. }
  25278. } else if (!strcasecmp(v->name, "session-expires")) {
  25279. if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
  25280. ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
  25281. peer->stimer.st_max_se = global_max_se;
  25282. }
  25283. } else if (!strcasecmp(v->name, "session-minse")) {
  25284. if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
  25285. ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
  25286. peer->stimer.st_min_se = global_min_se;
  25287. }
  25288. if (peer->stimer.st_min_se < DEFAULT_MIN_SE) {
  25289. 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);
  25290. peer->stimer.st_min_se = global_min_se;
  25291. }
  25292. } else if (!strcasecmp(v->name, "session-refresher")) {
  25293. int i = (int) str2strefresherparam(v->value);
  25294. if (i < 0) {
  25295. ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
  25296. peer->stimer.st_ref = global_st_refresher;
  25297. } else {
  25298. peer->stimer.st_ref = i;
  25299. }
  25300. } else if (!strcasecmp(v->name, "disallowed_methods")) {
  25301. char *disallow = ast_strdupa(v->value);
  25302. mark_parsed_methods(&peer->disallowed_methods, disallow);
  25303. } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
  25304. ast_string_field_set(peer, unsolicited_mailbox, v->value);
  25305. } else if (!strcasecmp(v->name, "use_q850_reason")) {
  25306. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
  25307. } else if (!strcasecmp(v->name, "encryption")) {
  25308. ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
  25309. } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
  25310. ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
  25311. }
  25312. }
  25313. /* These apply to devstate lookups */
  25314. if (realtime && !strcasecmp(v->name, "lastms")) {
  25315. sscanf(v->value, "%30d", &peer->lastms);
  25316. } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
  25317. ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
  25318. } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
  25319. if (alt_fullcontact && !alt) {
  25320. /* Reset, because the alternate also has a fullcontact and we
  25321. * do NOT want the field value to be doubled. It might be
  25322. * tempting to skip this, but the first table might not have
  25323. * fullcontact and since we're here, we know that the alternate
  25324. * absolutely does. */
  25325. alt_fullcontact = 0;
  25326. ast_str_reset(fullcontact);
  25327. }
  25328. /* Reconstruct field, because realtime separates our value at the ';' */
  25329. if (ast_str_strlen(fullcontact) > 0) {
  25330. ast_str_append(&fullcontact, 0, ";%s", v->value);
  25331. } else {
  25332. ast_str_set(&fullcontact, 0, "%s", v->value);
  25333. }
  25334. } else if (!strcasecmp(v->name, "qualify")) {
  25335. if (!strcasecmp(v->value, "no")) {
  25336. peer->maxms = 0;
  25337. } else if (!strcasecmp(v->value, "yes")) {
  25338. peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
  25339. } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
  25340. 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);
  25341. peer->maxms = 0;
  25342. }
  25343. if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
  25344. /* This would otherwise cause a network storm, where the
  25345. * qualify response refreshes the peer from the database,
  25346. * which in turn causes another qualify to be sent, ad
  25347. * infinitum. */
  25348. 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);
  25349. peer->maxms = 0;
  25350. }
  25351. } else if (!strcasecmp(v->name, "callcounter")) {
  25352. peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
  25353. } else if (!strcasecmp(v->name, "call-limit")) {
  25354. peer->call_limit = atoi(v->value);
  25355. if (peer->call_limit < 0) {
  25356. peer->call_limit = 0;
  25357. }
  25358. } else if (!strcasecmp(v->name, "busylevel")) {
  25359. peer->busy_level = atoi(v->value);
  25360. if (peer->busy_level < 0) {
  25361. peer->busy_level = 0;
  25362. }
  25363. } else if (ast_cc_is_config_param(v->name)) {
  25364. ast_cc_set_param(peer->cc_params, v->name, v->value);
  25365. }
  25366. }
  25367. if (!devstate_only) {
  25368. struct sip_mailbox *mailbox;
  25369. AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
  25370. if (mailbox->delme) {
  25371. AST_LIST_REMOVE_CURRENT(entry);
  25372. destroy_mailbox(mailbox);
  25373. }
  25374. }
  25375. AST_LIST_TRAVERSE_SAFE_END;
  25376. }
  25377. if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
  25378. 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);
  25379. ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
  25380. }
  25381. /* Note that Timer B is dependent upon T1 and MUST NOT be lower
  25382. * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
  25383. if (peer->timer_b < peer->timer_t1 * 64) {
  25384. if (timerb_set && timert1_set) {
  25385. 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);
  25386. } else if (timerb_set) {
  25387. if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
  25388. 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);
  25389. peer->timer_t1 = global_t1min;
  25390. peer->timer_b = peer->timer_t1 * 64;
  25391. }
  25392. peer->timer_t1 = peer->timer_b / 64;
  25393. } else {
  25394. peer->timer_b = peer->timer_t1 * 64;
  25395. }
  25396. }
  25397. if (!peer->default_outbound_transport) {
  25398. /* Set default set of transports */
  25399. peer->transports = default_transports;
  25400. /* Set default primary transport */
  25401. peer->default_outbound_transport = default_primary_transport;
  25402. }
  25403. /* The default transport type set during build_peer should only replace the socket.type when...
  25404. * 1. Registration is not present and the socket.type and default transport types are different.
  25405. * 2. The socket.type is not an acceptable transport type after rebuilding peer.
  25406. * 3. The socket.type is not set yet. */
  25407. if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
  25408. !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
  25409. set_socket_transport(&peer->socket, peer->default_outbound_transport);
  25410. }
  25411. ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
  25412. ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
  25413. ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
  25414. if (ast_str_strlen(fullcontact)) {
  25415. ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
  25416. peer->rt_fromcontact = TRUE;
  25417. /* We have a hostname in the fullcontact, but if we don't have an
  25418. * address listed on the entry (or if it's 'dynamic'), then we need to
  25419. * parse the entry to obtain the IP address, so a dynamic host can be
  25420. * contacted immediately after reload (as opposed to waiting for it to
  25421. * register once again). But if we have an address for this peer and NAT was
  25422. * specified, use that address instead. */
  25423. /* XXX May need to revisit the final argument; does the realtime DB store whether
  25424. * the original contact was over TLS or not? XXX */
  25425. if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) || ast_sockaddr_isnull(&peer->addr)) {
  25426. __set_address_from_contact(ast_str_buffer(fullcontact), &peer->addr, 0);
  25427. }
  25428. }
  25429. if (srvlookup && peer->dnsmgr == NULL) {
  25430. char transport[MAXHOSTNAMELEN];
  25431. char _srvlookup[MAXHOSTNAMELEN];
  25432. char *params;
  25433. ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
  25434. if ((params = strchr(_srvlookup, ';'))) {
  25435. *params++ = '\0';
  25436. }
  25437. snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
  25438. peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type); /* Filter address family */
  25439. if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
  25440. on_dns_update_peer, ref_peer(peer, "Store peer on dnsmgr"))) {
  25441. ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
  25442. unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
  25443. unref_peer(peer, "getting rid of a peer pointer");
  25444. return NULL;
  25445. }
  25446. if (!peer->dnsmgr) {
  25447. /* dnsmgr refresh disabeld, release reference */
  25448. unref_peer(peer, "dnsmgr disabled, unref peer");
  25449. }
  25450. ast_string_field_set(peer, tohost, srvlookup);
  25451. if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
  25452. int ha_error = 0;
  25453. sip_cfg.contact_ha = ast_append_ha("deny", ast_sockaddr_stringify_addr(&peer->addr),
  25454. sip_cfg.contact_ha, &ha_error);
  25455. if (ha_error) {
  25456. ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
  25457. }
  25458. }
  25459. } else if (peer->dnsmgr && !peer->host_dynamic) {
  25460. /* force a refresh here on reload if dnsmgr already exists and host is set. */
  25461. ast_dnsmgr_refresh(peer->dnsmgr);
  25462. }
  25463. if (port && !realtime && peer->host_dynamic) {
  25464. ast_sockaddr_set_port(&peer->defaddr, port);
  25465. } else if (port) {
  25466. ast_sockaddr_set_port(&peer->addr, port);
  25467. }
  25468. if (ast_sockaddr_port(&peer->addr) == 0) {
  25469. ast_sockaddr_set_port(&peer->addr,
  25470. (peer->socket.type & SIP_TRANSPORT_TLS) ?
  25471. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  25472. }
  25473. if (ast_sockaddr_port(&peer->defaddr) == 0) {
  25474. ast_sockaddr_set_port(&peer->defaddr,
  25475. (peer->socket.type & SIP_TRANSPORT_TLS) ?
  25476. STANDARD_TLS_PORT : STANDARD_SIP_PORT);
  25477. }
  25478. if (!peer->socket.port) {
  25479. peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
  25480. }
  25481. if (realtime) {
  25482. int enablepoke = 1;
  25483. if (!sip_cfg.ignore_regexpire && peer->host_dynamic) {
  25484. time_t nowtime = time(NULL);
  25485. if ((nowtime - regseconds) > 0) {
  25486. destroy_association(peer);
  25487. memset(&peer->addr, 0, sizeof(peer->addr));
  25488. peer->lastms = -1;
  25489. enablepoke = 0;
  25490. ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
  25491. }
  25492. }
  25493. /* Startup regular pokes */
  25494. if (!devstate_only && enablepoke) {
  25495. sip_poke_peer(peer, 0);
  25496. }
  25497. }
  25498. if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
  25499. sip_cfg.allowsubscribe = TRUE; /* No global ban any more */
  25500. }
  25501. /* If read-only RT backend, then refresh from local DB cache */
  25502. if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
  25503. reg_source_db(peer);
  25504. }
  25505. /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
  25506. * subscribe to it now. */
  25507. if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
  25508. !AST_LIST_EMPTY(&peer->mailboxes)) {
  25509. add_peer_mwi_subs(peer);
  25510. /* Send MWI from the event cache only. This is so we can send initial
  25511. * MWI if app_voicemail got loaded before chan_sip. If it is the other
  25512. * way, then we will get events when app_voicemail gets loaded. */
  25513. sip_send_mwi_to_peer(peer, 1);
  25514. }
  25515. peer->the_mark = 0;
  25516. ast_free_ha(oldha);
  25517. ast_free_ha(olddirectmediaha);
  25518. if (!ast_strlen_zero(callback)) { /* build string from peer info */
  25519. char *reg_string;
  25520. 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, callback) >= 0) {
  25521. sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
  25522. ast_free(reg_string);
  25523. }
  25524. }
  25525. return peer;
  25526. }
  25527. static int peer_markall_func(void *device, void *arg, int flags)
  25528. {
  25529. struct sip_peer *peer = device;
  25530. peer->the_mark = 1;
  25531. return 0;
  25532. }
  25533. static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
  25534. int global_nat, specific_nat;
  25535. 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))) {
  25536. ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the global setting can make\n");
  25537. ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
  25538. ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
  25539. ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
  25540. 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));
  25541. }
  25542. }
  25543. static void cleanup_all_regs(void)
  25544. {
  25545. /* First, destroy all outstanding registry calls */
  25546. /* This is needed, since otherwise active registry entries will not be destroyed */
  25547. ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do { /* regl is locked */
  25548. ASTOBJ_WRLOCK(iterator); /* now regl is locked, and the object is also locked */
  25549. if (iterator->call) {
  25550. ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
  25551. /* This will also remove references to the registry */
  25552. dialog_unlink_all(iterator->call);
  25553. iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
  25554. }
  25555. if (iterator->expire > -1) {
  25556. AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
  25557. }
  25558. if (iterator->timeout > -1) {
  25559. AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
  25560. }
  25561. if (iterator->dnsmgr) {
  25562. ast_dnsmgr_release(iterator->dnsmgr);
  25563. iterator->dnsmgr = NULL;
  25564. registry_unref(iterator, "reg ptr unref from dnsmgr");
  25565. }
  25566. ASTOBJ_UNLOCK(iterator);
  25567. } while(0));
  25568. }
  25569. /*! \brief Re-read SIP.conf config file
  25570. \note This function reloads all config data, except for
  25571. active peers (with registrations). They will only
  25572. change configuration data at restart, not at reload.
  25573. SIP debug and recordhistory state will not change
  25574. */
  25575. static int reload_config(enum channelreloadreason reason)
  25576. {
  25577. struct ast_config *cfg, *ucfg;
  25578. struct ast_variable *v;
  25579. struct sip_peer *peer;
  25580. char *cat, *stringp, *context, *oldregcontext;
  25581. char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
  25582. struct ast_flags mask[3] = {{0}};
  25583. struct ast_flags setflags[3] = {{0}};
  25584. struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
  25585. int auto_sip_domains = FALSE;
  25586. struct ast_sockaddr old_bindaddr = bindaddr;
  25587. int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
  25588. int subscribe_network_change = 1;
  25589. time_t run_start, run_end;
  25590. int bindport = 0;
  25591. run_start = time(0);
  25592. ast_unload_realtime("sipregs");
  25593. ast_unload_realtime("sippeers");
  25594. cfg = ast_config_load(config, config_flags);
  25595. /* We *must* have a config file otherwise stop immediately */
  25596. if (!cfg) {
  25597. ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
  25598. return -1;
  25599. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  25600. ucfg = ast_config_load("users.conf", config_flags);
  25601. if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
  25602. return 1;
  25603. } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
  25604. ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
  25605. return 1;
  25606. }
  25607. /* Must reread both files, because one changed */
  25608. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  25609. if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
  25610. ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
  25611. ast_config_destroy(ucfg);
  25612. return 1;
  25613. }
  25614. if (!cfg) {
  25615. /* should have been able to reload here */
  25616. ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
  25617. return -1;
  25618. }
  25619. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  25620. ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
  25621. return 1;
  25622. } else {
  25623. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  25624. if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
  25625. ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
  25626. ast_config_destroy(cfg);
  25627. return 1;
  25628. }
  25629. }
  25630. ast_free_ha(sip_cfg.contact_ha);
  25631. sip_cfg.contact_ha = NULL;
  25632. default_tls_cfg.enabled = FALSE; /* Default: Disable TLS */
  25633. if (reason != CHANNEL_MODULE_LOAD) {
  25634. ast_debug(4, "--------------- SIP reload started\n");
  25635. clear_sip_domains();
  25636. ast_mutex_lock(&authl_lock);
  25637. if (authl) {
  25638. ao2_t_ref(authl, -1, "Removing old global authentication");
  25639. authl = NULL;
  25640. }
  25641. ast_mutex_unlock(&authl_lock);
  25642. cleanup_all_regs();
  25643. /* Then, actually destroy users and registry */
  25644. ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
  25645. ast_debug(4, "--------------- Done destroying registry list\n");
  25646. ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
  25647. }
  25648. /* Reset certificate handling for TLS sessions */
  25649. if (reason != CHANNEL_MODULE_LOAD) {
  25650. ast_free(default_tls_cfg.certfile);
  25651. ast_free(default_tls_cfg.pvtfile);
  25652. ast_free(default_tls_cfg.cipher);
  25653. ast_free(default_tls_cfg.cafile);
  25654. ast_free(default_tls_cfg.capath);
  25655. }
  25656. default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
  25657. default_tls_cfg.pvtfile = ast_strdup("");
  25658. default_tls_cfg.cipher = ast_strdup("");
  25659. default_tls_cfg.cafile = ast_strdup("");
  25660. default_tls_cfg.capath = ast_strdup("");
  25661. /* Initialize copy of current sip_cfg.regcontext for later use in removing stale contexts */
  25662. ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
  25663. oldregcontext = oldcontexts;
  25664. /* Clear all flags before setting default values */
  25665. /* Preserve debugging settings for console */
  25666. sipdebug &= sip_debug_console;
  25667. ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
  25668. ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
  25669. ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
  25670. /* Reset IP addresses */
  25671. ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
  25672. memset(&internip, 0, sizeof(internip));
  25673. /* Free memory for local network address mask */
  25674. ast_free_ha(localaddr);
  25675. memset(&localaddr, 0, sizeof(localaddr));
  25676. memset(&externaddr, 0, sizeof(externaddr));
  25677. memset(&media_address, 0, sizeof(media_address));
  25678. memset(&default_prefs, 0 , sizeof(default_prefs));
  25679. memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
  25680. sip_cfg.outboundproxy.force = FALSE; /*!< Don't force proxy usage, use route: headers */
  25681. default_transports = SIP_TRANSPORT_UDP;
  25682. default_primary_transport = SIP_TRANSPORT_UDP;
  25683. ourport_tcp = STANDARD_SIP_PORT;
  25684. ourport_tls = STANDARD_TLS_PORT;
  25685. externtcpport = STANDARD_SIP_PORT;
  25686. externtlsport = STANDARD_TLS_PORT;
  25687. sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
  25688. global_tos_sip = DEFAULT_TOS_SIP;
  25689. global_tos_audio = DEFAULT_TOS_AUDIO;
  25690. global_tos_video = DEFAULT_TOS_VIDEO;
  25691. global_tos_text = DEFAULT_TOS_TEXT;
  25692. global_cos_sip = DEFAULT_COS_SIP;
  25693. global_cos_audio = DEFAULT_COS_AUDIO;
  25694. global_cos_video = DEFAULT_COS_VIDEO;
  25695. global_cos_text = DEFAULT_COS_TEXT;
  25696. externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
  25697. externexpire = 0; /* Expiration for DNS re-issuing */
  25698. externrefresh = 10;
  25699. /* Reset channel settings to default before re-configuring */
  25700. sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
  25701. sip_cfg.regcontext[0] = '\0';
  25702. sip_cfg.capability = DEFAULT_CAPABILITY;
  25703. sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
  25704. sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
  25705. sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
  25706. sip_cfg.notifycid = DEFAULT_NOTIFYCID;
  25707. sip_cfg.notifyhold = FALSE; /*!< Keep track of hold status for a peer */
  25708. sip_cfg.directrtpsetup = FALSE; /* Experimental feature, disabled by default */
  25709. sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
  25710. sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
  25711. sip_cfg.allowsubscribe = FALSE;
  25712. sip_cfg.disallowed_methods = SIP_UNKNOWN;
  25713. sip_cfg.contact_ha = NULL; /* Reset the contact ACL */
  25714. snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
  25715. snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
  25716. snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
  25717. global_prematuremediafilter = TRUE;
  25718. ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
  25719. ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
  25720. sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
  25721. ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
  25722. ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
  25723. sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
  25724. global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
  25725. global_regattempts_max = 0;
  25726. global_reg_retry_403 = 0;
  25727. sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
  25728. sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
  25729. global_autoframing = 0;
  25730. sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
  25731. global_callcounter = DEFAULT_CALLCOUNTER;
  25732. global_match_auth_username = FALSE; /*!< Match auth username if available instead of From: Default off. */
  25733. global_rtptimeout = 0;
  25734. global_rtpholdtimeout = 0;
  25735. global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
  25736. sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
  25737. sip_cfg.rtautoclear = 120;
  25738. ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for all devices: TRUE */
  25739. ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES); /* Default for all devices: Yes */
  25740. sip_cfg.peer_rtupdate = TRUE;
  25741. global_dynamic_exclude_static = 0; /* Exclude static peers */
  25742. sip_cfg.tcp_enabled = FALSE;
  25743. /* Session-Timers */
  25744. global_st_mode = SESSION_TIMER_MODE_ACCEPT;
  25745. global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
  25746. global_min_se = DEFAULT_MIN_SE;
  25747. global_max_se = DEFAULT_MAX_SE;
  25748. /* Peer poking settings */
  25749. global_qualify_gap = DEFAULT_QUALIFY_GAP;
  25750. global_qualify_peers = DEFAULT_QUALIFY_PEERS;
  25751. /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
  25752. ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
  25753. sip_cfg.default_subscribecontext[0] = '\0';
  25754. sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
  25755. default_language[0] = '\0';
  25756. default_fromdomain[0] = '\0';
  25757. default_fromdomainport = 0;
  25758. default_qualify = DEFAULT_QUALIFY;
  25759. default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
  25760. ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
  25761. ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
  25762. ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
  25763. ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
  25764. ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA); /*!< Allow re-invites */
  25765. ast_set_flag(&global_flags[0], SIP_NAT_FORCE_RPORT); /*!< Default to nat=force_rport */
  25766. ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
  25767. ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
  25768. /* Debugging settings, always default to off */
  25769. dumphistory = FALSE;
  25770. recordhistory = FALSE;
  25771. sipdebug &= ~sip_debug_config;
  25772. /* Misc settings for the channel */
  25773. global_relaxdtmf = FALSE;
  25774. sip_cfg.callevents = DEFAULT_CALLEVENTS;
  25775. global_authfailureevents = FALSE;
  25776. global_t1 = DEFAULT_TIMER_T1;
  25777. global_timer_b = 64 * DEFAULT_TIMER_T1;
  25778. global_t1min = DEFAULT_T1MIN;
  25779. global_qualifyfreq = DEFAULT_QUALIFYFREQ;
  25780. global_t38_maxdatagram = -1;
  25781. global_shrinkcallerid = 1;
  25782. authlimit = DEFAULT_AUTHLIMIT;
  25783. authtimeout = DEFAULT_AUTHTIMEOUT;
  25784. global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
  25785. sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
  25786. /* Copy the default jb config over global_jbconf */
  25787. memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
  25788. ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
  25789. ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
  25790. ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
  25791. ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
  25792. /* Read the [general] config section of sip.conf (or from realtime config) */
  25793. for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
  25794. if (handle_common_options(&setflags[0], &mask[0], v)) {
  25795. continue;
  25796. }
  25797. if (handle_t38_options(&setflags[0], &mask[0], v, &global_t38_maxdatagram)) {
  25798. continue;
  25799. }
  25800. /* handle jb conf */
  25801. if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
  25802. continue;
  25803. /* handle tls conf, don't allow setting of tlsverifyclient as it isn't supported by chan_sip */
  25804. if (!strcasecmp(v->name, "tlsverifyclient")) {
  25805. ast_log(LOG_WARNING, "Ignoring unsupported option 'tlsverifyclient'\n");
  25806. continue;
  25807. } else if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
  25808. continue;
  25809. }
  25810. if (!strcasecmp(v->name, "context")) {
  25811. ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
  25812. } else if (!strcasecmp(v->name, "subscribecontext")) {
  25813. ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
  25814. } else if (!strcasecmp(v->name, "callcounter")) {
  25815. global_callcounter = ast_true(v->value) ? 1 : 0;
  25816. } else if (!strcasecmp(v->name, "allowguest")) {
  25817. sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
  25818. } else if (!strcasecmp(v->name, "realm")) {
  25819. ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
  25820. } else if (!strcasecmp(v->name, "domainsasrealm")) {
  25821. sip_cfg.domainsasrealm = ast_true(v->value);
  25822. } else if (!strcasecmp(v->name, "useragent")) {
  25823. ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
  25824. ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
  25825. } else if (!strcasecmp(v->name, "sdpsession")) {
  25826. ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
  25827. } else if (!strcasecmp(v->name, "sdpowner")) {
  25828. /* Field cannot contain spaces */
  25829. if (!strstr(v->value, " ")) {
  25830. ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
  25831. } else {
  25832. ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
  25833. }
  25834. } else if (!strcasecmp(v->name, "allowtransfer")) {
  25835. sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
  25836. } else if (!strcasecmp(v->name, "rtcachefriends")) {
  25837. ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
  25838. } else if (!strcasecmp(v->name, "rtsavesysname")) {
  25839. sip_cfg.rtsave_sysname = ast_true(v->value);
  25840. } else if (!strcasecmp(v->name, "rtupdate")) {
  25841. sip_cfg.peer_rtupdate = ast_true(v->value);
  25842. } else if (!strcasecmp(v->name, "ignoreregexpire")) {
  25843. sip_cfg.ignore_regexpire = ast_true(v->value);
  25844. } else if (!strcasecmp(v->name, "timert1")) {
  25845. /* Defaults to 500ms, but RFC 3261 states that it is recommended
  25846. * for the value to be set higher, though a lower value is only
  25847. * allowed on private networks unconnected to the Internet. */
  25848. global_t1 = atoi(v->value);
  25849. } else if (!strcasecmp(v->name, "timerb")) {
  25850. int tmp = atoi(v->value);
  25851. if (tmp < 500) {
  25852. global_timer_b = global_t1 * 64;
  25853. ast_log(LOG_WARNING, "Invalid value for timerb ('%s'). Setting to default ('%d').\n", v->value, global_timer_b);
  25854. }
  25855. timerb_set = 1;
  25856. } else if (!strcasecmp(v->name, "t1min")) {
  25857. global_t1min = atoi(v->value);
  25858. } else if (!strcasecmp(v->name, "transport")) {
  25859. char *val = ast_strdupa(v->value);
  25860. char *trans;
  25861. default_transports = default_primary_transport = 0;
  25862. while ((trans = strsep(&val, ","))) {
  25863. trans = ast_skip_blanks(trans);
  25864. if (!strncasecmp(trans, "udp", 3)) {
  25865. default_transports |= SIP_TRANSPORT_UDP;
  25866. } else if (!strncasecmp(trans, "tcp", 3)) {
  25867. default_transports |= SIP_TRANSPORT_TCP;
  25868. } else if (!strncasecmp(trans, "tls", 3)) {
  25869. default_transports |= SIP_TRANSPORT_TLS;
  25870. } else {
  25871. ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
  25872. }
  25873. if (default_primary_transport == 0) {
  25874. default_primary_transport = default_transports;
  25875. }
  25876. }
  25877. } else if (!strcasecmp(v->name, "tcpenable")) {
  25878. if (!ast_false(v->value)) {
  25879. ast_debug(2, "Enabling TCP socket for listening\n");
  25880. sip_cfg.tcp_enabled = TRUE;
  25881. }
  25882. } else if (!strcasecmp(v->name, "tcpbindaddr")) {
  25883. if (ast_parse_arg(v->value, PARSE_ADDR,
  25884. &sip_tcp_desc.local_address)) {
  25885. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
  25886. v->name, v->value, v->lineno, config);
  25887. }
  25888. ast_debug(2, "Setting TCP socket address to %s\n",
  25889. ast_sockaddr_stringify(&sip_tcp_desc.local_address));
  25890. } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
  25891. global_dynamic_exclude_static = ast_true(v->value);
  25892. } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
  25893. int ha_error = 0;
  25894. sip_cfg.contact_ha = ast_append_ha(v->name + 7, v->value, sip_cfg.contact_ha, &ha_error);
  25895. if (ha_error) {
  25896. ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
  25897. }
  25898. } else if (!strcasecmp(v->name, "rtautoclear")) {
  25899. int i = atoi(v->value);
  25900. if (i > 0) {
  25901. sip_cfg.rtautoclear = i;
  25902. } else {
  25903. i = 0;
  25904. }
  25905. ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
  25906. } else if (!strcasecmp(v->name, "usereqphone")) {
  25907. ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
  25908. } else if (!strcasecmp(v->name, "prematuremedia")) {
  25909. global_prematuremediafilter = ast_true(v->value);
  25910. } else if (!strcasecmp(v->name, "relaxdtmf")) {
  25911. global_relaxdtmf = ast_true(v->value);
  25912. } else if (!strcasecmp(v->name, "vmexten")) {
  25913. ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
  25914. } else if (!strcasecmp(v->name, "rtptimeout")) {
  25915. if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
  25916. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  25917. global_rtptimeout = 0;
  25918. }
  25919. } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
  25920. if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
  25921. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  25922. global_rtpholdtimeout = 0;
  25923. }
  25924. } else if (!strcasecmp(v->name, "rtpkeepalive")) {
  25925. if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
  25926. ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
  25927. global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
  25928. }
  25929. } else if (!strcasecmp(v->name, "compactheaders")) {
  25930. sip_cfg.compactheaders = ast_true(v->value);
  25931. } else if (!strcasecmp(v->name, "notifymimetype")) {
  25932. ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
  25933. } else if (!strcasecmp(v->name, "directrtpsetup")) {
  25934. sip_cfg.directrtpsetup = ast_true(v->value);
  25935. } else if (!strcasecmp(v->name, "notifyringing")) {
  25936. sip_cfg.notifyringing = ast_true(v->value);
  25937. } else if (!strcasecmp(v->name, "notifyhold")) {
  25938. sip_cfg.notifyhold = ast_true(v->value);
  25939. } else if (!strcasecmp(v->name, "notifycid")) {
  25940. if (!strcasecmp(v->value, "ignore-context")) {
  25941. sip_cfg.notifycid = IGNORE_CONTEXT;
  25942. } else {
  25943. sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
  25944. }
  25945. } else if (!strcasecmp(v->name, "alwaysauthreject")) {
  25946. sip_cfg.alwaysauthreject = ast_true(v->value);
  25947. } else if (!strcasecmp(v->name, "auth_options_requests")) {
  25948. if (ast_true(v->value)) {
  25949. sip_cfg.auth_options_requests = 1;
  25950. }
  25951. } else if (!strcasecmp(v->name, "mohinterpret")) {
  25952. ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
  25953. } else if (!strcasecmp(v->name, "mohsuggest")) {
  25954. ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
  25955. } else if (!strcasecmp(v->name, "language")) {
  25956. ast_copy_string(default_language, v->value, sizeof(default_language));
  25957. } else if (!strcasecmp(v->name, "regcontext")) {
  25958. ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
  25959. stringp = newcontexts;
  25960. /* Let's remove any contexts that are no longer defined in regcontext */
  25961. cleanup_stale_contexts(stringp, oldregcontext);
  25962. /* Create contexts if they don't exist already */
  25963. while ((context = strsep(&stringp, "&"))) {
  25964. ast_copy_string(used_context, context, sizeof(used_context));
  25965. ast_context_find_or_create(NULL, NULL, context, "SIP");
  25966. }
  25967. ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
  25968. } else if (!strcasecmp(v->name, "regextenonqualify")) {
  25969. sip_cfg.regextenonqualify = ast_true(v->value);
  25970. } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
  25971. sip_cfg.legacy_useroption_parsing = ast_true(v->value);
  25972. } else if (!strcasecmp(v->name, "callerid")) {
  25973. ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
  25974. } else if (!strcasecmp(v->name, "mwi_from")) {
  25975. ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
  25976. } else if (!strcasecmp(v->name, "fromdomain")) {
  25977. char *fromdomainport;
  25978. ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
  25979. if ((fromdomainport = strchr(default_fromdomain, ':'))) {
  25980. *fromdomainport++ = '\0';
  25981. if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
  25982. ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
  25983. }
  25984. } else {
  25985. default_fromdomainport = STANDARD_SIP_PORT;
  25986. }
  25987. } else if (!strcasecmp(v->name, "outboundproxy")) {
  25988. struct sip_proxy *proxy;
  25989. if (ast_strlen_zero(v->value)) {
  25990. ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
  25991. continue;
  25992. }
  25993. proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
  25994. if (!proxy) {
  25995. ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
  25996. continue;
  25997. }
  25998. } else if (!strcasecmp(v->name, "autocreatepeer")) {
  25999. sip_cfg.autocreatepeer = ast_true(v->value);
  26000. } else if (!strcasecmp(v->name, "match_auth_username")) {
  26001. global_match_auth_username = ast_true(v->value);
  26002. } else if (!strcasecmp(v->name, "srvlookup")) {
  26003. sip_cfg.srvlookup = ast_true(v->value);
  26004. } else if (!strcasecmp(v->name, "pedantic")) {
  26005. sip_cfg.pedanticsipchecking = ast_true(v->value);
  26006. } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
  26007. max_expiry = atoi(v->value);
  26008. if (max_expiry < 1) {
  26009. max_expiry = DEFAULT_MAX_EXPIRY;
  26010. }
  26011. } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
  26012. min_expiry = atoi(v->value);
  26013. if (min_expiry < 1) {
  26014. min_expiry = DEFAULT_MIN_EXPIRY;
  26015. }
  26016. } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
  26017. default_expiry = atoi(v->value);
  26018. if (default_expiry < 1) {
  26019. default_expiry = DEFAULT_DEFAULT_EXPIRY;
  26020. }
  26021. } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
  26022. mwi_expiry = atoi(v->value);
  26023. if (mwi_expiry < 1) {
  26024. mwi_expiry = DEFAULT_MWI_EXPIRY;
  26025. }
  26026. } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
  26027. if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
  26028. &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
  26029. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
  26030. v->name, v->value, v->lineno, config);
  26031. }
  26032. } else if (!strcasecmp(v->name, "tcpauthlimit")) {
  26033. if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
  26034. &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
  26035. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
  26036. v->name, v->value, v->lineno, config);
  26037. }
  26038. } else if (!strcasecmp(v->name, "sipdebug")) {
  26039. if (ast_true(v->value))
  26040. sipdebug |= sip_debug_config;
  26041. } else if (!strcasecmp(v->name, "dumphistory")) {
  26042. dumphistory = ast_true(v->value);
  26043. } else if (!strcasecmp(v->name, "recordhistory")) {
  26044. recordhistory = ast_true(v->value);
  26045. } else if (!strcasecmp(v->name, "registertimeout")) {
  26046. global_reg_timeout = atoi(v->value);
  26047. if (global_reg_timeout < 1) {
  26048. global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
  26049. }
  26050. } else if (!strcasecmp(v->name, "registerattempts")) {
  26051. global_regattempts_max = atoi(v->value);
  26052. } else if (!strcasecmp(v->name, "register_retry_403")) {
  26053. global_reg_retry_403 = ast_true(v->value);
  26054. } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
  26055. if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
  26056. ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
  26057. }
  26058. } else if (!strcasecmp(v->name, "localnet")) {
  26059. struct ast_ha *na;
  26060. int ha_error = 0;
  26061. if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
  26062. ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
  26063. } else {
  26064. localaddr = na;
  26065. }
  26066. if (ha_error) {
  26067. ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
  26068. }
  26069. } else if (!strcasecmp(v->name, "media_address")) {
  26070. if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
  26071. ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
  26072. } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
  26073. if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
  26074. ast_log(LOG_WARNING,
  26075. "Invalid address for externaddr keyword: %s\n",
  26076. v->value);
  26077. }
  26078. externexpire = 0;
  26079. } else if (!strcasecmp(v->name, "externhost")) {
  26080. ast_copy_string(externhost, v->value, sizeof(externhost));
  26081. if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
  26082. ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
  26083. }
  26084. externexpire = time(NULL);
  26085. } else if (!strcasecmp(v->name, "externrefresh")) {
  26086. if (sscanf(v->value, "%30d", &externrefresh) != 1) {
  26087. ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
  26088. externrefresh = 10;
  26089. }
  26090. } else if (!strcasecmp(v->name, "externtcpport")) {
  26091. if (!(externtcpport = port_str2int(v->value, 0))) {
  26092. ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
  26093. externtcpport = 0;
  26094. }
  26095. } else if (!strcasecmp(v->name, "externtlsport")) {
  26096. if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
  26097. ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
  26098. }
  26099. } else if (!strcasecmp(v->name, "allow")) {
  26100. int error = ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, TRUE);
  26101. if (error) {
  26102. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  26103. }
  26104. } else if (!strcasecmp(v->name, "disallow")) {
  26105. int error = ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, FALSE);
  26106. if (error) {
  26107. ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
  26108. }
  26109. } else if (!strcasecmp(v->name, "preferred_codec_only")) {
  26110. ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
  26111. } else if (!strcasecmp(v->name, "autoframing")) {
  26112. global_autoframing = ast_true(v->value);
  26113. } else if (!strcasecmp(v->name, "allowexternaldomains")) {
  26114. sip_cfg.allow_external_domains = ast_true(v->value);
  26115. } else if (!strcasecmp(v->name, "autodomain")) {
  26116. auto_sip_domains = ast_true(v->value);
  26117. } else if (!strcasecmp(v->name, "domain")) {
  26118. char *domain = ast_strdupa(v->value);
  26119. char *cntx = strchr(domain, ',');
  26120. if (cntx) {
  26121. *cntx++ = '\0';
  26122. }
  26123. if (ast_strlen_zero(cntx)) {
  26124. ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
  26125. }
  26126. if (ast_strlen_zero(domain)) {
  26127. ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
  26128. } else {
  26129. add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
  26130. }
  26131. } else if (!strcasecmp(v->name, "register")) {
  26132. if (sip_register(v->value, v->lineno) == 0) {
  26133. registry_count++;
  26134. }
  26135. } else if (!strcasecmp(v->name, "mwi")) {
  26136. sip_subscribe_mwi(v->value, v->lineno);
  26137. } else if (!strcasecmp(v->name, "tos_sip")) {
  26138. if (ast_str2tos(v->value, &global_tos_sip)) {
  26139. ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
  26140. }
  26141. } else if (!strcasecmp(v->name, "tos_audio")) {
  26142. if (ast_str2tos(v->value, &global_tos_audio)) {
  26143. ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
  26144. }
  26145. } else if (!strcasecmp(v->name, "tos_video")) {
  26146. if (ast_str2tos(v->value, &global_tos_video)) {
  26147. ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
  26148. }
  26149. } else if (!strcasecmp(v->name, "tos_text")) {
  26150. if (ast_str2tos(v->value, &global_tos_text)) {
  26151. ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
  26152. }
  26153. } else if (!strcasecmp(v->name, "cos_sip")) {
  26154. if (ast_str2cos(v->value, &global_cos_sip)) {
  26155. ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
  26156. }
  26157. } else if (!strcasecmp(v->name, "cos_audio")) {
  26158. if (ast_str2cos(v->value, &global_cos_audio)) {
  26159. ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
  26160. }
  26161. } else if (!strcasecmp(v->name, "cos_video")) {
  26162. if (ast_str2cos(v->value, &global_cos_video)) {
  26163. ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
  26164. }
  26165. } else if (!strcasecmp(v->name, "cos_text")) {
  26166. if (ast_str2cos(v->value, &global_cos_text)) {
  26167. ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
  26168. }
  26169. } else if (!strcasecmp(v->name, "bindport")) {
  26170. if (sscanf(v->value, "%5d", &bindport) != 1) {
  26171. ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
  26172. }
  26173. } else if (!strcasecmp(v->name, "qualify")) {
  26174. if (!strcasecmp(v->value, "no")) {
  26175. default_qualify = 0;
  26176. } else if (!strcasecmp(v->value, "yes")) {
  26177. default_qualify = DEFAULT_MAXMS;
  26178. } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
  26179. ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
  26180. default_qualify = 0;
  26181. }
  26182. } else if (!strcasecmp(v->name, "qualifyfreq")) {
  26183. int i;
  26184. if (sscanf(v->value, "%30d", &i) == 1) {
  26185. global_qualifyfreq = i * 1000;
  26186. } else {
  26187. ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
  26188. global_qualifyfreq = DEFAULT_QUALIFYFREQ;
  26189. }
  26190. } else if (!strcasecmp(v->name, "callevents")) {
  26191. sip_cfg.callevents = ast_true(v->value);
  26192. } else if (!strcasecmp(v->name, "authfailureevents")) {
  26193. global_authfailureevents = ast_true(v->value);
  26194. } else if (!strcasecmp(v->name, "maxcallbitrate")) {
  26195. default_maxcallbitrate = atoi(v->value);
  26196. if (default_maxcallbitrate < 0)
  26197. default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
  26198. } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
  26199. sip_cfg.matchexternaddrlocally = ast_true(v->value);
  26200. } else if (!strcasecmp(v->name, "session-timers")) {
  26201. int i = (int) str2stmode(v->value);
  26202. if (i < 0) {
  26203. ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
  26204. global_st_mode = SESSION_TIMER_MODE_ACCEPT;
  26205. } else {
  26206. global_st_mode = i;
  26207. }
  26208. } else if (!strcasecmp(v->name, "session-expires")) {
  26209. if (sscanf(v->value, "%30d", &global_max_se) != 1) {
  26210. ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
  26211. global_max_se = DEFAULT_MAX_SE;
  26212. }
  26213. } else if (!strcasecmp(v->name, "session-minse")) {
  26214. if (sscanf(v->value, "%30d", &global_min_se) != 1) {
  26215. ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
  26216. global_min_se = DEFAULT_MIN_SE;
  26217. }
  26218. if (global_min_se < DEFAULT_MIN_SE) {
  26219. 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);
  26220. global_min_se = DEFAULT_MIN_SE;
  26221. }
  26222. } else if (!strcasecmp(v->name, "session-refresher")) {
  26223. int i = (int) str2strefresherparam(v->value);
  26224. if (i < 0) {
  26225. ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
  26226. global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
  26227. } else {
  26228. global_st_refresher = i;
  26229. }
  26230. } else if (!strcasecmp(v->name, "storesipcause")) {
  26231. global_store_sip_cause = ast_true(v->value);
  26232. } else if (!strcasecmp(v->name, "qualifygap")) {
  26233. if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
  26234. ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
  26235. global_qualify_gap = DEFAULT_QUALIFY_GAP;
  26236. }
  26237. } else if (!strcasecmp(v->name, "qualifypeers")) {
  26238. if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
  26239. ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
  26240. global_qualify_peers = DEFAULT_QUALIFY_PEERS;
  26241. }
  26242. } else if (!strcasecmp(v->name, "disallowed_methods")) {
  26243. char *disallow = ast_strdupa(v->value);
  26244. mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
  26245. } else if (!strcasecmp(v->name, "shrinkcallerid")) {
  26246. if (ast_true(v->value)) {
  26247. global_shrinkcallerid = 1;
  26248. } else if (ast_false(v->value)) {
  26249. global_shrinkcallerid = 0;
  26250. } else {
  26251. ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
  26252. }
  26253. } else if (!strcasecmp(v->name, "use_q850_reason")) {
  26254. ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
  26255. } else if (!strcasecmp(v->name, "maxforwards")) {
  26256. if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
  26257. || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
  26258. ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
  26259. sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
  26260. }
  26261. } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
  26262. if (ast_true(v->value)) {
  26263. subscribe_network_change = 1;
  26264. } else if (ast_false(v->value)) {
  26265. subscribe_network_change = 0;
  26266. } else {
  26267. ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
  26268. }
  26269. } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
  26270. ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
  26271. } else if (!strcasecmp(v->name, "parkinglot")) {
  26272. ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
  26273. }
  26274. }
  26275. /* Override global defaults if setting found in general section */
  26276. ast_copy_flags(&global_flags[0], &setflags[0], mask[0].flags);
  26277. ast_copy_flags(&global_flags[1], &setflags[1], mask[1].flags);
  26278. ast_copy_flags(&global_flags[2], &setflags[2], mask[2].flags);
  26279. if (subscribe_network_change) {
  26280. network_change_event_subscribe();
  26281. } else {
  26282. network_change_event_unsubscribe();
  26283. }
  26284. if (global_t1 < global_t1min) {
  26285. ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d). Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
  26286. global_t1 = global_t1min;
  26287. }
  26288. if (global_timer_b < global_t1 * 64) {
  26289. if (timerb_set && timert1_set) {
  26290. 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);
  26291. } else if (timerb_set) {
  26292. if ((global_t1 = global_timer_b / 64) < global_t1min) {
  26293. 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);
  26294. global_t1 = global_t1min;
  26295. global_timer_b = global_t1 * 64;
  26296. }
  26297. } else {
  26298. global_timer_b = global_t1 * 64;
  26299. }
  26300. }
  26301. if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
  26302. ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
  26303. sip_cfg.allow_external_domains = 1;
  26304. }
  26305. /* If not or badly configured, set default transports */
  26306. if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
  26307. ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
  26308. default_primary_transport &= ~SIP_TRANSPORT_TCP;
  26309. default_transports &= ~SIP_TRANSPORT_TCP;
  26310. }
  26311. if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
  26312. ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
  26313. default_primary_transport &= ~SIP_TRANSPORT_TLS;
  26314. default_transports &= ~SIP_TRANSPORT_TLS;
  26315. }
  26316. if (!default_transports) {
  26317. ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
  26318. default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
  26319. } else if (!default_primary_transport) {
  26320. ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
  26321. default_primary_transport = SIP_TRANSPORT_UDP;
  26322. }
  26323. /* Build list of authentication to various SIP realms, i.e. service providers */
  26324. for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
  26325. /* Format for authentication is auth = username:password@realm */
  26326. if (!strcasecmp(v->name, "auth")) {
  26327. add_realm_authentication(&authl, v->value, v->lineno);
  26328. }
  26329. }
  26330. if (bindport) {
  26331. if (ast_sockaddr_port(&bindaddr)) {
  26332. ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
  26333. "Using %d.\n", bindport);
  26334. }
  26335. ast_sockaddr_set_port(&bindaddr, bindport);
  26336. }
  26337. if (!ast_sockaddr_port(&bindaddr)) {
  26338. ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
  26339. }
  26340. /* Set UDP address and open socket */
  26341. ast_sockaddr_copy(&internip, &bindaddr);
  26342. if (ast_find_ourip(&internip, &bindaddr, 0)) {
  26343. ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
  26344. ast_config_destroy(cfg);
  26345. return 0;
  26346. }
  26347. ast_mutex_lock(&netlock);
  26348. if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
  26349. close(sipsock);
  26350. sipsock = -1;
  26351. }
  26352. if (sipsock < 0) {
  26353. sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
  26354. AF_INET6 : AF_INET, SOCK_DGRAM, 0);
  26355. if (sipsock < 0) {
  26356. ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
  26357. ast_config_destroy(cfg);
  26358. ast_mutex_unlock(&netlock);
  26359. return -1;
  26360. } else {
  26361. /* Allow SIP clients on the same host to access us: */
  26362. const int reuseFlag = 1;
  26363. setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
  26364. (const char*)&reuseFlag,
  26365. sizeof reuseFlag);
  26366. ast_enable_packet_fragmentation(sipsock);
  26367. if (ast_bind(sipsock, &bindaddr) < 0) {
  26368. ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
  26369. ast_sockaddr_stringify(&bindaddr), strerror(errno));
  26370. close(sipsock);
  26371. sipsock = -1;
  26372. } else {
  26373. ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
  26374. ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
  26375. }
  26376. }
  26377. } else {
  26378. ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
  26379. }
  26380. ast_mutex_unlock(&netlock);
  26381. /* Start TCP server */
  26382. if (sip_cfg.tcp_enabled) {
  26383. if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
  26384. ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
  26385. }
  26386. if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
  26387. ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
  26388. }
  26389. } else {
  26390. ast_sockaddr_setnull(&sip_tcp_desc.local_address);
  26391. }
  26392. ast_tcptls_server_start(&sip_tcp_desc);
  26393. if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
  26394. /* TCP server start failed. Tell the admin */
  26395. ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
  26396. } else {
  26397. ast_debug(2, "SIP TCP server started\n");
  26398. }
  26399. /* Start TLS server if needed */
  26400. memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
  26401. if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
  26402. if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
  26403. ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
  26404. ast_sockaddr_set_port(&sip_tls_desc.local_address,
  26405. STANDARD_TLS_PORT);
  26406. }
  26407. if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
  26408. ast_sockaddr_set_port(&sip_tls_desc.local_address,
  26409. STANDARD_TLS_PORT);
  26410. }
  26411. ast_tcptls_server_start(&sip_tls_desc);
  26412. if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
  26413. ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
  26414. sip_tls_desc.tls_cfg = NULL;
  26415. }
  26416. } else if (sip_tls_desc.tls_cfg->enabled) {
  26417. sip_tls_desc.tls_cfg = NULL;
  26418. ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
  26419. }
  26420. if (ucfg) {
  26421. struct ast_variable *gen;
  26422. int genhassip, genregistersip;
  26423. const char *hassip, *registersip;
  26424. genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
  26425. genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
  26426. gen = ast_variable_browse(ucfg, "general");
  26427. cat = ast_category_browse(ucfg, NULL);
  26428. while (cat) {
  26429. if (strcasecmp(cat, "general")) {
  26430. hassip = ast_variable_retrieve(ucfg, cat, "hassip");
  26431. registersip = ast_variable_retrieve(ucfg, cat, "registersip");
  26432. if (ast_true(hassip) || (!hassip && genhassip)) {
  26433. peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
  26434. if (peer) {
  26435. /* user.conf entries are always of type friend */
  26436. peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
  26437. ao2_t_link(peers, peer, "link peer into peer table");
  26438. if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
  26439. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  26440. }
  26441. unref_peer(peer, "unref_peer: from reload_config");
  26442. peer_count++;
  26443. }
  26444. }
  26445. if (ast_true(registersip) || (!registersip && genregistersip)) {
  26446. char tmp[256];
  26447. const char *host = ast_variable_retrieve(ucfg, cat, "host");
  26448. const char *username = ast_variable_retrieve(ucfg, cat, "username");
  26449. const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
  26450. const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
  26451. const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
  26452. if (!host) {
  26453. host = ast_variable_retrieve(ucfg, "general", "host");
  26454. }
  26455. if (!username) {
  26456. username = ast_variable_retrieve(ucfg, "general", "username");
  26457. }
  26458. if (!secret) {
  26459. secret = ast_variable_retrieve(ucfg, "general", "secret");
  26460. }
  26461. if (!contact) {
  26462. contact = "s";
  26463. }
  26464. if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
  26465. if (!ast_strlen_zero(secret)) {
  26466. if (!ast_strlen_zero(authuser)) {
  26467. snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
  26468. } else {
  26469. snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
  26470. }
  26471. } else if (!ast_strlen_zero(authuser)) {
  26472. snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
  26473. } else {
  26474. snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
  26475. }
  26476. if (sip_register(tmp, 0) == 0) {
  26477. registry_count++;
  26478. }
  26479. }
  26480. }
  26481. }
  26482. cat = ast_category_browse(ucfg, cat);
  26483. }
  26484. ast_config_destroy(ucfg);
  26485. }
  26486. /* Load peers, users and friends */
  26487. cat = NULL;
  26488. while ( (cat = ast_category_browse(cfg, cat)) ) {
  26489. const char *utype;
  26490. if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
  26491. continue;
  26492. utype = ast_variable_retrieve(cfg, cat, "type");
  26493. if (!utype) {
  26494. ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
  26495. continue;
  26496. } else {
  26497. if (!strcasecmp(utype, "user")) {
  26498. ;
  26499. } else if (!strcasecmp(utype, "friend")) {
  26500. ;
  26501. } else if (!strcasecmp(utype, "peer")) {
  26502. ;
  26503. } else {
  26504. ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
  26505. continue;
  26506. }
  26507. peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
  26508. if (peer) {
  26509. display_nat_warning(cat, reason, &peer->flags[0]);
  26510. ao2_t_link(peers, peer, "link peer into peers table");
  26511. if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
  26512. ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
  26513. }
  26514. unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
  26515. peer_count++;
  26516. }
  26517. }
  26518. }
  26519. /* Add default domains - host name, IP address and IP:port
  26520. * Only do this if user added any sip domain with "localdomains"
  26521. * In order to *not* break backwards compatibility
  26522. * Some phones address us at IP only, some with additional port number
  26523. */
  26524. if (auto_sip_domains) {
  26525. char temp[MAXHOSTNAMELEN];
  26526. /* First our default IP address */
  26527. if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
  26528. add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
  26529. SIP_DOMAIN_AUTO, NULL);
  26530. } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
  26531. /* Our internal IP address, if configured */
  26532. add_sip_domain(ast_sockaddr_stringify_addr(&internip),
  26533. SIP_DOMAIN_AUTO, NULL);
  26534. } else {
  26535. ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
  26536. }
  26537. /* If TCP is running on a different IP than UDP, then add it too */
  26538. if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
  26539. !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
  26540. add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
  26541. SIP_DOMAIN_AUTO, NULL);
  26542. }
  26543. /* If TLS is running on a different IP than UDP and TCP, then add that too */
  26544. if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
  26545. !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
  26546. !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
  26547. &sip_tls_desc.local_address)) {
  26548. add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
  26549. SIP_DOMAIN_AUTO, NULL);
  26550. }
  26551. /* Our extern IP address, if configured */
  26552. if (!ast_sockaddr_isnull(&externaddr)) {
  26553. add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
  26554. SIP_DOMAIN_AUTO, NULL);
  26555. }
  26556. /* Extern host name (NAT traversal support) */
  26557. if (!ast_strlen_zero(externhost)) {
  26558. add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
  26559. }
  26560. /* Our host name */
  26561. if (!gethostname(temp, sizeof(temp))) {
  26562. add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
  26563. }
  26564. }
  26565. /* Release configuration from memory */
  26566. ast_config_destroy(cfg);
  26567. /* Load the list of manual NOTIFY types to support */
  26568. if (notify_types)
  26569. ast_config_destroy(notify_types);
  26570. if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
  26571. ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
  26572. notify_types = NULL;
  26573. }
  26574. /* Done, tell the manager */
  26575. manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "ChannelType: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count);
  26576. run_end = time(0);
  26577. ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
  26578. return 0;
  26579. }
  26580. static int apply_directmedia_ha(struct sip_pvt *p1, struct sip_pvt *p2, const char *op)
  26581. {
  26582. struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
  26583. int res = AST_SENSE_ALLOW;
  26584. ast_rtp_instance_get_remote_address(p1->rtp, &them);
  26585. ast_rtp_instance_get_local_address(p1->rtp, &us);
  26586. /* If p2 is a guest call, there will be no peer. If there is no peer, there
  26587. * is no directmediaha, so go ahead and allow it */
  26588. if (!p2->relatedpeer) {
  26589. return res;
  26590. }
  26591. if ((res = ast_apply_ha(p2->relatedpeer->directmediaha, &them)) == AST_SENSE_DENY) {
  26592. const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
  26593. const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
  26594. ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
  26595. op, them_addr, us_addr);
  26596. }
  26597. return res;
  26598. }
  26599. static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
  26600. {
  26601. struct sip_pvt *p;
  26602. struct ast_channel *opp_chan;
  26603. struct sip_pvt *opp;
  26604. struct ast_udptl *udptl = NULL;
  26605. p = chan->tech_pvt;
  26606. if (!p) {
  26607. return NULL;
  26608. }
  26609. if (!(opp_chan = ast_bridged_channel(chan))) {
  26610. return NULL;
  26611. } else if (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
  26612. (!(opp = opp_chan->tech_pvt))) {
  26613. return NULL;
  26614. }
  26615. sip_pvt_lock(p);
  26616. while (sip_pvt_trylock(opp)) {
  26617. sip_pvt_unlock(p);
  26618. usleep(1);
  26619. sip_pvt_lock(p);
  26620. }
  26621. if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  26622. if (apply_directmedia_ha(p, opp, "UDPTL T.38 data")) {
  26623. udptl = p->udptl;
  26624. }
  26625. }
  26626. sip_pvt_unlock(opp);
  26627. sip_pvt_unlock(p);
  26628. return udptl;
  26629. }
  26630. static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
  26631. {
  26632. struct sip_pvt *p;
  26633. /* Lock the channel and the private safely. */
  26634. ast_channel_lock(chan);
  26635. p = chan->tech_pvt;
  26636. if (!p) {
  26637. ast_channel_unlock(chan);
  26638. return -1;
  26639. }
  26640. sip_pvt_lock(p);
  26641. if (p->owner != chan) {
  26642. /* I suppose it could be argued that if this happens it is a bug. */
  26643. ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
  26644. sip_pvt_unlock(p);
  26645. ast_channel_unlock(chan);
  26646. return 0;
  26647. }
  26648. if (udptl) {
  26649. ast_udptl_get_peer(udptl, &p->udptlredirip);
  26650. } else {
  26651. memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
  26652. }
  26653. if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
  26654. if (!p->pendinginvite) {
  26655. ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
  26656. p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
  26657. transmit_reinvite_with_sdp(p, TRUE, FALSE);
  26658. } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  26659. ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
  26660. p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
  26661. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  26662. }
  26663. }
  26664. /* Reset lastrtprx timer */
  26665. p->lastrtprx = p->lastrtptx = time(NULL);
  26666. sip_pvt_unlock(p);
  26667. ast_channel_unlock(chan);
  26668. return 0;
  26669. }
  26670. static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
  26671. {
  26672. struct sip_pvt *p = NULL;
  26673. struct ast_channel *opp_chan;
  26674. struct sip_pvt *opp = NULL;
  26675. enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
  26676. if (!(p = chan->tech_pvt)) {
  26677. return AST_RTP_GLUE_RESULT_FORBID;
  26678. }
  26679. if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
  26680. (!(opp = opp_chan->tech_pvt)))) {
  26681. return AST_RTP_GLUE_RESULT_FORBID;
  26682. }
  26683. sip_pvt_lock(p);
  26684. while (opp && sip_pvt_trylock(opp)) {
  26685. sip_pvt_unlock(p);
  26686. usleep(1);
  26687. sip_pvt_lock(p);
  26688. }
  26689. if (!(p->rtp)) {
  26690. if (opp) {
  26691. sip_pvt_unlock(opp);
  26692. }
  26693. sip_pvt_unlock(p);
  26694. return AST_RTP_GLUE_RESULT_FORBID;
  26695. }
  26696. ao2_ref(p->rtp, +1);
  26697. *instance = p->rtp;
  26698. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  26699. res = AST_RTP_GLUE_RESULT_REMOTE;
  26700. if (opp && !apply_directmedia_ha(p, opp, "audio")) {
  26701. res = AST_RTP_GLUE_RESULT_FORBID;
  26702. }
  26703. } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
  26704. res = AST_RTP_GLUE_RESULT_REMOTE;
  26705. } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
  26706. res = AST_RTP_GLUE_RESULT_FORBID;
  26707. }
  26708. if (opp) {
  26709. sip_pvt_unlock(opp);
  26710. }
  26711. if (p->srtp) {
  26712. res = AST_RTP_GLUE_RESULT_FORBID;
  26713. }
  26714. sip_pvt_unlock(p);
  26715. return res;
  26716. }
  26717. static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
  26718. {
  26719. struct sip_pvt *p = NULL;
  26720. struct ast_channel *opp_chan;
  26721. struct sip_pvt *opp = NULL;
  26722. enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
  26723. if (!(p = chan->tech_pvt)) {
  26724. return AST_RTP_GLUE_RESULT_FORBID;
  26725. }
  26726. if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
  26727. (!(opp = opp_chan->tech_pvt)))) {
  26728. return AST_RTP_GLUE_RESULT_FORBID;
  26729. }
  26730. sip_pvt_lock(p);
  26731. while (opp && sip_pvt_trylock(opp)) {
  26732. sip_pvt_unlock(p);
  26733. usleep(1);
  26734. sip_pvt_lock(p);
  26735. }
  26736. if (!(p->vrtp)) {
  26737. if (opp) {
  26738. sip_pvt_unlock(opp);
  26739. }
  26740. sip_pvt_unlock(p);
  26741. return AST_RTP_GLUE_RESULT_FORBID;
  26742. }
  26743. ao2_ref(p->vrtp, +1);
  26744. *instance = p->vrtp;
  26745. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  26746. res = AST_RTP_GLUE_RESULT_REMOTE;
  26747. if (opp && !apply_directmedia_ha(p, opp, "video")) {
  26748. res = AST_RTP_GLUE_RESULT_FORBID;
  26749. }
  26750. }
  26751. if (opp) {
  26752. sip_pvt_unlock(opp);
  26753. }
  26754. sip_pvt_unlock(p);
  26755. return res;
  26756. }
  26757. static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
  26758. {
  26759. struct sip_pvt *p = NULL;
  26760. struct ast_channel *opp_chan;
  26761. struct sip_pvt *opp = NULL;
  26762. enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
  26763. if (!(p = chan->tech_pvt)) {
  26764. return AST_RTP_GLUE_RESULT_FORBID;
  26765. }
  26766. if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
  26767. (!(opp = opp_chan->tech_pvt)))) {
  26768. return AST_RTP_GLUE_RESULT_FORBID;
  26769. }
  26770. sip_pvt_lock(p);
  26771. while (opp && sip_pvt_trylock(opp)) {
  26772. sip_pvt_unlock(p);
  26773. usleep(1);
  26774. sip_pvt_lock(p);
  26775. }
  26776. if (!(p->trtp)) {
  26777. if (opp) {
  26778. sip_pvt_unlock(opp);
  26779. }
  26780. sip_pvt_unlock(p);
  26781. return AST_RTP_GLUE_RESULT_FORBID;
  26782. }
  26783. ao2_ref(p->trtp, +1);
  26784. *instance = p->trtp;
  26785. if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
  26786. res = AST_RTP_GLUE_RESULT_REMOTE;
  26787. if (opp && !apply_directmedia_ha(p, opp, "text")) {
  26788. res = AST_RTP_GLUE_RESULT_FORBID;
  26789. }
  26790. }
  26791. if (opp) {
  26792. sip_pvt_unlock(opp);
  26793. }
  26794. sip_pvt_unlock(p);
  26795. return res;
  26796. }
  26797. 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, format_t codecs, int nat_active)
  26798. {
  26799. struct sip_pvt *p;
  26800. int changed = 0;
  26801. /* Lock the channel and the private safely. */
  26802. ast_channel_lock(chan);
  26803. p = chan->tech_pvt;
  26804. if (!p) {
  26805. ast_channel_unlock(chan);
  26806. return -1;
  26807. }
  26808. sip_pvt_lock(p);
  26809. if (p->owner != chan) {
  26810. /* I suppose it could be argued that if this happens it is a bug. */
  26811. ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
  26812. sip_pvt_unlock(p);
  26813. ast_channel_unlock(chan);
  26814. return 0;
  26815. }
  26816. /* Disable early RTP bridge */
  26817. if ((instance || vinstance || tinstance) &&
  26818. !ast_bridged_channel(chan) &&
  26819. !sip_cfg.directrtpsetup) {
  26820. sip_pvt_unlock(p);
  26821. ast_channel_unlock(chan);
  26822. return 0;
  26823. }
  26824. if (p->alreadygone) {
  26825. /* If we're destroyed, don't bother */
  26826. sip_pvt_unlock(p);
  26827. ast_channel_unlock(chan);
  26828. return 0;
  26829. }
  26830. /* if this peer cannot handle reinvites of the media stream to devices
  26831. that are known to be behind a NAT, then stop the process now
  26832. */
  26833. if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
  26834. sip_pvt_unlock(p);
  26835. ast_channel_unlock(chan);
  26836. return 0;
  26837. }
  26838. if (instance) {
  26839. changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
  26840. if (p->rtp) {
  26841. /* Prevent audio RTCP reads */
  26842. ast_channel_set_fd(chan, 1, -1);
  26843. /* Silence RTCP while audio RTP is inactive */
  26844. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
  26845. }
  26846. } else if (!ast_sockaddr_isnull(&p->redirip)) {
  26847. memset(&p->redirip, 0, sizeof(p->redirip));
  26848. changed = 1;
  26849. if (p->rtp) {
  26850. /* Enable RTCP since it will be inactive if we're coming back
  26851. * from a reinvite */
  26852. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
  26853. /* Enable audio RTCP reads */
  26854. ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
  26855. }
  26856. }
  26857. if (vinstance) {
  26858. changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
  26859. if (p->vrtp) {
  26860. /* Prevent video RTCP reads */
  26861. ast_channel_set_fd(chan, 3, -1);
  26862. /* Silence RTCP while video RTP is inactive */
  26863. ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
  26864. }
  26865. } else if (!ast_sockaddr_isnull(&p->vredirip)) {
  26866. memset(&p->vredirip, 0, sizeof(p->vredirip));
  26867. changed = 1;
  26868. if (p->vrtp) {
  26869. /* Enable RTCP since it will be inactive if we're coming back
  26870. * from a reinvite */
  26871. ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
  26872. /* Enable video RTCP reads */
  26873. ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
  26874. }
  26875. }
  26876. if (tinstance) {
  26877. changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
  26878. } else if (!ast_sockaddr_isnull(&p->tredirip)) {
  26879. memset(&p->tredirip, 0, sizeof(p->tredirip));
  26880. changed = 1;
  26881. }
  26882. if (codecs && (p->redircodecs != codecs)) {
  26883. p->redircodecs = codecs;
  26884. changed = 1;
  26885. }
  26886. if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
  26887. /* We only wish to withhold sending the initial direct media reinvite on the incoming dialog.
  26888. * Further direct media reinvites beyond the initial should be sent. In order to allow further
  26889. * direct media reinvites to be sent, we clear this flag.
  26890. */
  26891. ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
  26892. sip_pvt_unlock(p);
  26893. ast_channel_unlock(chan);
  26894. return 0;
  26895. }
  26896. if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
  26897. if (chan->_state != AST_STATE_UP) { /* We are in early state */
  26898. if (p->do_history)
  26899. append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
  26900. ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
  26901. } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
  26902. 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));
  26903. transmit_reinvite_with_sdp(p, FALSE, FALSE);
  26904. } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
  26905. 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));
  26906. /* We have a pending Invite. Send re-invite when we're done with the invite */
  26907. ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
  26908. }
  26909. }
  26910. /* Reset lastrtprx timer */
  26911. p->lastrtprx = p->lastrtptx = time(NULL);
  26912. sip_pvt_unlock(p);
  26913. ast_channel_unlock(chan);
  26914. return 0;
  26915. }
  26916. static format_t sip_get_codec(struct ast_channel *chan)
  26917. {
  26918. struct sip_pvt *p = chan->tech_pvt;
  26919. return p->peercapability ? p->peercapability : p->capability;
  26920. }
  26921. static struct ast_rtp_glue sip_rtp_glue = {
  26922. .type = "SIP",
  26923. .get_rtp_info = sip_get_rtp_peer,
  26924. .get_vrtp_info = sip_get_vrtp_peer,
  26925. .get_trtp_info = sip_get_trtp_peer,
  26926. .update_peer = sip_set_rtp_peer,
  26927. .get_codec = sip_get_codec,
  26928. };
  26929. static char *app_dtmfmode = "SIPDtmfMode";
  26930. static char *app_sipaddheader = "SIPAddHeader";
  26931. static char *app_sipremoveheader = "SIPRemoveHeader";
  26932. /*! \brief Set the DTMFmode for an outbound SIP call (application) */
  26933. static int sip_dtmfmode(struct ast_channel *chan, const char *data)
  26934. {
  26935. struct sip_pvt *p;
  26936. const char *mode = data;
  26937. if (!data) {
  26938. ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
  26939. return 0;
  26940. }
  26941. ast_channel_lock(chan);
  26942. if (!IS_SIP_TECH(chan->tech)) {
  26943. ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
  26944. ast_channel_unlock(chan);
  26945. return 0;
  26946. }
  26947. p = chan->tech_pvt;
  26948. if (!p) {
  26949. ast_channel_unlock(chan);
  26950. return 0;
  26951. }
  26952. sip_pvt_lock(p);
  26953. if (!strcasecmp(mode, "info")) {
  26954. ast_clear_flag(&p->flags[0], SIP_DTMF);
  26955. ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
  26956. p->jointnoncodeccapability &= ~AST_RTP_DTMF;
  26957. } else if (!strcasecmp(mode, "shortinfo")) {
  26958. ast_clear_flag(&p->flags[0], SIP_DTMF);
  26959. ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
  26960. p->jointnoncodeccapability &= ~AST_RTP_DTMF;
  26961. } else if (!strcasecmp(mode, "rfc2833")) {
  26962. ast_clear_flag(&p->flags[0], SIP_DTMF);
  26963. ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
  26964. p->jointnoncodeccapability |= AST_RTP_DTMF;
  26965. } else if (!strcasecmp(mode, "inband")) {
  26966. ast_clear_flag(&p->flags[0], SIP_DTMF);
  26967. ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
  26968. p->jointnoncodeccapability &= ~AST_RTP_DTMF;
  26969. } else {
  26970. ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
  26971. }
  26972. if (p->rtp)
  26973. ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
  26974. if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
  26975. (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
  26976. enable_dsp_detect(p);
  26977. } else {
  26978. disable_dsp_detect(p);
  26979. }
  26980. sip_pvt_unlock(p);
  26981. ast_channel_unlock(chan);
  26982. return 0;
  26983. }
  26984. /*! \brief Add a SIP header to an outbound INVITE */
  26985. static int sip_addheader(struct ast_channel *chan, const char *data)
  26986. {
  26987. int no = 0;
  26988. int ok = FALSE;
  26989. char varbuf[30];
  26990. const char *inbuf = data;
  26991. char *subbuf;
  26992. if (ast_strlen_zero(inbuf)) {
  26993. ast_log(LOG_WARNING, "This application requires the argument: Header\n");
  26994. return 0;
  26995. }
  26996. ast_channel_lock(chan);
  26997. /* Check for headers */
  26998. while (!ok && no <= 50) {
  26999. no++;
  27000. snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
  27001. /* Compare without the leading underscores */
  27002. if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
  27003. ok = TRUE;
  27004. }
  27005. }
  27006. if (ok) {
  27007. size_t len = strlen(inbuf);
  27008. subbuf = ast_alloca(len + 1);
  27009. ast_get_encoded_str(inbuf, subbuf, len + 1);
  27010. pbx_builtin_setvar_helper(chan, varbuf, subbuf);
  27011. if (sipdebug) {
  27012. ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
  27013. }
  27014. } else {
  27015. ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
  27016. }
  27017. ast_channel_unlock(chan);
  27018. return 0;
  27019. }
  27020. /*! \brief Remove SIP headers added previously with SipAddHeader application */
  27021. static int sip_removeheader(struct ast_channel *chan, const char *data)
  27022. {
  27023. struct ast_var_t *newvariable;
  27024. struct varshead *headp;
  27025. int removeall = 0;
  27026. char *inbuf = (char *) data;
  27027. if (ast_strlen_zero(inbuf)) {
  27028. removeall = 1;
  27029. }
  27030. ast_channel_lock(chan);
  27031. headp=&chan->varshead;
  27032. AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
  27033. if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
  27034. if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
  27035. if (sipdebug)
  27036. ast_debug(1,"removing SIP Header \"%s\" as %s\n",
  27037. ast_var_value(newvariable),
  27038. ast_var_name(newvariable));
  27039. AST_LIST_REMOVE_CURRENT(entries);
  27040. ast_var_delete(newvariable);
  27041. }
  27042. }
  27043. }
  27044. AST_LIST_TRAVERSE_SAFE_END;
  27045. ast_channel_unlock(chan);
  27046. return 0;
  27047. }
  27048. /*! \brief Transfer call before connect with a 302 redirect
  27049. \note Called by the transfer() dialplan application through the sip_transfer()
  27050. pbx interface function if the call is in ringing state
  27051. \todo Fix this function so that we wait for reply to the REFER and
  27052. react to errors, denials or other issues the other end might have.
  27053. */
  27054. static int sip_sipredirect(struct sip_pvt *p, const char *dest)
  27055. {
  27056. char *cdest;
  27057. char *extension, *domain;
  27058. cdest = ast_strdupa(dest);
  27059. extension = strsep(&cdest, "@");
  27060. domain = cdest;
  27061. if (ast_strlen_zero(extension)) {
  27062. ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
  27063. return 0;
  27064. }
  27065. /* we'll issue the redirect message here */
  27066. if (!domain) {
  27067. char *local_to_header;
  27068. char to_header[256];
  27069. ast_copy_string(to_header, get_header(&p->initreq, "To"), sizeof(to_header));
  27070. if (ast_strlen_zero(to_header)) {
  27071. ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
  27072. return 0;
  27073. }
  27074. if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
  27075. && (local_to_header = strchr(local_to_header, '@'))) {
  27076. char ldomain[256];
  27077. memset(ldomain, 0, sizeof(ldomain));
  27078. local_to_header++;
  27079. /* This is okey because lhost and lport are as big as tmp */
  27080. sscanf(local_to_header, "%256[^<>; ]", ldomain);
  27081. if (ast_strlen_zero(ldomain)) {
  27082. ast_log(LOG_ERROR, "Can't find the host address\n");
  27083. return 0;
  27084. }
  27085. domain = ast_strdupa(ldomain);
  27086. }
  27087. }
  27088. ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
  27089. transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
  27090. sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Make sure we stop send this reply. */
  27091. sip_alreadygone(p);
  27092. if (p->owner) {
  27093. enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
  27094. ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
  27095. }
  27096. /* hangup here */
  27097. return 0;
  27098. }
  27099. static int sip_is_xml_parsable(void)
  27100. {
  27101. #ifdef HAVE_LIBXML2
  27102. return TRUE;
  27103. #else
  27104. return FALSE;
  27105. #endif
  27106. }
  27107. /*! \brief Send a poke to all known peers */
  27108. static void sip_poke_all_peers(void)
  27109. {
  27110. int ms = 0, num = 0;
  27111. struct ao2_iterator i;
  27112. struct sip_peer *peer;
  27113. if (!speerobjs) { /* No peers, just give up */
  27114. return;
  27115. }
  27116. i = ao2_iterator_init(peers, 0);
  27117. while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
  27118. ao2_lock(peer);
  27119. /* Don't schedule poking on a peer without qualify */
  27120. if (peer->maxms) {
  27121. if (num == global_qualify_peers) {
  27122. ms += global_qualify_gap;
  27123. num = 0;
  27124. } else {
  27125. num++;
  27126. }
  27127. AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
  27128. unref_peer(_data, "removing poke peer ref"),
  27129. unref_peer(peer, "removing poke peer ref"),
  27130. ref_peer(peer, "adding poke peer ref"));
  27131. }
  27132. ao2_unlock(peer);
  27133. unref_peer(peer, "toss iterator peer ptr");
  27134. }
  27135. ao2_iterator_destroy(&i);
  27136. }
  27137. /*! \brief Send all known registrations */
  27138. static void sip_send_all_registers(void)
  27139. {
  27140. int ms;
  27141. int regspacing;
  27142. if (!regobjs)
  27143. return;
  27144. regspacing = default_expiry * 1000/regobjs;
  27145. if (regspacing > 100) {
  27146. regspacing = 100;
  27147. }
  27148. ms = regspacing;
  27149. ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
  27150. ASTOBJ_WRLOCK(iterator);
  27151. ms += regspacing;
  27152. AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
  27153. registry_unref(_data, "REPLACE sched del decs the refcount"),
  27154. registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
  27155. registry_addref(iterator, "REPLACE sched add incs the refcount"));
  27156. ASTOBJ_UNLOCK(iterator);
  27157. } while (0)
  27158. );
  27159. }
  27160. /*! \brief Send all MWI subscriptions */
  27161. static void sip_send_all_mwi_subscriptions(void)
  27162. {
  27163. ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
  27164. struct sip_subscription_mwi *saved;
  27165. ASTOBJ_WRLOCK(iterator);
  27166. AST_SCHED_DEL(sched, iterator->resub);
  27167. saved = ASTOBJ_REF(iterator);
  27168. if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, saved)) < 0) {
  27169. ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
  27170. }
  27171. ASTOBJ_UNLOCK(iterator);
  27172. } while (0));
  27173. }
  27174. /* SRTP */
  27175. static int setup_srtp(struct sip_srtp **srtp)
  27176. {
  27177. if (!ast_rtp_engine_srtp_is_registered()) {
  27178. ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
  27179. return -1;
  27180. }
  27181. if (!(*srtp = sip_srtp_alloc())) { /* Allocate SRTP data structure */
  27182. return -1;
  27183. }
  27184. return 0;
  27185. }
  27186. static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
  27187. {
  27188. /* If no RTP instance exists for this media stream don't bother processing the crypto line */
  27189. if (!rtp) {
  27190. ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
  27191. return FALSE;
  27192. }
  27193. if (strncasecmp(a, "crypto:", 7)) {
  27194. return FALSE;
  27195. }
  27196. if (!*srtp) {
  27197. if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
  27198. ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
  27199. return FALSE;
  27200. }
  27201. if (setup_srtp(srtp) < 0) {
  27202. return FALSE;
  27203. }
  27204. }
  27205. if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
  27206. return FALSE;
  27207. }
  27208. if (sdp_crypto_process((*srtp)->crypto, a, rtp) < 0) {
  27209. return FALSE;
  27210. }
  27211. ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
  27212. return TRUE;
  27213. }
  27214. /*! \brief Reload module */
  27215. static int sip_do_reload(enum channelreloadreason reason)
  27216. {
  27217. time_t start_poke, end_poke;
  27218. reload_config(reason);
  27219. ast_sched_dump(sched);
  27220. start_poke = time(0);
  27221. /* Prune peers who still are supposed to be deleted */
  27222. unlink_marked_peers_from_tables();
  27223. ast_debug(4, "--------------- Done destroying pruned peers\n");
  27224. /* Send qualify (OPTIONS) to all peers */
  27225. sip_poke_all_peers();
  27226. /* Register with all services */
  27227. sip_send_all_registers();
  27228. sip_send_all_mwi_subscriptions();
  27229. end_poke = time(0);
  27230. ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
  27231. ast_debug(4, "--------------- SIP reload done\n");
  27232. return 0;
  27233. }
  27234. /*! \brief Force reload of module from cli */
  27235. static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  27236. {
  27237. static struct sip_peer *tmp_peer, *new_peer;
  27238. switch (cmd) {
  27239. case CLI_INIT:
  27240. e->command = "sip reload";
  27241. e->usage =
  27242. "Usage: sip reload\n"
  27243. " Reloads SIP configuration from sip.conf\n";
  27244. return NULL;
  27245. case CLI_GENERATE:
  27246. return NULL;
  27247. }
  27248. ast_mutex_lock(&sip_reload_lock);
  27249. if (sip_reloading) {
  27250. ast_verbose("Previous SIP reload not yet done\n");
  27251. } else {
  27252. sip_reloading = TRUE;
  27253. sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
  27254. }
  27255. ast_mutex_unlock(&sip_reload_lock);
  27256. restart_monitor();
  27257. tmp_peer = bogus_peer;
  27258. /* Create new bogus peer possibly with new global settings. */
  27259. if ((new_peer = temp_peer("(bogus_peer)"))) {
  27260. ast_string_field_set(new_peer, md5secret, BOGUS_PEER_MD5SECRET);
  27261. ast_clear_flag(&new_peer->flags[0], SIP_INSECURE);
  27262. bogus_peer = new_peer;
  27263. ao2_t_ref(tmp_peer, -1, "unref the old bogus_peer during reload");
  27264. } else {
  27265. ast_log(LOG_ERROR, "Could not update the fake authentication peer.\n");
  27266. /* You probably have bigger (memory?) issues to worry about though.. */
  27267. }
  27268. return CLI_SUCCESS;
  27269. }
  27270. /*! \brief Part of Asterisk module interface */
  27271. static int reload(void)
  27272. {
  27273. if (sip_reload(0, 0, NULL))
  27274. return 0;
  27275. return 1;
  27276. }
  27277. /*! \brief Return the first entry from ast_sockaddr_resolve filtered by address family
  27278. *
  27279. * \warn Using this function probably means you have a faulty design.
  27280. */
  27281. static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
  27282. const char* name, int flag, int family)
  27283. {
  27284. struct ast_sockaddr *addrs;
  27285. int addrs_cnt;
  27286. addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
  27287. if (addrs_cnt <= 0) {
  27288. return 1;
  27289. }
  27290. if (addrs_cnt > 1) {
  27291. ast_debug(1, "Multiple addresses, using the first one only\n");
  27292. }
  27293. ast_sockaddr_copy(addr, &addrs[0]);
  27294. ast_free(addrs);
  27295. return 0;
  27296. }
  27297. /*! \brief Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
  27298. *
  27299. * \warn Using this function probably means you have a faulty design.
  27300. */
  27301. static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
  27302. const char* name, int flag)
  27303. {
  27304. return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(SIP_TRANSPORT_UDP));
  27305. }
  27306. /*! \brief Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
  27307. *
  27308. * \warn Using this function probably means you have a faulty design.
  27309. */
  27310. static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
  27311. const char* name, int flag, unsigned int transport)
  27312. {
  27313. return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
  27314. }
  27315. /*! \brief
  27316. * \note The only member of the peer used here is the name field
  27317. */
  27318. static int peer_hash_cb(const void *obj, const int flags)
  27319. {
  27320. const struct sip_peer *peer = obj;
  27321. return ast_str_case_hash(peer->name);
  27322. }
  27323. /*!
  27324. * \note The only member of the peer used here is the name field
  27325. */
  27326. static int peer_cmp_cb(void *obj, void *arg, int flags)
  27327. {
  27328. struct sip_peer *peer = obj, *peer2 = arg;
  27329. return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
  27330. }
  27331. /*!
  27332. * Hash function based on the the peer's ip address. For IPv6, we use the end
  27333. * of the address.
  27334. * \todo Find a better hashing function
  27335. */
  27336. static int peer_iphash_cb(const void *obj, const int flags)
  27337. {
  27338. const struct sip_peer *peer = obj;
  27339. int ret = 0;
  27340. if (ast_sockaddr_isnull(&peer->addr)) {
  27341. ast_log(LOG_ERROR, "Empty address\n");
  27342. }
  27343. ret = ast_sockaddr_hash(&peer->addr);
  27344. if (ret < 0) {
  27345. ret = -ret;
  27346. }
  27347. return ret;
  27348. }
  27349. /*!
  27350. * Match Peers by IP and Port number.
  27351. *
  27352. * This function has two modes.
  27353. * - If the peer arg does not have INSECURE_PORT set, then we will only return
  27354. * a match for a peer that matches both the IP and port.
  27355. * - If the peer arg does have the INSECURE_PORT flag set, then we will only
  27356. * return a match for a peer that matches the IP and has insecure=port
  27357. * in its configuration.
  27358. *
  27359. * This callback will be used twice when doing peer matching. There is a first
  27360. * pass for full IP+port matching, and a second pass in case there is a match
  27361. * that meets the insecure=port criteria.
  27362. *
  27363. * \note Connections coming in over TCP or TLS should never be matched by port.
  27364. *
  27365. * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
  27366. */
  27367. static int peer_ipcmp_cb(void *obj, void *arg, int flags)
  27368. {
  27369. struct sip_peer *peer = obj, *peer2 = arg;
  27370. if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
  27371. /* IP doesn't match */
  27372. return 0;
  27373. }
  27374. /* We matched the IP, check to see if we need to match by port as well. */
  27375. if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
  27376. /* peer matching on port is not possible with TCP/TLS */
  27377. return CMP_MATCH | CMP_STOP;
  27378. } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
  27379. /* We are allowing match without port for peers configured that
  27380. * way in this pass through the peers. */
  27381. return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
  27382. (CMP_MATCH | CMP_STOP) : 0;
  27383. }
  27384. /* Now only return a match if the port matches, as well. */
  27385. return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
  27386. (CMP_MATCH | CMP_STOP) : 0;
  27387. }
  27388. static int threadt_hash_cb(const void *obj, const int flags)
  27389. {
  27390. const struct sip_threadinfo *th = obj;
  27391. return ast_sockaddr_hash(&th->tcptls_session->remote_address);
  27392. }
  27393. static int threadt_cmp_cb(void *obj, void *arg, int flags)
  27394. {
  27395. struct sip_threadinfo *th = obj, *th2 = arg;
  27396. return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
  27397. }
  27398. /*!
  27399. * \note The only member of the dialog used here callid string
  27400. */
  27401. static int dialog_hash_cb(const void *obj, const int flags)
  27402. {
  27403. const struct sip_pvt *pvt = obj;
  27404. return ast_str_case_hash(pvt->callid);
  27405. }
  27406. /*!
  27407. * \note Same as dialog_cmp_cb, except without the CMP_STOP on match
  27408. */
  27409. static int dialog_find_multiple(void *obj, void *arg, int flags)
  27410. {
  27411. struct sip_pvt *pvt = obj, *pvt2 = arg;
  27412. return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
  27413. }
  27414. /*!
  27415. * \note The only member of the dialog used here callid string
  27416. */
  27417. static int dialog_cmp_cb(void *obj, void *arg, int flags)
  27418. {
  27419. struct sip_pvt *pvt = obj, *pvt2 = arg;
  27420. return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
  27421. }
  27422. /*! \brief SIP Cli commands definition */
  27423. static struct ast_cli_entry cli_sip[] = {
  27424. AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
  27425. AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
  27426. AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
  27427. AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
  27428. AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
  27429. AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
  27430. AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
  27431. AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
  27432. AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
  27433. AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
  27434. AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
  27435. AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
  27436. AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
  27437. AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
  27438. AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
  27439. AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
  27440. AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
  27441. AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
  27442. AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
  27443. AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
  27444. AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
  27445. AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
  27446. AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
  27447. };
  27448. /*! \brief SIP test registration */
  27449. static void sip_register_tests(void)
  27450. {
  27451. sip_config_parser_register_tests();
  27452. sip_request_parser_register_tests();
  27453. sip_dialplan_function_register_tests();
  27454. }
  27455. /*! \brief SIP test registration */
  27456. static void sip_unregister_tests(void)
  27457. {
  27458. sip_config_parser_unregister_tests();
  27459. sip_request_parser_unregister_tests();
  27460. sip_dialplan_function_unregister_tests();
  27461. }
  27462. #ifdef TEST_FRAMEWORK
  27463. AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
  27464. {
  27465. int found = 0;
  27466. enum ast_test_result_state res = AST_TEST_PASS;
  27467. const char *mwi1 = "1234@mysipprovider.com/1234";
  27468. const char *mwi2 = "1234:password@mysipprovider.com/1234";
  27469. const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
  27470. const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
  27471. const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
  27472. const char *mwi6 = "1234:password";
  27473. switch (cmd) {
  27474. case TEST_INIT:
  27475. info->name = "sip_mwi_subscribe_parse_test";
  27476. info->category = "/channels/chan_sip/";
  27477. info->summary = "SIP MWI subscribe line parse unit test";
  27478. info->description =
  27479. "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
  27480. return AST_TEST_NOT_RUN;
  27481. case TEST_EXECUTE:
  27482. break;
  27483. }
  27484. if (sip_subscribe_mwi(mwi1, 1)) {
  27485. res = AST_TEST_FAIL;
  27486. } else {
  27487. found = 0;
  27488. res = AST_TEST_FAIL;
  27489. ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
  27490. ASTOBJ_WRLOCK(iterator);
  27491. if (
  27492. !strcmp(iterator->hostname, "mysipprovider.com") &&
  27493. !strcmp(iterator->username, "1234") &&
  27494. !strcmp(iterator->secret, "") &&
  27495. !strcmp(iterator->authuser, "") &&
  27496. !strcmp(iterator->mailbox, "1234") &&
  27497. iterator->portno == 0) {
  27498. found = 1;
  27499. res = AST_TEST_PASS;
  27500. }
  27501. ASTOBJ_UNLOCK(iterator);
  27502. } while(0));
  27503. if (!found) {
  27504. ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
  27505. }
  27506. }
  27507. if (sip_subscribe_mwi(mwi2, 1)) {
  27508. res = AST_TEST_FAIL;
  27509. } else {
  27510. found = 0;
  27511. res = AST_TEST_FAIL;
  27512. ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
  27513. ASTOBJ_WRLOCK(iterator);
  27514. if (
  27515. !strcmp(iterator->hostname, "mysipprovider.com") &&
  27516. !strcmp(iterator->username, "1234") &&
  27517. !strcmp(iterator->secret, "password") &&
  27518. !strcmp(iterator->authuser, "") &&
  27519. !strcmp(iterator->mailbox, "1234") &&
  27520. iterator->portno == 0) {
  27521. found = 1;
  27522. res = AST_TEST_PASS;
  27523. }
  27524. ASTOBJ_UNLOCK(iterator);
  27525. } while(0));
  27526. if (!found) {
  27527. ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
  27528. }
  27529. }
  27530. if (sip_subscribe_mwi(mwi3, 1)) {
  27531. res = AST_TEST_FAIL;
  27532. } else {
  27533. found = 0;
  27534. res = AST_TEST_FAIL;
  27535. ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
  27536. ASTOBJ_WRLOCK(iterator);
  27537. if (
  27538. !strcmp(iterator->hostname, "mysipprovider.com") &&
  27539. !strcmp(iterator->username, "1234") &&
  27540. !strcmp(iterator->secret, "password") &&
  27541. !strcmp(iterator->authuser, "") &&
  27542. !strcmp(iterator->mailbox, "1234") &&
  27543. iterator->portno == 5061) {
  27544. found = 1;
  27545. res = AST_TEST_PASS;
  27546. }
  27547. ASTOBJ_UNLOCK(iterator);
  27548. } while(0));
  27549. if (!found) {
  27550. ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
  27551. }
  27552. }
  27553. if (sip_subscribe_mwi(mwi4, 1)) {
  27554. res = AST_TEST_FAIL;
  27555. } else {
  27556. found = 0;
  27557. res = AST_TEST_FAIL;
  27558. ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
  27559. ASTOBJ_WRLOCK(iterator);
  27560. if (
  27561. !strcmp(iterator->hostname, "mysipprovider.com") &&
  27562. !strcmp(iterator->username, "1234") &&
  27563. !strcmp(iterator->secret, "password") &&
  27564. !strcmp(iterator->authuser, "authuser") &&
  27565. !strcmp(iterator->mailbox, "1234") &&
  27566. iterator->portno == 0) {
  27567. found = 1;
  27568. res = AST_TEST_PASS;
  27569. }
  27570. ASTOBJ_UNLOCK(iterator);
  27571. } while(0));
  27572. if (!found) {
  27573. ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
  27574. }
  27575. }
  27576. if (sip_subscribe_mwi(mwi5, 1)) {
  27577. res = AST_TEST_FAIL;
  27578. } else {
  27579. found = 0;
  27580. res = AST_TEST_FAIL;
  27581. ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
  27582. ASTOBJ_WRLOCK(iterator);
  27583. if (
  27584. !strcmp(iterator->hostname, "mysipprovider.com") &&
  27585. !strcmp(iterator->username, "1234") &&
  27586. !strcmp(iterator->secret, "password") &&
  27587. !strcmp(iterator->authuser, "authuser") &&
  27588. !strcmp(iterator->mailbox, "1234") &&
  27589. iterator->portno == 5061) {
  27590. found = 1;
  27591. res = AST_TEST_PASS;
  27592. }
  27593. ASTOBJ_UNLOCK(iterator);
  27594. } while(0));
  27595. if (!found) {
  27596. ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
  27597. }
  27598. }
  27599. if (sip_subscribe_mwi(mwi6, 1)) {
  27600. res = AST_TEST_PASS;
  27601. } else {
  27602. res = AST_TEST_FAIL;
  27603. }
  27604. return res;
  27605. }
  27606. AST_TEST_DEFINE(test_sip_peers_get)
  27607. {
  27608. struct sip_peer *peer;
  27609. struct ast_data *node;
  27610. struct ast_data_query query = {
  27611. .path = "/asterisk/channel/sip/peers",
  27612. .search = "peers/peer/name=test_peer_data_provider"
  27613. };
  27614. switch (cmd) {
  27615. case TEST_INIT:
  27616. info->name = "sip_peers_get_data_test";
  27617. info->category = "/main/data/sip/peers/";
  27618. info->summary = "SIP peers data providers unit test";
  27619. info->description =
  27620. "Tests whether the SIP peers data provider implementation works as expected.";
  27621. return AST_TEST_NOT_RUN;
  27622. case TEST_EXECUTE:
  27623. break;
  27624. }
  27625. /* Create the peer that we will retrieve. */
  27626. peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
  27627. if (!peer) {
  27628. return AST_TEST_FAIL;
  27629. }
  27630. peer->type = SIP_TYPE_USER;
  27631. peer->call_limit = 10;
  27632. ao2_link(peers, peer);
  27633. /* retrieve the chan_sip/peers tree and check the created peer. */
  27634. node = ast_data_get(&query);
  27635. if (!node) {
  27636. ao2_unlink(peers, peer);
  27637. ao2_ref(peer, -1);
  27638. return AST_TEST_FAIL;
  27639. }
  27640. /* compare item. */
  27641. if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
  27642. ao2_unlink(peers, peer);
  27643. ao2_ref(peer, -1);
  27644. ast_data_free(node);
  27645. return AST_TEST_FAIL;
  27646. }
  27647. if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
  27648. ao2_unlink(peers, peer);
  27649. ao2_ref(peer, -1);
  27650. ast_data_free(node);
  27651. return AST_TEST_FAIL;
  27652. }
  27653. if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
  27654. ao2_unlink(peers, peer);
  27655. ao2_ref(peer, -1);
  27656. ast_data_free(node);
  27657. return AST_TEST_FAIL;
  27658. }
  27659. /* release resources */
  27660. ast_data_free(node);
  27661. ao2_unlink(peers, peer);
  27662. ao2_ref(peer, -1);
  27663. return AST_TEST_PASS;
  27664. }
  27665. /*!
  27666. * \brief Imitation TCP reception loop
  27667. *
  27668. * This imitates the logic used by SIP's TCP code. Its purpose
  27669. * is to either
  27670. * 1) Combine fragments into a single message
  27671. * 2) Break up combined messages into single messages
  27672. *
  27673. * \param fragments The message fragments. This simulates the data received on a TCP socket.
  27674. * \param num_fragments This indicates the number of fragments to receive
  27675. * \param overflow This is a place to stash extra data if more than one message is received
  27676. * in a single fragment
  27677. * \param[out] messages The parsed messages are placed in this array
  27678. * \param[out] num_messages The number of messages that were parsed
  27679. * \param test Used for printing messages
  27680. * \retval 0 Success
  27681. * \retval -1 Failure
  27682. */
  27683. static int mock_tcp_loop(char *fragments[], size_t num_fragments,
  27684. struct ast_str **overflow, char **messages, int *num_messages, struct ast_test* test)
  27685. {
  27686. struct ast_str *req_data;
  27687. int i = 0;
  27688. int res = 0;
  27689. req_data = ast_str_create(128);
  27690. ast_str_reset(*overflow);
  27691. while (i < num_fragments || ast_str_strlen(*overflow) > 0) {
  27692. enum message_integrity message_integrity = MESSAGE_FRAGMENT;
  27693. ast_str_reset(req_data);
  27694. while (message_integrity == MESSAGE_FRAGMENT) {
  27695. if (ast_str_strlen(*overflow) > 0) {
  27696. ast_str_append(&req_data, 0, "%s", ast_str_buffer(*overflow));
  27697. ast_str_reset(*overflow);
  27698. } else {
  27699. ast_str_append(&req_data, 0, "%s", fragments[i++]);
  27700. }
  27701. message_integrity = check_message_integrity(&req_data, overflow);
  27702. }
  27703. if (strcmp(ast_str_buffer(req_data), messages[*num_messages])) {
  27704. ast_test_status_update(test, "Mismatch in SIP messages.\n");
  27705. ast_test_status_update(test, "Expected message:\n%s", messages[*num_messages]);
  27706. ast_test_status_update(test, "Parsed message:\n%s", ast_str_buffer(req_data));
  27707. res = -1;
  27708. goto end;
  27709. } else {
  27710. ast_test_status_update(test, "Successfully read message:\n%s", ast_str_buffer(req_data));
  27711. }
  27712. (*num_messages)++;
  27713. }
  27714. end:
  27715. ast_free(req_data);
  27716. return res;
  27717. };
  27718. AST_TEST_DEFINE(test_tcp_message_fragmentation)
  27719. {
  27720. /* Normal single message in one fragment */
  27721. char *normal[] = {
  27722. "INVITE sip:bob@example.org SIP/2.0\r\n"
  27723. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27724. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27725. "To: <sip:bob@example.org:5060>\r\n"
  27726. "Call-ID: 12345\r\n"
  27727. "CSeq: 1 INVITE\r\n"
  27728. "Contact: sip:127.0.0.1:5061\r\n"
  27729. "Max-Forwards: 70\r\n"
  27730. "Content-Type: application/sdp\r\n"
  27731. "Content-Length: 130\r\n"
  27732. "\r\n"
  27733. "v=0\r\n"
  27734. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  27735. "s=-\r\n"
  27736. "c=IN IP4 127.0.0.1\r\n"
  27737. "t=0 0\r\n"
  27738. "m=audio 10000 RTP/AVP 0\r\n"
  27739. "a=rtpmap:0 PCMU/8000\r\n"
  27740. };
  27741. /* Single message in two fragments.
  27742. * Fragments combine to make "normal"
  27743. */
  27744. char *fragmented[] = {
  27745. "INVITE sip:bob@example.org SIP/2.0\r\n"
  27746. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27747. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27748. "To: <sip:bob@example.org:5060>\r\n"
  27749. "Call-ID: 12345\r\n"
  27750. "CSeq: 1 INVITE\r\n"
  27751. "Contact: sip:127.0.0.1:5061\r\n"
  27752. "Max-Forwards: ",
  27753. "70\r\n"
  27754. "Content-Type: application/sdp\r\n"
  27755. "Content-Length: 130\r\n"
  27756. "\r\n"
  27757. "v=0\r\n"
  27758. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  27759. "s=-\r\n"
  27760. "c=IN IP4 127.0.0.1\r\n"
  27761. "t=0 0\r\n"
  27762. "m=audio 10000 RTP/AVP 0\r\n"
  27763. "a=rtpmap:0 PCMU/8000\r\n"
  27764. };
  27765. /* Single message in two fragments, divided precisely at the body
  27766. * Fragments combine to make "normal"
  27767. */
  27768. char *fragmented_body[] = {
  27769. "INVITE sip:bob@example.org SIP/2.0\r\n"
  27770. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27771. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27772. "To: <sip:bob@example.org:5060>\r\n"
  27773. "Call-ID: 12345\r\n"
  27774. "CSeq: 1 INVITE\r\n"
  27775. "Contact: sip:127.0.0.1:5061\r\n"
  27776. "Max-Forwards: 70\r\n"
  27777. "Content-Type: application/sdp\r\n"
  27778. "Content-Length: 130\r\n"
  27779. "\r\n",
  27780. "v=0\r\n"
  27781. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  27782. "s=-\r\n"
  27783. "c=IN IP4 127.0.0.1\r\n"
  27784. "t=0 0\r\n"
  27785. "m=audio 10000 RTP/AVP 0\r\n"
  27786. "a=rtpmap:0 PCMU/8000\r\n"
  27787. };
  27788. /* Single message in three fragments
  27789. * Fragments combine to make "normal"
  27790. */
  27791. char *multi_fragment[] = {
  27792. "INVITE sip:bob@example.org SIP/2.0\r\n"
  27793. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27794. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27795. "To: <sip:bob@example.org:5060>\r\n"
  27796. "Call-ID: 12345\r\n"
  27797. "CSeq: 1 INVITE\r\n",
  27798. "Contact: sip:127.0.0.1:5061\r\n"
  27799. "Max-Forwards: 70\r\n"
  27800. "Content-Type: application/sdp\r\n"
  27801. "Content-Length: 130\r\n"
  27802. "\r\n"
  27803. "v=0\r\n"
  27804. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  27805. "s=-\r\n"
  27806. "c=IN IP4",
  27807. " 127.0.0.1\r\n"
  27808. "t=0 0\r\n"
  27809. "m=audio 10000 RTP/AVP 0\r\n"
  27810. "a=rtpmap:0 PCMU/8000\r\n"
  27811. };
  27812. /* Two messages in a single fragment
  27813. * Fragments split into "multi_message_divided"
  27814. */
  27815. char *multi_message[] = {
  27816. "SIP/2.0 100 Trying\r\n"
  27817. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27818. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27819. "To: <sip:bob@example.org:5060>\r\n"
  27820. "Call-ID: 12345\r\n"
  27821. "CSeq: 1 INVITE\r\n"
  27822. "Contact: <sip:bob@example.org:5060>\r\n"
  27823. "Content-Length: 0\r\n"
  27824. "\r\n"
  27825. "SIP/2.0 180 Ringing\r\n"
  27826. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27827. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27828. "To: <sip:bob@example.org:5060>\r\n"
  27829. "Call-ID: 12345\r\n"
  27830. "CSeq: 1 INVITE\r\n"
  27831. "Contact: <sip:bob@example.org:5060>\r\n"
  27832. "Content-Length: 0\r\n"
  27833. "\r\n"
  27834. };
  27835. char *multi_message_divided[] = {
  27836. "SIP/2.0 100 Trying\r\n"
  27837. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27838. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27839. "To: <sip:bob@example.org:5060>\r\n"
  27840. "Call-ID: 12345\r\n"
  27841. "CSeq: 1 INVITE\r\n"
  27842. "Contact: <sip:bob@example.org:5060>\r\n"
  27843. "Content-Length: 0\r\n"
  27844. "\r\n",
  27845. "SIP/2.0 180 Ringing\r\n"
  27846. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27847. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27848. "To: <sip:bob@example.org:5060>\r\n"
  27849. "Call-ID: 12345\r\n"
  27850. "CSeq: 1 INVITE\r\n"
  27851. "Contact: <sip:bob@example.org:5060>\r\n"
  27852. "Content-Length: 0\r\n"
  27853. "\r\n"
  27854. };
  27855. /* Two messages with bodies combined into one fragment
  27856. * Fragments split into "multi_message_body_divided"
  27857. */
  27858. char *multi_message_body[] = {
  27859. "INVITE sip:bob@example.org SIP/2.0\r\n"
  27860. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27861. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27862. "To: <sip:bob@example.org:5060>\r\n"
  27863. "Call-ID: 12345\r\n"
  27864. "CSeq: 1 INVITE\r\n"
  27865. "Contact: sip:127.0.0.1:5061\r\n"
  27866. "Max-Forwards: 70\r\n"
  27867. "Content-Type: application/sdp\r\n"
  27868. "Content-Length: 130\r\n"
  27869. "\r\n"
  27870. "v=0\r\n"
  27871. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  27872. "s=-\r\n"
  27873. "c=IN IP4 127.0.0.1\r\n"
  27874. "t=0 0\r\n"
  27875. "m=audio 10000 RTP/AVP 0\r\n"
  27876. "a=rtpmap:0 PCMU/8000\r\n"
  27877. "INVITE sip:bob@example.org SIP/2.0\r\n"
  27878. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27879. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27880. "To: <sip:bob@example.org:5060>\r\n"
  27881. "Call-ID: 12345\r\n"
  27882. "CSeq: 2 INVITE\r\n"
  27883. "Contact: sip:127.0.0.1:5061\r\n"
  27884. "Max-Forwards: 70\r\n"
  27885. "Content-Type: application/sdp\r\n"
  27886. "Content-Length: 130\r\n"
  27887. "\r\n"
  27888. "v=0\r\n"
  27889. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  27890. "s=-\r\n"
  27891. "c=IN IP4 127.0.0.1\r\n"
  27892. "t=0 0\r\n"
  27893. "m=audio 10000 RTP/AVP 0\r\n"
  27894. "a=rtpmap:0 PCMU/8000\r\n"
  27895. };
  27896. char *multi_message_body_divided[] = {
  27897. "INVITE sip:bob@example.org SIP/2.0\r\n"
  27898. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27899. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27900. "To: <sip:bob@example.org:5060>\r\n"
  27901. "Call-ID: 12345\r\n"
  27902. "CSeq: 1 INVITE\r\n"
  27903. "Contact: sip:127.0.0.1:5061\r\n"
  27904. "Max-Forwards: 70\r\n"
  27905. "Content-Type: application/sdp\r\n"
  27906. "Content-Length: 130\r\n"
  27907. "\r\n"
  27908. "v=0\r\n"
  27909. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  27910. "s=-\r\n"
  27911. "c=IN IP4 127.0.0.1\r\n"
  27912. "t=0 0\r\n"
  27913. "m=audio 10000 RTP/AVP 0\r\n"
  27914. "a=rtpmap:0 PCMU/8000\r\n",
  27915. "INVITE sip:bob@example.org SIP/2.0\r\n"
  27916. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27917. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27918. "To: <sip:bob@example.org:5060>\r\n"
  27919. "Call-ID: 12345\r\n"
  27920. "CSeq: 2 INVITE\r\n"
  27921. "Contact: sip:127.0.0.1:5061\r\n"
  27922. "Max-Forwards: 70\r\n"
  27923. "Content-Type: application/sdp\r\n"
  27924. "Content-Length: 130\r\n"
  27925. "\r\n"
  27926. "v=0\r\n"
  27927. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  27928. "s=-\r\n"
  27929. "c=IN IP4 127.0.0.1\r\n"
  27930. "t=0 0\r\n"
  27931. "m=audio 10000 RTP/AVP 0\r\n"
  27932. "a=rtpmap:0 PCMU/8000\r\n"
  27933. };
  27934. /* Two messages that appear in two fragments. Fragment
  27935. * boundaries do not align with message boundaries.
  27936. * Fragments combine to make "multi_message_divided"
  27937. */
  27938. char *multi_message_in_fragments[] = {
  27939. "SIP/2.0 100 Trying\r\n"
  27940. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27941. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27942. "To: <sip:bob@example.org:5060>\r\n"
  27943. "Call-ID: 12345\r\n"
  27944. "CSeq: 1 INVI",
  27945. "TE\r\n"
  27946. "Contact: <sip:bob@example.org:5060>\r\n"
  27947. "Content-Length: 0\r\n"
  27948. "\r\n"
  27949. "SIP/2.0 180 Ringing\r\n"
  27950. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27951. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27952. "To: <sip:bob@example.org:5060>\r\n"
  27953. "Call-ID: 12345\r\n"
  27954. "CSeq: 1 INVITE\r\n"
  27955. "Contact: <sip:bob@example.org:5060>\r\n"
  27956. "Content-Length: 0\r\n"
  27957. "\r\n"
  27958. };
  27959. /* Message with compact content-length header
  27960. * Same as "normal" but with compact content-length header
  27961. */
  27962. char *compact[] = {
  27963. "INVITE sip:bob@example.org SIP/2.0\r\n"
  27964. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27965. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27966. "To: <sip:bob@example.org:5060>\r\n"
  27967. "Call-ID: 12345\r\n"
  27968. "CSeq: 1 INVITE\r\n"
  27969. "Contact: sip:127.0.0.1:5061\r\n"
  27970. "Max-Forwards: 70\r\n"
  27971. "Content-Type: application/sdp\r\n"
  27972. "l:130\r\n" /* intentionally no space */
  27973. "\r\n"
  27974. "v=0\r\n"
  27975. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  27976. "s=-\r\n"
  27977. "c=IN IP4 127.0.0.1\r\n"
  27978. "t=0 0\r\n"
  27979. "m=audio 10000 RTP/AVP 0\r\n"
  27980. "a=rtpmap:0 PCMU/8000\r\n"
  27981. };
  27982. /* Message with faux content-length headers
  27983. * Same as "normal" but with extra fake content-length headers
  27984. */
  27985. char *faux[] = {
  27986. "INVITE sip:bob@example.org SIP/2.0\r\n"
  27987. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  27988. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  27989. "To: <sip:bob@example.org:5060>\r\n"
  27990. "Call-ID: 12345\r\n"
  27991. "CSeq: 1 INVITE\r\n"
  27992. "Contact: sip:127.0.0.1:5061\r\n"
  27993. "Max-Forwards: 70\r\n"
  27994. "Content-Type: application/sdp\r\n"
  27995. "DisContent-Length: 0\r\n"
  27996. "MalContent-Length: 60\r\n"
  27997. "Content-Length:130\r\n" /* intentionally no space */
  27998. "\r\n"
  27999. "v=0\r\n"
  28000. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  28001. "s=-\r\n"
  28002. "c=IN IP4 127.0.0.1\r\n"
  28003. "t=0 0\r\n"
  28004. "m=audio 10000 RTP/AVP 0\r\n"
  28005. "a=rtpmap:0 PCMU/8000\r\n"
  28006. };
  28007. /* Message with folded Content-Length header
  28008. * Message is "normal" with Content-Length spread across three lines
  28009. *
  28010. * This is the test that requires pedantic=yes in order to pass
  28011. */
  28012. char *folded[] = {
  28013. "INVITE sip:bob@example.org SIP/2.0\r\n"
  28014. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  28015. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  28016. "To: <sip:bob@example.org:5060>\r\n"
  28017. "Call-ID: 12345\r\n"
  28018. "CSeq: 1 INVITE\r\n"
  28019. "Contact: sip:127.0.0.1:5061\r\n"
  28020. "Max-Forwards: 70\r\n"
  28021. "Content-Type: application/sdp\r\n"
  28022. "Content-Length: \t\r\n"
  28023. "\t \r\n"
  28024. " 130\t \r\n"
  28025. "\r\n"
  28026. "v=0\r\n"
  28027. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  28028. "s=-\r\n"
  28029. "c=IN IP4 127.0.0.1\r\n"
  28030. "t=0 0\r\n"
  28031. "m=audio 10000 RTP/AVP 0\r\n"
  28032. "a=rtpmap:0 PCMU/8000\r\n"
  28033. };
  28034. /* Message with compact Content-length header in message and
  28035. * full Content-Length header in the body. Ensure that the header
  28036. * in the message is read and that the one in the body is ignored
  28037. */
  28038. char *cl_in_body[] = {
  28039. "INVITE sip:bob@example.org SIP/2.0\r\n"
  28040. "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
  28041. "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
  28042. "To: <sip:bob@example.org:5060>\r\n"
  28043. "Call-ID: 12345\r\n"
  28044. "CSeq: 1 INVITE\r\n"
  28045. "Contact: sip:127.0.0.1:5061\r\n"
  28046. "Max-Forwards: 70\r\n"
  28047. "Content-Type: application/sdp\r\n"
  28048. "l: 149\r\n"
  28049. "\r\n"
  28050. "v=0\r\n"
  28051. "Content-Length: 0\r\n"
  28052. "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
  28053. "s=-\r\n"
  28054. "c=IN IP4 127.0.0.1\r\n"
  28055. "t=0 0\r\n"
  28056. "m=audio 10000 RTP/AVP 0\r\n"
  28057. "a=rtpmap:0 PCMU/8000\r\n"
  28058. };
  28059. struct ast_str *overflow;
  28060. struct {
  28061. char **fragments;
  28062. char **expected;
  28063. int num_expected;
  28064. const char *description;
  28065. } tests[] = {
  28066. { normal, normal, 1, "normal" },
  28067. { fragmented, normal, 1, "fragmented" },
  28068. { fragmented_body, normal, 1, "fragmented_body" },
  28069. { multi_fragment, normal, 1, "multi_fragment" },
  28070. { multi_message, multi_message_divided, 2, "multi_message" },
  28071. { multi_message_body, multi_message_body_divided, 2, "multi_message_body" },
  28072. { multi_message_in_fragments, multi_message_divided, 2, "multi_message_in_fragments" },
  28073. { compact, compact, 1, "compact" },
  28074. { faux, faux, 1, "faux" },
  28075. { folded, folded, 1, "folded" },
  28076. { cl_in_body, cl_in_body, 1, "cl_in_body" },
  28077. };
  28078. int i;
  28079. enum ast_test_result_state res = AST_TEST_PASS;
  28080. switch (cmd) {
  28081. case TEST_INIT:
  28082. info->name = "sip_tcp_message_fragmentation";
  28083. info->category = "/main/sip/transport/";
  28084. info->summary = "SIP TCP message fragmentation test";
  28085. info->description =
  28086. "Tests reception of different TCP messages that have been fragmented or"
  28087. "run together. This test mimicks the code that TCP reception uses.";
  28088. return AST_TEST_NOT_RUN;
  28089. case TEST_EXECUTE:
  28090. break;
  28091. }
  28092. if (!sip_cfg.pedanticsipchecking) {
  28093. ast_log(LOG_WARNING, "Not running test. Pedantic SIP checking is not enabled, so it is guaranteed to fail\n");
  28094. return AST_TEST_NOT_RUN;
  28095. }
  28096. overflow = ast_str_create(128);
  28097. if (!overflow) {
  28098. return AST_TEST_FAIL;
  28099. }
  28100. for (i = 0; i < ARRAY_LEN(tests); ++i) {
  28101. int num_messages = 0;
  28102. if (mock_tcp_loop(tests[i].fragments, ARRAY_LEN(tests[i].fragments),
  28103. &overflow, tests[i].expected, &num_messages, test)) {
  28104. ast_test_status_update(test, "Failed to parse message '%s'\n", tests[i].description);
  28105. res = AST_TEST_FAIL;
  28106. break;
  28107. }
  28108. if (num_messages != tests[i].num_expected) {
  28109. ast_test_status_update(test, "Did not receive the expected number of messages. "
  28110. "Expected %d but received %d\n", tests[i].num_expected, num_messages);
  28111. res = AST_TEST_FAIL;
  28112. break;
  28113. }
  28114. }
  28115. ast_free(overflow);
  28116. return res;
  28117. }
  28118. AST_TEST_DEFINE(get_in_brackets_const_test)
  28119. {
  28120. const char *input;
  28121. const char *start = NULL;
  28122. int len = 0;
  28123. int res;
  28124. #define CHECK_RESULTS(in, expected_res, expected_start, expected_len) do { \
  28125. input = (in); \
  28126. res = get_in_brackets_const(input, &start, &len); \
  28127. if ((expected_res) != res) { \
  28128. ast_test_status_update(test, "Unexpected result: %d != %d\n", expected_res, res); \
  28129. return AST_TEST_FAIL; \
  28130. } \
  28131. if ((expected_start) != start) { \
  28132. const char *e = expected_start ? expected_start : "(null)"; \
  28133. const char *a = start ? start : "(null)"; \
  28134. ast_test_status_update(test, "Unexpected start: %s != %s\n", e, a); \
  28135. return AST_TEST_FAIL; \
  28136. } \
  28137. if ((expected_len) != len) { \
  28138. ast_test_status_update(test, "Unexpected len: %d != %d\n", expected_len, len); \
  28139. return AST_TEST_FAIL; \
  28140. } \
  28141. } while(0)
  28142. switch (cmd) {
  28143. case TEST_INIT:
  28144. info->name = __func__;
  28145. info->category = "/channels/chan_sip/";
  28146. info->summary = "get_in_brackets_const test";
  28147. info->description =
  28148. "Tests the get_in_brackets_const function";
  28149. return AST_TEST_NOT_RUN;
  28150. case TEST_EXECUTE:
  28151. break;
  28152. }
  28153. CHECK_RESULTS("", 1, NULL, -1);
  28154. CHECK_RESULTS("normal <test>", 0, input + 8, 4);
  28155. CHECK_RESULTS("\"normal\" <test>", 0, input + 10, 4);
  28156. CHECK_RESULTS("not normal <test", -1, NULL, -1);
  28157. CHECK_RESULTS("\"yes < really\" <test>", 0, input + 16, 4);
  28158. CHECK_RESULTS("\"even > this\" <test>", 0, input + 15, 4);
  28159. CHECK_RESULTS("<sip:id1@10.10.10.10;lr>", 0, input + 1, 22);
  28160. CHECK_RESULTS("<sip:id1@10.10.10.10;lr>, <sip:id1@10.10.10.20;lr>", 0, input + 1, 22);
  28161. CHECK_RESULTS("<sip:id1,id2@10.10.10.10;lr>", 0, input + 1, 26);
  28162. CHECK_RESULTS("<sip:id1@10., <sip:id2@10.10.10.10;lr>", 0, input + 1, 36);
  28163. CHECK_RESULTS("\"quoted text\" <sip:dlg1@10.10.10.10;lr>", 0, input + 15, 23);
  28164. return AST_TEST_PASS;
  28165. }
  28166. #endif
  28167. #define DATA_EXPORT_SIP_PEER(MEMBER) \
  28168. MEMBER(sip_peer, name, AST_DATA_STRING) \
  28169. MEMBER(sip_peer, secret, AST_DATA_PASSWORD) \
  28170. MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD) \
  28171. MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD) \
  28172. MEMBER(sip_peer, context, AST_DATA_STRING) \
  28173. MEMBER(sip_peer, subscribecontext, AST_DATA_STRING) \
  28174. MEMBER(sip_peer, username, AST_DATA_STRING) \
  28175. MEMBER(sip_peer, accountcode, AST_DATA_STRING) \
  28176. MEMBER(sip_peer, tohost, AST_DATA_STRING) \
  28177. MEMBER(sip_peer, regexten, AST_DATA_STRING) \
  28178. MEMBER(sip_peer, fromuser, AST_DATA_STRING) \
  28179. MEMBER(sip_peer, fromdomain, AST_DATA_STRING) \
  28180. MEMBER(sip_peer, fullcontact, AST_DATA_STRING) \
  28181. MEMBER(sip_peer, cid_num, AST_DATA_STRING) \
  28182. MEMBER(sip_peer, cid_name, AST_DATA_STRING) \
  28183. MEMBER(sip_peer, vmexten, AST_DATA_STRING) \
  28184. MEMBER(sip_peer, language, AST_DATA_STRING) \
  28185. MEMBER(sip_peer, mohinterpret, AST_DATA_STRING) \
  28186. MEMBER(sip_peer, mohsuggest, AST_DATA_STRING) \
  28187. MEMBER(sip_peer, parkinglot, AST_DATA_STRING) \
  28188. MEMBER(sip_peer, useragent, AST_DATA_STRING) \
  28189. MEMBER(sip_peer, mwi_from, AST_DATA_STRING) \
  28190. MEMBER(sip_peer, engine, AST_DATA_STRING) \
  28191. MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING) \
  28192. MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN) \
  28193. MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN) \
  28194. MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN) \
  28195. MEMBER(sip_peer, inUse, AST_DATA_INTEGER) \
  28196. MEMBER(sip_peer, inRinging, AST_DATA_INTEGER) \
  28197. MEMBER(sip_peer, onHold, AST_DATA_INTEGER) \
  28198. MEMBER(sip_peer, call_limit, AST_DATA_INTEGER) \
  28199. MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER) \
  28200. MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
  28201. MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS) \
  28202. MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
  28203. MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS) \
  28204. MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS) \
  28205. MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS) \
  28206. MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS) \
  28207. MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS) \
  28208. MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)
  28209. AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
  28210. static int peers_data_provider_get(const struct ast_data_search *search,
  28211. struct ast_data *data_root)
  28212. {
  28213. struct sip_peer *peer;
  28214. struct ao2_iterator i;
  28215. struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
  28216. struct ast_data *data_sip_options;
  28217. int total_mailboxes, x;
  28218. struct sip_mailbox *mailbox;
  28219. i = ao2_iterator_init(peers, 0);
  28220. while ((peer = ao2_iterator_next(&i))) {
  28221. ao2_lock(peer);
  28222. data_peer = ast_data_add_node(data_root, "peer");
  28223. if (!data_peer) {
  28224. ao2_unlock(peer);
  28225. ao2_ref(peer, -1);
  28226. continue;
  28227. }
  28228. ast_data_add_structure(sip_peer, data_peer, peer);
  28229. /* transfer mode */
  28230. enum_node = ast_data_add_node(data_peer, "allowtransfer");
  28231. if (!enum_node) {
  28232. ao2_unlock(peer);
  28233. ao2_ref(peer, -1);
  28234. continue;
  28235. }
  28236. ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
  28237. ast_data_add_int(enum_node, "value", peer->allowtransfer);
  28238. /* transports */
  28239. ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
  28240. /* peer type */
  28241. if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
  28242. ast_data_add_str(data_peer, "type", "friend");
  28243. } else if (peer->type & SIP_TYPE_PEER) {
  28244. ast_data_add_str(data_peer, "type", "peer");
  28245. } else if (peer->type & SIP_TYPE_USER) {
  28246. ast_data_add_str(data_peer, "type", "user");
  28247. }
  28248. /* mailboxes */
  28249. total_mailboxes = 0;
  28250. AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
  28251. if (!total_mailboxes) {
  28252. data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
  28253. if (!data_peer_mailboxes) {
  28254. break;
  28255. }
  28256. total_mailboxes++;
  28257. }
  28258. data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
  28259. if (!data_peer_mailbox) {
  28260. continue;
  28261. }
  28262. ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
  28263. ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
  28264. }
  28265. /* amaflags */
  28266. enum_node = ast_data_add_node(data_peer, "amaflags");
  28267. if (!enum_node) {
  28268. ao2_unlock(peer);
  28269. ao2_ref(peer, -1);
  28270. continue;
  28271. }
  28272. ast_data_add_int(enum_node, "value", peer->amaflags);
  28273. ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
  28274. /* sip options */
  28275. data_sip_options = ast_data_add_node(data_peer, "sipoptions");
  28276. if (!data_sip_options) {
  28277. ao2_unlock(peer);
  28278. ao2_ref(peer, -1);
  28279. continue;
  28280. }
  28281. for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
  28282. ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
  28283. }
  28284. /* callingpres */
  28285. enum_node = ast_data_add_node(data_peer, "callingpres");
  28286. if (!enum_node) {
  28287. ao2_unlock(peer);
  28288. ao2_ref(peer, -1);
  28289. continue;
  28290. }
  28291. ast_data_add_int(enum_node, "value", peer->callingpres);
  28292. ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
  28293. /* codecs */
  28294. ast_data_add_codecs(data_peer, "codecs", peer->capability);
  28295. if (!ast_data_search_match(search, data_peer)) {
  28296. ast_data_remove_node(data_root, data_peer);
  28297. }
  28298. ao2_unlock(peer);
  28299. ao2_ref(peer, -1);
  28300. }
  28301. ao2_iterator_destroy(&i);
  28302. return 0;
  28303. }
  28304. static const struct ast_data_handler peers_data_provider = {
  28305. .version = AST_DATA_HANDLER_VERSION,
  28306. .get = peers_data_provider_get
  28307. };
  28308. static const struct ast_data_entry sip_data_providers[] = {
  28309. AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
  28310. };
  28311. /*! \brief PBX load module - initialization */
  28312. static int load_module(void)
  28313. {
  28314. ast_verbose("SIP channel loading...\n");
  28315. /* the fact that ao2_containers can't resize automatically is a major worry! */
  28316. /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
  28317. peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
  28318. peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
  28319. dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
  28320. dialogs_to_destroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_to_destroy");
  28321. threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
  28322. if (!peers || !peers_by_ip || !dialogs || !dialogs_to_destroy || !threadt) {
  28323. ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
  28324. return AST_MODULE_LOAD_FAILURE;
  28325. }
  28326. ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
  28327. ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
  28328. if (!(sched = sched_context_create())) {
  28329. ast_log(LOG_ERROR, "Unable to create scheduler context\n");
  28330. return AST_MODULE_LOAD_FAILURE;
  28331. }
  28332. if (!(io = io_context_create())) {
  28333. ast_log(LOG_ERROR, "Unable to create I/O context\n");
  28334. sched_context_destroy(sched);
  28335. return AST_MODULE_LOAD_FAILURE;
  28336. }
  28337. sip_reloadreason = CHANNEL_MODULE_LOAD;
  28338. can_parse_xml = sip_is_xml_parsable();
  28339. if (reload_config(sip_reloadreason)) { /* Load the configuration from sip.conf */
  28340. return AST_MODULE_LOAD_DECLINE;
  28341. }
  28342. /* Initialize bogus peer. Can be done first after reload_config() */
  28343. if (!(bogus_peer = temp_peer("(bogus_peer)"))) {
  28344. ast_log(LOG_ERROR, "Unable to create bogus_peer for authentication\n");
  28345. io_context_destroy(io);
  28346. sched_context_destroy(sched);
  28347. return AST_MODULE_LOAD_FAILURE;
  28348. }
  28349. /* Make sure the auth will always fail. */
  28350. ast_string_field_set(bogus_peer, md5secret, BOGUS_PEER_MD5SECRET);
  28351. ast_clear_flag(&bogus_peer->flags[0], SIP_INSECURE);
  28352. /* Prepare the version that does not require DTMF BEGIN frames.
  28353. * We need to use tricks such as memcpy and casts because the variable
  28354. * has const fields.
  28355. */
  28356. memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
  28357. memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
  28358. /* Make sure we can register our sip channel type */
  28359. if (ast_channel_register(&sip_tech)) {
  28360. ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
  28361. ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
  28362. io_context_destroy(io);
  28363. sched_context_destroy(sched);
  28364. return AST_MODULE_LOAD_FAILURE;
  28365. }
  28366. #ifdef TEST_FRAMEWORK
  28367. AST_TEST_REGISTER(test_sip_peers_get);
  28368. AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
  28369. AST_TEST_REGISTER(test_tcp_message_fragmentation);
  28370. AST_TEST_REGISTER(get_in_brackets_const_test);
  28371. #endif
  28372. /* Register AstData providers */
  28373. ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
  28374. /* Register all CLI functions for SIP */
  28375. ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
  28376. /* Tell the UDPTL subdriver that we're here */
  28377. ast_udptl_proto_register(&sip_udptl);
  28378. /* Tell the RTP engine about our RTP glue */
  28379. ast_rtp_glue_register(&sip_rtp_glue);
  28380. /* Register dialplan applications */
  28381. ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
  28382. ast_register_application_xml(app_sipaddheader, sip_addheader);
  28383. ast_register_application_xml(app_sipremoveheader, sip_removeheader);
  28384. /* Register dialplan functions */
  28385. ast_custom_function_register(&sip_header_function);
  28386. ast_custom_function_register(&sippeer_function);
  28387. ast_custom_function_register(&sipchaninfo_function);
  28388. ast_custom_function_register(&checksipdomain_function);
  28389. /* Register manager commands */
  28390. ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
  28391. ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
  28392. ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
  28393. ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
  28394. ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
  28395. sip_poke_all_peers();
  28396. sip_send_all_registers();
  28397. sip_send_all_mwi_subscriptions();
  28398. initialize_escs();
  28399. if (sip_epa_register(&cc_epa_static_data)) {
  28400. return AST_MODULE_LOAD_DECLINE;
  28401. }
  28402. if (sip_reqresp_parser_init() == -1) {
  28403. ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
  28404. return AST_MODULE_LOAD_DECLINE;
  28405. }
  28406. if (can_parse_xml) {
  28407. /* SIP CC agents require the ability to parse XML PIDF bodies
  28408. * in incoming PUBLISH requests
  28409. */
  28410. if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
  28411. return AST_MODULE_LOAD_DECLINE;
  28412. }
  28413. }
  28414. if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
  28415. return AST_MODULE_LOAD_DECLINE;
  28416. }
  28417. if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
  28418. return AST_MODULE_LOAD_DECLINE;
  28419. }
  28420. /* And start the monitor for the first time */
  28421. restart_monitor();
  28422. ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
  28423. "name", RQ_CHAR, 10,
  28424. "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
  28425. "port", RQ_UINTEGER2, 5,
  28426. "regseconds", RQ_INTEGER4, 11,
  28427. "defaultuser", RQ_CHAR, 10,
  28428. "fullcontact", RQ_CHAR, 35,
  28429. "regserver", RQ_CHAR, 20,
  28430. "useragent", RQ_CHAR, 20,
  28431. "lastms", RQ_INTEGER4, 11,
  28432. SENTINEL);
  28433. sip_register_tests();
  28434. network_change_event_subscribe();
  28435. return AST_MODULE_LOAD_SUCCESS;
  28436. }
  28437. /*! \brief PBX unload module API */
  28438. static int unload_module(void)
  28439. {
  28440. struct sip_pvt *p;
  28441. struct sip_threadinfo *th;
  28442. struct ast_context *con;
  28443. struct ao2_iterator i;
  28444. int wait_count;
  28445. network_change_event_unsubscribe();
  28446. ast_sched_dump(sched);
  28447. /* First, take us out of the channel type list */
  28448. ast_channel_unregister(&sip_tech);
  28449. /* Unregister dial plan functions */
  28450. ast_custom_function_unregister(&sipchaninfo_function);
  28451. ast_custom_function_unregister(&sippeer_function);
  28452. ast_custom_function_unregister(&sip_header_function);
  28453. ast_custom_function_unregister(&checksipdomain_function);
  28454. /* Unregister dial plan applications */
  28455. ast_unregister_application(app_dtmfmode);
  28456. ast_unregister_application(app_sipaddheader);
  28457. ast_unregister_application(app_sipremoveheader);
  28458. #ifdef TEST_FRAMEWORK
  28459. AST_TEST_UNREGISTER(test_sip_peers_get);
  28460. AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
  28461. AST_TEST_UNREGISTER(test_tcp_message_fragmentation);
  28462. AST_TEST_UNREGISTER(get_in_brackets_const_test);
  28463. #endif
  28464. /* Unregister all the AstData providers */
  28465. ast_data_unregister(NULL);
  28466. /* Unregister CLI commands */
  28467. ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
  28468. /* Disconnect from UDPTL */
  28469. ast_udptl_proto_unregister(&sip_udptl);
  28470. /* Disconnect from RTP engine */
  28471. ast_rtp_glue_unregister(&sip_rtp_glue);
  28472. /* Unregister AMI actions */
  28473. ast_manager_unregister("SIPpeers");
  28474. ast_manager_unregister("SIPshowpeer");
  28475. ast_manager_unregister("SIPqualifypeer");
  28476. ast_manager_unregister("SIPshowregistry");
  28477. ast_manager_unregister("SIPnotify");
  28478. /* Kill TCP/TLS server threads */
  28479. if (sip_tcp_desc.master) {
  28480. ast_tcptls_server_stop(&sip_tcp_desc);
  28481. }
  28482. if (sip_tls_desc.master) {
  28483. ast_tcptls_server_stop(&sip_tls_desc);
  28484. }
  28485. ast_ssl_teardown(sip_tls_desc.tls_cfg);
  28486. /* Kill all existing TCP/TLS threads */
  28487. i = ao2_iterator_init(threadt, 0);
  28488. while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
  28489. pthread_t thread = th->threadid;
  28490. th->stop = 1;
  28491. pthread_kill(thread, SIGURG);
  28492. ao2_t_ref(th, -1, "decrement ref from iterator");
  28493. }
  28494. ao2_iterator_destroy(&i);
  28495. /* Hangup all dialogs if they have an owner */
  28496. i = ao2_iterator_init(dialogs, 0);
  28497. while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  28498. if (p->owner)
  28499. ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
  28500. ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
  28501. }
  28502. ao2_iterator_destroy(&i);
  28503. unlink_all_peers_from_tables();
  28504. ast_mutex_lock(&monlock);
  28505. if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
  28506. pthread_t th = monitor_thread;
  28507. monitor_thread = AST_PTHREADT_STOP;
  28508. pthread_cancel(th);
  28509. pthread_kill(th, SIGURG);
  28510. ast_mutex_unlock(&monlock);
  28511. pthread_join(th, NULL);
  28512. } else {
  28513. monitor_thread = AST_PTHREADT_STOP;
  28514. ast_mutex_unlock(&monlock);
  28515. }
  28516. /* Destroy all the dialogs and free their memory */
  28517. i = ao2_iterator_init(dialogs, 0);
  28518. while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
  28519. dialog_unlink_all(p);
  28520. ao2_t_ref(p, -1, "throw away iterator result");
  28521. }
  28522. ao2_iterator_destroy(&i);
  28523. /* Free memory for local network address mask */
  28524. ast_free_ha(localaddr);
  28525. ast_mutex_lock(&authl_lock);
  28526. if (authl) {
  28527. ao2_t_ref(authl, -1, "Removing global authentication");
  28528. authl = NULL;
  28529. }
  28530. ast_mutex_unlock(&authl_lock);
  28531. sip_epa_unregister_all();
  28532. destroy_escs();
  28533. ast_free(default_tls_cfg.certfile);
  28534. ast_free(default_tls_cfg.pvtfile);
  28535. ast_free(default_tls_cfg.cipher);
  28536. ast_free(default_tls_cfg.cafile);
  28537. ast_free(default_tls_cfg.capath);
  28538. cleanup_all_regs();
  28539. ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
  28540. ASTOBJ_CONTAINER_DESTROY(&regl);
  28541. ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
  28542. ASTOBJ_WRLOCK(iterator);
  28543. if (iterator->dnsmgr) {
  28544. ast_dnsmgr_release(iterator->dnsmgr);
  28545. iterator->dnsmgr = NULL;
  28546. ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
  28547. }
  28548. ASTOBJ_UNLOCK(iterator);
  28549. } while(0));
  28550. ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
  28551. ASTOBJ_CONTAINER_DESTROY(&submwil);
  28552. /*
  28553. * Wait awhile for the TCP/TLS thread container to become empty.
  28554. *
  28555. * XXX This is a hack, but the worker threads cannot be created
  28556. * joinable. They can die on their own and remove themselves
  28557. * from the container thus resulting in a huge memory leak.
  28558. */
  28559. wait_count = 1000;
  28560. while (ao2_container_count(threadt) && --wait_count) {
  28561. sched_yield();
  28562. }
  28563. if (!wait_count) {
  28564. ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
  28565. }
  28566. ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
  28567. ao2_t_ref(peers, -1, "unref the peers table");
  28568. ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
  28569. ao2_t_ref(dialogs, -1, "unref the dialogs table");
  28570. ao2_t_ref(dialogs_to_destroy, -1, "unref dialogs_to_destroy");
  28571. ao2_t_ref(threadt, -1, "unref the thread table");
  28572. ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
  28573. clear_sip_domains();
  28574. ast_free_ha(sip_cfg.contact_ha);
  28575. if (sipsock_read_id) {
  28576. ast_io_remove(io, sipsock_read_id);
  28577. sipsock_read_id = NULL;
  28578. }
  28579. close(sipsock);
  28580. io_context_destroy(io);
  28581. sched_context_destroy(sched);
  28582. con = ast_context_find(used_context);
  28583. if (con) {
  28584. ast_context_destroy(con, "SIP");
  28585. }
  28586. ast_unload_realtime("sipregs");
  28587. ast_unload_realtime("sippeers");
  28588. ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
  28589. ast_cc_agent_unregister(&sip_cc_agent_callbacks);
  28590. sip_reqresp_parser_exit();
  28591. sip_unregister_tests();
  28592. if (notify_types) {
  28593. ast_config_destroy(notify_types);
  28594. notify_types = NULL;
  28595. }
  28596. return 0;
  28597. }
  28598. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
  28599. .load = load_module,
  28600. .unload = unload_module,
  28601. .reload = reload,
  28602. .load_pri = AST_MODPRI_CHANNEL_DRIVER,
  28603. .nonoptreq = "res_crypto,chan_local",
  28604. );