res_pjsip_pubsub.c 185 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2013, Digium, Inc.
  5. *
  6. * Mark Michelson <mmichelson@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. * \brief Opaque structure representing an RFC 3265 SIP subscription
  20. */
  21. /*** MODULEINFO
  22. <depend>pjproject</depend>
  23. <depend>res_pjsip</depend>
  24. <support_level>core</support_level>
  25. ***/
  26. #include "asterisk.h"
  27. #include <pjsip.h>
  28. #include <pjsip_simple.h>
  29. #include <pjlib.h>
  30. #include "asterisk/mwi.h"
  31. #include "asterisk/res_pjsip_pubsub.h"
  32. #include "asterisk/module.h"
  33. #include "asterisk/linkedlists.h"
  34. #include "asterisk/astobj2.h"
  35. #include "asterisk/datastore.h"
  36. #include "asterisk/uuid.h"
  37. #include "asterisk/taskprocessor.h"
  38. #include "asterisk/sched.h"
  39. #include "asterisk/res_pjsip.h"
  40. #include "asterisk/callerid.h"
  41. #include "asterisk/manager.h"
  42. #include "asterisk/cli.h"
  43. #include "asterisk/test.h"
  44. #include "res_pjsip/include/res_pjsip_private.h"
  45. #include "asterisk/res_pjsip_presence_xml.h"
  46. /*** DOCUMENTATION
  47. <manager name="PJSIPShowSubscriptionsInbound" language="en_US">
  48. <synopsis>
  49. Lists subscriptions.
  50. </synopsis>
  51. <syntax />
  52. <description>
  53. <para>
  54. Provides a listing of all inbound subscriptions. An event <literal>InboundSubscriptionDetail</literal>
  55. is issued for each subscription object. Once all detail events are completed an
  56. <literal>InboundSubscriptionDetailComplete</literal> event is issued.
  57. </para>
  58. </description>
  59. </manager>
  60. <manager name="PJSIPShowSubscriptionsOutbound" language="en_US">
  61. <synopsis>
  62. Lists subscriptions.
  63. </synopsis>
  64. <syntax />
  65. <description>
  66. <para>
  67. Provides a listing of all outbound subscriptions. An event <literal>OutboundSubscriptionDetail</literal>
  68. is issued for each subscription object. Once all detail events are completed an
  69. <literal>OutboundSubscriptionDetailComplete</literal> event is issued.
  70. </para>
  71. </description>
  72. </manager>
  73. <manager name="PJSIPShowResourceLists" language="en_US">
  74. <synopsis>
  75. Displays settings for configured resource lists.
  76. </synopsis>
  77. <syntax />
  78. <description>
  79. <para>
  80. Provides a listing of all resource lists. An event <literal>ResourceListDetail</literal>
  81. is issued for each resource list object. Once all detail events are completed a
  82. <literal>ResourceListDetailComplete</literal> event is issued.
  83. </para>
  84. </description>
  85. </manager>
  86. <configInfo name="res_pjsip_pubsub" language="en_US">
  87. <synopsis>Module that implements publish and subscribe support.</synopsis>
  88. <configFile name="pjsip.conf">
  89. <configObject name="subscription_persistence">
  90. <synopsis>Persists SIP subscriptions so they survive restarts.</synopsis>
  91. <configOption name="packet">
  92. <synopsis>Entire SIP SUBSCRIBE packet that created the subscription</synopsis>
  93. </configOption>
  94. <configOption name="src_name">
  95. <synopsis>The source address of the subscription</synopsis>
  96. </configOption>
  97. <configOption name="src_port">
  98. <synopsis>The source port of the subscription</synopsis>
  99. </configOption>
  100. <configOption name="transport_key">
  101. <synopsis>The type of transport the subscription was received on</synopsis>
  102. </configOption>
  103. <configOption name="local_name">
  104. <synopsis>The local address the subscription was received on</synopsis>
  105. </configOption>
  106. <configOption name="local_port">
  107. <synopsis>The local port the subscription was received on</synopsis>
  108. </configOption>
  109. <configOption name="cseq">
  110. <synopsis>The sequence number of the next NOTIFY to be sent</synopsis>
  111. </configOption>
  112. <configOption name="tag">
  113. <synopsis>The local tag of the dialog for the subscription</synopsis>
  114. </configOption>
  115. <configOption name="endpoint">
  116. <synopsis>The name of the endpoint that subscribed</synopsis>
  117. </configOption>
  118. <configOption name="expires">
  119. <synopsis>The time at which the subscription expires</synopsis>
  120. </configOption>
  121. <configOption name="contact_uri">
  122. <synopsis>The Contact URI of the dialog for the subscription</synopsis>
  123. </configOption>
  124. <configOption name="prune_on_boot">
  125. <synopsis>If set, indicates that the contact used a reliable transport
  126. and therefore the subscription must be deleted after an asterisk restart.
  127. </synopsis>
  128. </configOption>
  129. <configOption name="generator_data">
  130. <synopsis>If set, contains persistence data for all generators of content
  131. for the subscription.
  132. </synopsis>
  133. </configOption>
  134. </configObject>
  135. <configObject name="resource_list">
  136. <synopsis>Resource list configuration parameters.</synopsis>
  137. <description>
  138. <para>This configuration object allows for RFC 4662 resource list subscriptions
  139. to be specified. This can be useful to decrease the amount of subscription traffic
  140. that a server has to process.</para>
  141. <note>
  142. <para>Current limitations limit the size of SIP NOTIFY requests that Asterisk sends
  143. to double that of the PJSIP maximum packet length. If your resource list notifications
  144. are larger than this maximum, you will need to make adjustments.</para>
  145. </note>
  146. </description>
  147. <configOption name="type">
  148. <synopsis>Must be of type 'resource_list'</synopsis>
  149. </configOption>
  150. <configOption name="event">
  151. <synopsis>The SIP event package that the list resource belong to.</synopsis>
  152. <description><para>
  153. The SIP event package describes the types of resources that Asterisk reports
  154. the state of.
  155. </para>
  156. <enumlist>
  157. <enum name="presence"><para>
  158. Device state and presence reporting.
  159. </para></enum>
  160. <enum name="dialog"><para>
  161. This is identical to <replaceable>presence</replaceable>.
  162. </para></enum>
  163. <enum name="message-summary"><para>
  164. Message-waiting indication (MWI) reporting.
  165. </para></enum>
  166. </enumlist>
  167. </description>
  168. </configOption>
  169. <configOption name="list_item">
  170. <synopsis>The name of a resource to report state on</synopsis>
  171. <description>
  172. <para>In general Asterisk looks up list items in the following way:</para>
  173. <para>1. Check if the list item refers to another configured resource list.</para>
  174. <para>2. Pass the name of the resource off to event-package-specific handlers
  175. to find the specified resource.</para>
  176. <para>The second part means that the way the list item is specified depends
  177. on what type of list this is. For instance, if you have the <replaceable>event</replaceable>
  178. set to <literal>presence</literal>, then list items should be in the form of
  179. dialplan_extension@dialplan_context. For <literal>message-summary</literal> mailbox
  180. names should be listed.</para>
  181. </description>
  182. </configOption>
  183. <configOption name="full_state" default="no">
  184. <synopsis>Indicates if the entire list's state should be sent out.</synopsis>
  185. <description>
  186. <para>If this option is enabled, and a resource changes state, then Asterisk will construct
  187. a notification that contains the state of all resources in the list. If the option is
  188. disabled, Asterisk will construct a notification that only contains the states of
  189. resources that have changed.</para>
  190. <note>
  191. <para>Even with this option disabled, there are certain situations where Asterisk is forced
  192. to send a notification with the states of all resources in the list. When a subscriber
  193. renews or terminates its subscription to the list, Asterisk MUST send a full state
  194. notification.</para>
  195. </note>
  196. </description>
  197. </configOption>
  198. <configOption name="notification_batch_interval" default="0">
  199. <synopsis>Time Asterisk should wait, in milliseconds, before sending notifications.</synopsis>
  200. <description>
  201. <para>When a resource's state changes, it may be desired to wait a certain amount before Asterisk
  202. sends a notification to subscribers. This allows for other state changes to accumulate, so that
  203. Asterisk can communicate multiple state changes in a single notification instead of rapidly sending
  204. many notifications.</para>
  205. </description>
  206. </configOption>
  207. <configOption name="resource_display_name" default="no">
  208. <synopsis>Indicates whether display name of resource or the resource name being reported.</synopsis>
  209. <description>
  210. <para>If this option is enabled, the Display Name will be reported as resource name.
  211. If the <replaceable>event</replaceable> set to <literal>presence</literal> or <literal>dialog</literal>,
  212. the non-empty HINT name will be set as the Display Name.
  213. The <literal>message-summary</literal> is not supported yet.</para>
  214. </description>
  215. </configOption>
  216. </configObject>
  217. <configObject name="inbound-publication">
  218. <synopsis>The configuration for inbound publications</synopsis>
  219. <configOption name="endpoint" default="">
  220. <synopsis>Optional name of an endpoint that is only allowed to publish to this resource</synopsis>
  221. </configOption>
  222. <configOption name="type">
  223. <synopsis>Must be of type 'inbound-publication'.</synopsis>
  224. </configOption>
  225. </configObject>
  226. </configFile>
  227. </configInfo>
  228. ***/
  229. static pj_bool_t pubsub_on_rx_request(pjsip_rx_data *rdata);
  230. static struct pjsip_module pubsub_module = {
  231. .name = { "PubSub Module", 13 },
  232. .priority = PJSIP_MOD_PRIORITY_APPLICATION,
  233. .on_rx_request = pubsub_on_rx_request,
  234. };
  235. #define MOD_DATA_PERSISTENCE "sub_persistence"
  236. #define MOD_DATA_MSG "sub_msg"
  237. static const pj_str_t str_event_name = { "Event", 5 };
  238. /*! \brief Scheduler used for automatically expiring publications */
  239. static struct ast_sched_context *sched;
  240. /*! \brief Number of buckets for publications (on a per handler) */
  241. #define PUBLICATIONS_BUCKETS 37
  242. /*! \brief Default expiration time for PUBLISH if one is not specified */
  243. #define DEFAULT_PUBLISH_EXPIRES 3600
  244. /*! \brief Number of buckets for subscription datastore */
  245. #define DATASTORE_BUCKETS 53
  246. /*! \brief Default expiration for subscriptions */
  247. #define DEFAULT_EXPIRES 3600
  248. /*! \brief Defined method for PUBLISH */
  249. const pjsip_method pjsip_publish_method =
  250. {
  251. PJSIP_OTHER_METHOD,
  252. { "PUBLISH", 7 }
  253. };
  254. /*!
  255. * \brief The types of PUBLISH messages defined in RFC 3903
  256. */
  257. enum sip_publish_type {
  258. /*!
  259. * \brief Unknown
  260. *
  261. * \details
  262. * This actually is not defined in RFC 3903. We use this as a constant
  263. * to indicate that an incoming PUBLISH does not fit into any of the
  264. * other categories and is thus invalid.
  265. */
  266. SIP_PUBLISH_UNKNOWN,
  267. /*!
  268. * \brief Initial
  269. *
  270. * \details
  271. * The first PUBLISH sent. This will contain a non-zero Expires header
  272. * as well as a body that indicates the current state of the endpoint
  273. * that has sent the message. The initial PUBLISH is the only type
  274. * of PUBLISH to not contain a Sip-If-Match header in it.
  275. */
  276. SIP_PUBLISH_INITIAL,
  277. /*!
  278. * \brief Refresh
  279. *
  280. * \details
  281. * Used to keep a published state from expiring. This will contain a
  282. * non-zero Expires header but no body since its purpose is not to
  283. * update state.
  284. */
  285. SIP_PUBLISH_REFRESH,
  286. /*!
  287. * \brief Modify
  288. *
  289. * \details
  290. * Used to change state from its previous value. This will contain
  291. * a body updating the published state. May or may not contain an
  292. * Expires header.
  293. */
  294. SIP_PUBLISH_MODIFY,
  295. /*!
  296. * \brief Remove
  297. *
  298. * \details
  299. * Used to remove published state from an ESC. This will contain
  300. * an Expires header set to 0 and likely no body.
  301. */
  302. SIP_PUBLISH_REMOVE,
  303. };
  304. /*!
  305. * \brief A vector of strings commonly used throughout this module
  306. */
  307. AST_VECTOR(resources, const char *);
  308. /*!
  309. * \brief Resource list configuration item
  310. */
  311. struct resource_list {
  312. SORCERY_OBJECT(details);
  313. /*! SIP event package the list uses. */
  314. char event[32];
  315. /*! Strings representing resources in the list. */
  316. struct resources items;
  317. /*! Indicates if Asterisk sends full or partial state on notifications. */
  318. unsigned int full_state;
  319. /*! Time, in milliseconds Asterisk waits before sending a batched notification.*/
  320. unsigned int notification_batch_interval;
  321. /*! Indicates whether display name of resource or the resource name being reported.*/
  322. unsigned int resource_display_name;
  323. };
  324. /*!
  325. * Used to create new entity IDs by ESCs.
  326. */
  327. static int esc_etag_counter;
  328. /*!
  329. * \brief Structure representing a SIP publication
  330. */
  331. struct ast_sip_publication {
  332. /*! Publication datastores set up by handlers */
  333. struct ao2_container *datastores;
  334. /*! \brief Entity tag for the publication */
  335. int entity_tag;
  336. /*! \brief Handler for this publication */
  337. struct ast_sip_publish_handler *handler;
  338. /*! \brief The endpoint with which the subscription is communicating */
  339. struct ast_sip_endpoint *endpoint;
  340. /*! \brief Expiration time of the publication */
  341. unsigned int expires;
  342. /*! \brief Scheduled item for expiration of publication */
  343. int sched_id;
  344. /*! \brief The resource the publication is to */
  345. char *resource;
  346. /*! \brief The name of the event type configuration */
  347. char *event_configuration_name;
  348. /*! \brief Data containing the above */
  349. char data[0];
  350. };
  351. /*!
  352. * \brief Structure used for persisting an inbound subscription
  353. */
  354. struct subscription_persistence {
  355. /*! Sorcery object details */
  356. SORCERY_OBJECT(details);
  357. /*! The name of the endpoint involved in the subscription */
  358. char *endpoint;
  359. /*! SIP message that creates the subscription */
  360. char packet[PJSIP_MAX_PKT_LEN];
  361. /*! Source address of the message */
  362. char src_name[PJ_INET6_ADDRSTRLEN];
  363. /*! Source port of the message */
  364. int src_port;
  365. /*! Local transport type (UDP,TCP,TLS)*/
  366. char transport_type[32];
  367. /*! Local transport address */
  368. char local_name[PJ_INET6_ADDRSTRLEN];
  369. /*! Local transport port */
  370. int local_port;
  371. /*! Next CSeq to use for message */
  372. unsigned int cseq;
  373. /*! Local tag of the dialog */
  374. char *tag;
  375. /*! When this subscription expires */
  376. struct timeval expires;
  377. /*! Contact URI */
  378. char contact_uri[PJSIP_MAX_URL_SIZE];
  379. /*! Prune subscription on restart */
  380. int prune_on_boot;
  381. /*! Body generator specific persistence data */
  382. struct ast_json *generator_data;
  383. };
  384. /*!
  385. * \brief The state of the subscription tree
  386. */
  387. enum sip_subscription_tree_state {
  388. /*! Normal operation */
  389. SIP_SUB_TREE_NORMAL = 0,
  390. /*! A terminate has been requested by Asterisk, the client, or pjproject */
  391. SIP_SUB_TREE_TERMINATE_PENDING,
  392. /*! The terminate is in progress */
  393. SIP_SUB_TREE_TERMINATE_IN_PROGRESS,
  394. /*! The terminate process has finished and the subscription tree is no longer valid */
  395. SIP_SUB_TREE_TERMINATED,
  396. };
  397. static char *sub_tree_state_description[] = {
  398. "Normal",
  399. "TerminatePending",
  400. "TerminateInProgress",
  401. "Terminated"
  402. };
  403. /*!
  404. * \brief A tree of SIP subscriptions
  405. *
  406. * Because of the ability to subscribe to resource lists, a SIP
  407. * subscription can result in a tree of subscriptions being created.
  408. * This structure represents the information relevant to the subscription
  409. * as a whole, to include the underlying PJSIP structure for the
  410. * subscription.
  411. */
  412. struct sip_subscription_tree {
  413. /*! The endpoint with which the subscription is communicating */
  414. struct ast_sip_endpoint *endpoint;
  415. /*! Serializer on which to place operations for this subscription */
  416. struct ast_taskprocessor *serializer;
  417. /*! The role for this subscription */
  418. enum ast_sip_subscription_role role;
  419. /*! Persistence information */
  420. struct subscription_persistence *persistence;
  421. /*! The underlying PJSIP event subscription structure */
  422. pjsip_evsub *evsub;
  423. /*! The underlying PJSIP dialog */
  424. pjsip_dialog *dlg;
  425. /*! Interval to use for batching notifications */
  426. unsigned int notification_batch_interval;
  427. /*! Scheduler ID for batched notification */
  428. int notify_sched_id;
  429. /*! Indicator if scheduled batched notification should be sent */
  430. unsigned int send_scheduled_notify;
  431. /*! The root of the subscription tree */
  432. struct ast_sip_subscription *root;
  433. /*! Is this subscription to a list? */
  434. int is_list;
  435. /*! Next item in the list */
  436. AST_LIST_ENTRY(sip_subscription_tree) next;
  437. /*! Subscription tree state */
  438. enum sip_subscription_tree_state state;
  439. /*! On asterisk restart, this is the task data used
  440. * to restart the expiration timer if pjproject isn't
  441. * capable of restarting the timer.
  442. */
  443. struct ast_sip_sched_task *expiration_task;
  444. /*! The transport the subscription was received on.
  445. * Only used for reliable transports.
  446. */
  447. char transport_key[IP6ADDR_COLON_PORT_BUFLEN];
  448. /*! Indicator if initial notify should be generated.
  449. * Used to refresh modified RLS.
  450. */
  451. unsigned int generate_initial_notify;
  452. };
  453. /*!
  454. * \brief Structure representing a "virtual" SIP subscription.
  455. *
  456. * This structure serves a dual purpose. Structurally, it is
  457. * the constructed tree of subscriptions based on the resources
  458. * being subscribed to. API-wise, this serves as the handle that
  459. * subscription handlers use in order to interact with the pubsub API.
  460. */
  461. struct ast_sip_subscription {
  462. /*! Subscription datastores set up by handlers */
  463. struct ao2_container *datastores;
  464. /*! The handler for this subscription */
  465. const struct ast_sip_subscription_handler *handler;
  466. /*! Pointer to the base of the tree */
  467. struct sip_subscription_tree *tree;
  468. /*! Body generator for NOTIFYs */
  469. struct ast_sip_pubsub_body_generator *body_generator;
  470. /*! Vector of child subscriptions */
  471. AST_VECTOR(, struct ast_sip_subscription *) children;
  472. /*! Saved NOTIFY body text for this subscription */
  473. struct ast_str *body_text;
  474. /*! Indicator that the body text has changed since the last notification */
  475. int body_changed;
  476. /*! The current state of the subscription */
  477. pjsip_evsub_state subscription_state;
  478. /*! For lists, the current version to place in the RLMI body */
  479. unsigned int version;
  480. /*! For lists, indicates if full state should always be communicated. */
  481. unsigned int full_state;
  482. /*! URI associated with the subscription */
  483. pjsip_sip_uri *uri;
  484. /*! Data to be persisted with the subscription */
  485. struct ast_json *persistence_data;
  486. /*! Display Name of resource */
  487. char *display_name;
  488. /*! Name of resource being subscribed to */
  489. char resource[0];
  490. };
  491. /*!
  492. * \brief Structure representing a publication resource
  493. */
  494. struct ast_sip_publication_resource {
  495. /*! \brief Sorcery object details */
  496. SORCERY_OBJECT(details);
  497. /*! \brief Optional name of an endpoint that is only allowed to publish to this resource */
  498. char *endpoint;
  499. /*! \brief Mapping for event types to configuration */
  500. struct ast_variable *events;
  501. };
  502. static const char *sip_subscription_roles_map[] = {
  503. [AST_SIP_SUBSCRIBER] = "Subscriber",
  504. [AST_SIP_NOTIFIER] = "Notifier"
  505. };
  506. enum sip_persistence_update_type {
  507. /*! Called from send request */
  508. SUBSCRIPTION_PERSISTENCE_SEND_REQUEST = 0,
  509. /*! Subscription created from initial client request */
  510. SUBSCRIPTION_PERSISTENCE_CREATED,
  511. /*! Subscription recreated by asterisk on startup */
  512. SUBSCRIPTION_PERSISTENCE_RECREATED,
  513. /*! Subscription created from client refresh */
  514. SUBSCRIPTION_PERSISTENCE_REFRESHED,
  515. };
  516. AST_RWLIST_HEAD_STATIC(subscriptions, sip_subscription_tree);
  517. AST_RWLIST_HEAD_STATIC(body_generators, ast_sip_pubsub_body_generator);
  518. AST_RWLIST_HEAD_STATIC(body_supplements, ast_sip_pubsub_body_supplement);
  519. static pjsip_media_type rlmi_media_type;
  520. static void pubsub_on_evsub_state(pjsip_evsub *sub, pjsip_event *event);
  521. static void pubsub_on_rx_refresh(pjsip_evsub *sub, pjsip_rx_data *rdata,
  522. int *p_st_code, pj_str_t **p_st_text, pjsip_hdr *res_hdr, pjsip_msg_body **p_body);
  523. static void pubsub_on_rx_notify(pjsip_evsub *sub, pjsip_rx_data *rdata, int *p_st_code,
  524. pj_str_t **p_st_text, pjsip_hdr *res_hdr, pjsip_msg_body **p_body);
  525. static void pubsub_on_client_refresh(pjsip_evsub *sub);
  526. static void pubsub_on_server_timeout(pjsip_evsub *sub);
  527. static pjsip_evsub_user pubsub_cb = {
  528. .on_evsub_state = pubsub_on_evsub_state,
  529. .on_rx_refresh = pubsub_on_rx_refresh,
  530. .on_rx_notify = pubsub_on_rx_notify,
  531. .on_client_refresh = pubsub_on_client_refresh,
  532. .on_server_timeout = pubsub_on_server_timeout,
  533. };
  534. /*! \brief Destructor for publication resource */
  535. static void publication_resource_destroy(void *obj)
  536. {
  537. struct ast_sip_publication_resource *resource = obj;
  538. ast_free(resource->endpoint);
  539. ast_variables_destroy(resource->events);
  540. }
  541. /*! \brief Allocator for publication resource */
  542. static void *publication_resource_alloc(const char *name)
  543. {
  544. return ast_sorcery_generic_alloc(sizeof(struct ast_sip_publication_resource), publication_resource_destroy);
  545. }
  546. static int sub_tree_subscription_terminate_cb(void *data)
  547. {
  548. struct sip_subscription_tree *sub_tree = data;
  549. if (!sub_tree->evsub) {
  550. /* Something else already terminated the subscription. */
  551. ao2_ref(sub_tree, -1);
  552. return 0;
  553. }
  554. ast_debug(3, "Transport destroyed. Removing subscription '%s->%s' prune on boot: %d\n",
  555. sub_tree->persistence->endpoint, sub_tree->root->resource,
  556. sub_tree->persistence->prune_on_boot);
  557. sub_tree->state = SIP_SUB_TREE_TERMINATE_IN_PROGRESS;
  558. pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
  559. ao2_ref(sub_tree, -1);
  560. return 0;
  561. }
  562. /*!
  563. * \internal
  564. * \brief The reliable transport we used as a subscription contact has shutdown.
  565. *
  566. * \param data What subscription needs to be terminated.
  567. *
  568. * \note Normally executed by the pjsip monitor thread.
  569. */
  570. static void sub_tree_transport_cb(void *data)
  571. {
  572. struct sip_subscription_tree *sub_tree = data;
  573. /*
  574. * Push off the subscription termination to the serializer to
  575. * avoid deadlock. Another thread could be trying to send a
  576. * message on the subscription that can deadlock with this
  577. * thread.
  578. */
  579. ao2_ref(sub_tree, +1);
  580. if (ast_sip_push_task(sub_tree->serializer, sub_tree_subscription_terminate_cb,
  581. sub_tree)) {
  582. ao2_ref(sub_tree, -1);
  583. }
  584. }
  585. /*! \brief Destructor for subscription persistence */
  586. static void subscription_persistence_destroy(void *obj)
  587. {
  588. struct subscription_persistence *persistence = obj;
  589. ast_free(persistence->endpoint);
  590. ast_free(persistence->tag);
  591. ast_json_unref(persistence->generator_data);
  592. }
  593. /*! \brief Allocator for subscription persistence */
  594. static void *subscription_persistence_alloc(const char *name)
  595. {
  596. return ast_sorcery_generic_alloc(sizeof(struct subscription_persistence), subscription_persistence_destroy);
  597. }
  598. /*! \brief Function which creates initial persistence information of a subscription in sorcery */
  599. static struct subscription_persistence *subscription_persistence_create(struct sip_subscription_tree *sub_tree)
  600. {
  601. char tag[PJ_GUID_STRING_LENGTH + 1];
  602. /* The id of this persistence object doesn't matter as we keep it on the subscription and don't need to
  603. * look it up by id at all.
  604. */
  605. struct subscription_persistence *persistence = ast_sorcery_alloc(ast_sip_get_sorcery(),
  606. "subscription_persistence", NULL);
  607. pjsip_dialog *dlg = sub_tree->dlg;
  608. if (!persistence) {
  609. return NULL;
  610. }
  611. persistence->endpoint = ast_strdup(ast_sorcery_object_get_id(sub_tree->endpoint));
  612. ast_copy_pj_str(tag, &dlg->local.info->tag, sizeof(tag));
  613. persistence->tag = ast_strdup(tag);
  614. ast_sorcery_create(ast_sip_get_sorcery(), persistence);
  615. return persistence;
  616. }
  617. /*! \brief Function which updates persistence information of a subscription in sorcery */
  618. static void subscription_persistence_update(struct sip_subscription_tree *sub_tree,
  619. pjsip_rx_data *rdata, enum sip_persistence_update_type type)
  620. {
  621. pjsip_dialog *dlg;
  622. if (!sub_tree->persistence) {
  623. return;
  624. }
  625. ast_debug(3, "Updating persistence for '%s->%s' prune on boot: %s\n",
  626. sub_tree->persistence->endpoint, sub_tree->root->resource,
  627. sub_tree->persistence->prune_on_boot ? "yes" : "no");
  628. dlg = sub_tree->dlg;
  629. sub_tree->persistence->cseq = dlg->local.cseq;
  630. if (rdata) {
  631. unsigned int expires;
  632. pjsip_expires_hdr *expires_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL);
  633. pjsip_contact_hdr *contact_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, NULL);
  634. expires = expires_hdr ? expires_hdr->ivalue : DEFAULT_PUBLISH_EXPIRES;
  635. sub_tree->persistence->expires = ast_tvadd(ast_tvnow(), ast_samp2tv(expires, 1));
  636. if (contact_hdr) {
  637. if (contact_hdr) {
  638. if (type == SUBSCRIPTION_PERSISTENCE_CREATED) {
  639. sub_tree->persistence->prune_on_boot =
  640. !ast_sip_will_uri_survive_restart(
  641. (pjsip_sip_uri *)pjsip_uri_get_uri(contact_hdr->uri),
  642. sub_tree->endpoint, rdata);
  643. if (sub_tree->persistence->prune_on_boot) {
  644. ast_debug(3, "adding transport monitor on %s for '%s->%s' prune on boot: %d\n",
  645. rdata->tp_info.transport->obj_name,
  646. sub_tree->persistence->endpoint, sub_tree->root->resource,
  647. sub_tree->persistence->prune_on_boot);
  648. AST_SIP_MAKE_REMOTE_IPADDR_PORT_STR(rdata->tp_info.transport,
  649. sub_tree->transport_key);
  650. ast_sip_transport_monitor_register_key(sub_tree->transport_key,
  651. sub_tree_transport_cb, sub_tree);
  652. /*
  653. * FYI: ast_sip_transport_monitor_register holds a reference to the sub_tree
  654. */
  655. }
  656. }
  657. }
  658. pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, contact_hdr->uri,
  659. sub_tree->persistence->contact_uri, sizeof(sub_tree->persistence->contact_uri));
  660. } else {
  661. ast_log(LOG_WARNING, "Contact not updated due to missing contact header\n");
  662. }
  663. /* When receiving a packet on an streaming transport, it's possible to receive more than one SIP
  664. * message at a time into the rdata->pkt_info.packet buffer. However, the rdata->msg_info.msg_buf
  665. * will always point to the proper SIP message that is to be processed. When updating subscription
  666. * persistence that is pulled from persistent storage, though, the rdata->pkt_info.packet will
  667. * only ever have a single SIP message on it, and so we base persistence on that.
  668. */
  669. if (type == SUBSCRIPTION_PERSISTENCE_CREATED
  670. || type == SUBSCRIPTION_PERSISTENCE_RECREATED) {
  671. if (rdata->msg_info.msg_buf) {
  672. ast_copy_string(sub_tree->persistence->packet, rdata->msg_info.msg_buf,
  673. MIN(sizeof(sub_tree->persistence->packet), rdata->msg_info.len + 1));
  674. } else {
  675. ast_copy_string(sub_tree->persistence->packet, rdata->pkt_info.packet,
  676. sizeof(sub_tree->persistence->packet));
  677. }
  678. }
  679. ast_copy_string(sub_tree->persistence->src_name, rdata->pkt_info.src_name,
  680. sizeof(sub_tree->persistence->src_name));
  681. sub_tree->persistence->src_port = rdata->pkt_info.src_port;
  682. ast_copy_string(sub_tree->persistence->transport_type, rdata->tp_info.transport->type_name,
  683. sizeof(sub_tree->persistence->transport_type));
  684. ast_copy_pj_str(sub_tree->persistence->local_name, &rdata->tp_info.transport->local_name.host,
  685. sizeof(sub_tree->persistence->local_name));
  686. sub_tree->persistence->local_port = rdata->tp_info.transport->local_name.port;
  687. }
  688. ast_sorcery_update(ast_sip_get_sorcery(), sub_tree->persistence);
  689. }
  690. /*! \brief Function which removes persistence of a subscription from sorcery */
  691. static void subscription_persistence_remove(struct sip_subscription_tree *sub_tree)
  692. {
  693. if (!sub_tree->persistence) {
  694. return;
  695. }
  696. if (sub_tree->persistence->prune_on_boot && !ast_strlen_zero(sub_tree->transport_key)) {
  697. ast_debug(3, "Unregistering transport monitor on %s '%s->%s'\n",
  698. sub_tree->transport_key,
  699. sub_tree->endpoint ? ast_sorcery_object_get_id(sub_tree->endpoint) : "Unknown",
  700. sub_tree->root ? sub_tree->root->resource : "Unknown");
  701. ast_sip_transport_monitor_unregister_key(sub_tree->transport_key,
  702. sub_tree_transport_cb, sub_tree, NULL);
  703. }
  704. ast_sorcery_delete(ast_sip_get_sorcery(), sub_tree->persistence);
  705. ao2_ref(sub_tree->persistence, -1);
  706. sub_tree->persistence = NULL;
  707. }
  708. static struct ast_sip_subscription_handler *find_sub_handler_for_event_name(const char *event_name);
  709. static struct ast_sip_pubsub_body_generator *find_body_generator(char accept[AST_SIP_MAX_ACCEPT][64],
  710. size_t num_accept, const char *body_type);
  711. /*! \brief Retrieve a handler using the Event header of an rdata message */
  712. static struct ast_sip_subscription_handler *subscription_get_handler_from_rdata(pjsip_rx_data *rdata, const char *endpoint)
  713. {
  714. pjsip_event_hdr *event_header;
  715. char event[32];
  716. struct ast_sip_subscription_handler *handler;
  717. event_header = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_event_name, rdata->msg_info.msg->hdr.next);
  718. if (!event_header) {
  719. ast_log(LOG_WARNING, "Incoming SUBSCRIBE request from %s with no Event header\n",
  720. endpoint ? endpoint : "Unknown");
  721. return NULL;
  722. }
  723. ast_copy_pj_str(event, &event_header->event_type, sizeof(event));
  724. handler = find_sub_handler_for_event_name(event);
  725. if (!handler) {
  726. ast_log(LOG_WARNING, "No registered subscribe handler for event %s from %s\n", event,
  727. endpoint ? endpoint : "Unknown");
  728. }
  729. return handler;
  730. }
  731. /*!
  732. * \brief Accept headers that are exceptions to the rule
  733. *
  734. * Typically, when a SUBSCRIBE arrives, we attempt to find a
  735. * body generator that matches one of the Accept headers in
  736. * the request. When subscribing to a single resource, this works
  737. * great. However, when subscribing to a list, things work
  738. * differently. Most Accept header values are fine, but there
  739. * are a couple that are endemic to resource lists that need
  740. * to be ignored when searching for a body generator to use
  741. * for the individual resources of the subscription.
  742. */
  743. const char *accept_exceptions[] = {
  744. "multipart/related",
  745. "application/rlmi+xml",
  746. };
  747. /*!
  748. * \brief Is the Accept header from the SUBSCRIBE in the list of exceptions?
  749. *
  750. * \retval 1 This Accept header value is an exception to the rule.
  751. * \retval 0 This Accept header is not an exception to the rule.
  752. */
  753. static int exceptional_accept(const pj_str_t *accept)
  754. {
  755. int i;
  756. for (i = 0; i < ARRAY_LEN(accept_exceptions); ++i) {
  757. if (!pj_strcmp2(accept, accept_exceptions[i])) {
  758. return 1;
  759. }
  760. }
  761. return 0;
  762. }
  763. /*! \brief Retrieve a body generator using the Accept header of an rdata message */
  764. static struct ast_sip_pubsub_body_generator *subscription_get_generator_from_rdata(pjsip_rx_data *rdata,
  765. const struct ast_sip_subscription_handler *handler)
  766. {
  767. pjsip_accept_hdr *accept_header = (pjsip_accept_hdr *) &rdata->msg_info.msg->hdr;
  768. char accept[AST_SIP_MAX_ACCEPT][64];
  769. size_t num_accept_headers = 0;
  770. while ((accept_header = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_ACCEPT, accept_header->next)) &&
  771. (num_accept_headers < AST_SIP_MAX_ACCEPT)) {
  772. int i;
  773. for (i = 0; i < accept_header->count && num_accept_headers < AST_SIP_MAX_ACCEPT; ++i) {
  774. if (!exceptional_accept(&accept_header->values[i])) {
  775. ast_copy_pj_str(accept[num_accept_headers], &accept_header->values[i], sizeof(accept[num_accept_headers]));
  776. ++num_accept_headers;
  777. }
  778. }
  779. }
  780. if (num_accept_headers == 0) {
  781. /* If a SUBSCRIBE contains no Accept headers, then we must assume that
  782. * the default accept type for the event package is to be used.
  783. */
  784. ast_copy_string(accept[0], handler->notifier->default_accept, sizeof(accept[0]));
  785. num_accept_headers = 1;
  786. }
  787. return find_body_generator(accept, num_accept_headers, handler->body_type);
  788. }
  789. /*! \brief Check if the rdata has a Supported header containing 'eventlist'
  790. *
  791. * \retval 1 rdata has an eventlist containing supported header
  792. * \retval 0 rdata doesn't have an eventlist containing supported header
  793. */
  794. static int ast_sip_pubsub_has_eventlist_support(pjsip_rx_data *rdata)
  795. {
  796. pjsip_supported_hdr *supported_header = (pjsip_supported_hdr *) &rdata->msg_info.msg->hdr;
  797. while ((supported_header = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_SUPPORTED, supported_header->next))) {
  798. int i;
  799. for (i = 0; i < supported_header->count; i++) {
  800. if (!pj_stricmp2(&supported_header->values[i], "eventlist")) {
  801. return 1;
  802. }
  803. }
  804. }
  805. return 0;
  806. }
  807. struct resource_tree;
  808. /*!
  809. * \brief A node for a resource tree.
  810. */
  811. struct tree_node {
  812. AST_VECTOR(, struct tree_node *) children;
  813. unsigned int full_state;
  814. char *display_name;
  815. char resource[0];
  816. };
  817. /*!
  818. * \brief Helper function for retrieving a resource list for a given event.
  819. *
  820. * This will retrieve a resource list that corresponds to the resource and event provided.
  821. *
  822. * \param resource The name of the resource list to retrieve
  823. * \param event The expected event name on the resource list
  824. */
  825. static struct resource_list *retrieve_resource_list(const char *resource, const char *event)
  826. {
  827. struct resource_list *list;
  828. list = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "resource_list", resource);
  829. if (!list) {
  830. return NULL;
  831. }
  832. if (strcmp(list->event, event)) {
  833. ast_log(LOG_WARNING, "Found resource list %s, but its event type (%s) does not match SUBSCRIBE's (%s)\n",
  834. resource, list->event, event);
  835. ao2_cleanup(list);
  836. return NULL;
  837. }
  838. return list;
  839. }
  840. /*!
  841. * \brief Allocate a tree node
  842. *
  843. * In addition to allocating and initializing the tree node, the node is also added
  844. * to the vector of visited resources. See \ref build_resource_tree for more information
  845. * on the visited resources.
  846. *
  847. * \param resource The name of the resource for this tree node.
  848. * \param visited The vector of resources that have been visited.
  849. * \param full_state if allocating a list, indicate whether full state is requested in notifications.
  850. * \param display_name the display name to include with this tree node.
  851. *
  852. * \retval NULL Allocation failure.
  853. * \retval non-NULL The newly-allocated tree_node
  854. */
  855. static struct tree_node *tree_node_alloc(const char *resource, struct resources *visited, unsigned int full_state, const char *display_name)
  856. {
  857. struct tree_node *node;
  858. node = ast_calloc(1, sizeof(*node) + strlen(resource) + 1);
  859. if (!node) {
  860. return NULL;
  861. }
  862. strcpy(node->resource, resource);
  863. if (AST_VECTOR_INIT(&node->children, 4)) {
  864. ast_free(node);
  865. return NULL;
  866. }
  867. node->full_state = full_state;
  868. node->display_name = ast_strdup(display_name);
  869. if (visited) {
  870. AST_VECTOR_APPEND(visited, resource);
  871. }
  872. return node;
  873. }
  874. /*!
  875. * \brief Destructor for a tree node
  876. *
  877. * This function calls recursively in order to destroy
  878. * all nodes lower in the tree from the given node in
  879. * addition to the node itself.
  880. *
  881. * \param node The node to destroy.
  882. */
  883. static void tree_node_destroy(struct tree_node *node)
  884. {
  885. int i;
  886. if (!node) {
  887. return;
  888. }
  889. for (i = 0; i < AST_VECTOR_SIZE(&node->children); ++i) {
  890. tree_node_destroy(AST_VECTOR_GET(&node->children, i));
  891. }
  892. AST_VECTOR_FREE(&node->children);
  893. ast_free(node->display_name);
  894. ast_free(node);
  895. }
  896. /*!
  897. * \brief Determine if this resource has been visited already
  898. *
  899. * See \ref build_resource_tree for more information
  900. *
  901. * \param resource The resource currently being visited
  902. * \param visited The resources that have previously been visited
  903. */
  904. static int have_visited(const char *resource, struct resources *visited)
  905. {
  906. int i;
  907. for (i = 0; i < AST_VECTOR_SIZE(visited); ++i) {
  908. if (!strcmp(resource, AST_VECTOR_GET(visited, i))) {
  909. return 1;
  910. }
  911. }
  912. return 0;
  913. }
  914. #define NEW_SUBSCRIBE(notifier, endpoint, resource, rdata) notifier->new_subscribe_with_rdata ? notifier->new_subscribe_with_rdata(endpoint, resource, rdata) : notifier->new_subscribe(endpoint, resource)
  915. /*!
  916. * \brief Build child nodes for a given parent.
  917. *
  918. * This iterates through the items on a resource list and creates tree nodes for each one. The
  919. * tree nodes created are children of the supplied parent node. If an item in the resource
  920. * list is itself a list, then this function is called recursively to provide children for
  921. * the new node.
  922. *
  923. * If an item in a resource list is not a list, then the supplied subscription handler is
  924. * called into as if a new SUBSCRIBE for the list item were presented. The handler's response
  925. * is used to determine if the node can be added to the tree or not.
  926. *
  927. * If a parent node ends up having no child nodes added under it, then the parent node is
  928. * pruned from the tree.
  929. *
  930. * \param endpoint The endpoint that sent the inbound SUBSCRIBE.
  931. * \param handler The subscription handler for leaf nodes in the tree.
  932. * \param list The configured resource list from which the child node is being built.
  933. * \param parent The parent node for these children.
  934. * \param visited The resources that have already been visited.
  935. */
  936. static void build_node_children(struct ast_sip_endpoint *endpoint, const struct ast_sip_subscription_handler *handler,
  937. struct resource_list *list, struct tree_node *parent, struct resources *visited, pjsip_rx_data *rdata)
  938. {
  939. int i;
  940. for (i = 0; i < AST_VECTOR_SIZE(&list->items); ++i) {
  941. struct tree_node *current;
  942. struct resource_list *child_list;
  943. const char *resource = AST_VECTOR_GET(&list->items, i);
  944. if (have_visited(resource, visited)) {
  945. ast_debug(1, "Already visited resource %s. Avoiding duplicate resource or potential loop.\n", resource);
  946. continue;
  947. }
  948. child_list = retrieve_resource_list(resource, list->event);
  949. if (!child_list) {
  950. int resp = NEW_SUBSCRIBE(handler->notifier, endpoint, resource, rdata);
  951. if (PJSIP_IS_STATUS_IN_CLASS(resp, 200)) {
  952. char display_name[AST_MAX_EXTENSION] = "";
  953. if (list->resource_display_name && handler->notifier->get_resource_display_name) {
  954. handler->notifier->get_resource_display_name(endpoint, resource, display_name, sizeof(display_name));
  955. }
  956. current = tree_node_alloc(resource, visited, 0, ast_strlen_zero(display_name) ? NULL : display_name);
  957. if (!current) {
  958. ast_debug(1,
  959. "Subscription to leaf resource %s was successful, but encountered allocation error afterwards\n",
  960. resource);
  961. continue;
  962. }
  963. ast_debug(2, "Subscription to leaf resource %s resulted in success. Adding to parent %s\n",
  964. resource, parent->resource);
  965. if (AST_VECTOR_APPEND(&parent->children, current)) {
  966. tree_node_destroy(current);
  967. }
  968. } else {
  969. ast_debug(2, "Subscription to leaf resource %s resulted in error response %d\n",
  970. resource, resp);
  971. }
  972. } else {
  973. ast_debug(2, "Resource %s (child of %s) is a list\n", resource, parent->resource);
  974. current = tree_node_alloc(resource, visited, child_list->full_state, NULL);
  975. if (!current) {
  976. ast_debug(1, "Cannot build children of resource %s due to allocation failure\n", resource);
  977. continue;
  978. }
  979. build_node_children(endpoint, handler, child_list, current, visited, rdata);
  980. if (AST_VECTOR_SIZE(&current->children) > 0) {
  981. ast_debug(1, "List %s had no successful children.\n", resource);
  982. if (AST_VECTOR_APPEND(&parent->children, current)) {
  983. tree_node_destroy(current);
  984. }
  985. } else {
  986. ast_debug(2, "List %s had successful children. Adding to parent %s\n",
  987. resource, parent->resource);
  988. tree_node_destroy(current);
  989. }
  990. ao2_cleanup(child_list);
  991. }
  992. }
  993. }
  994. /*!
  995. * \brief A resource tree
  996. *
  997. * When an inbound SUBSCRIBE arrives, the resource being subscribed to may
  998. * be a resource list. If this is the case, the resource list may contain resources
  999. * that are themselves lists. The structure needed to hold the resources is
  1000. * a tree.
  1001. *
  1002. * Upon receipt of the SUBSCRIBE, the tree is built by determining if subscriptions
  1003. * to the individual resources in the tree would be successful or not. Any successful
  1004. * subscriptions result in a node in the tree being created. Any unsuccessful subscriptions
  1005. * result in no node being created.
  1006. *
  1007. * This tree can be seen as a bare-bones analog of the tree of ast_sip_subscriptions that
  1008. * will end up being created to actually carry out the duties of a SIP SUBSCRIBE dialog.
  1009. */
  1010. struct resource_tree {
  1011. struct tree_node *root;
  1012. unsigned int notification_batch_interval;
  1013. };
  1014. /*!
  1015. * \brief Destroy a resource tree.
  1016. *
  1017. * This function makes no assumptions about how the tree itself was
  1018. * allocated and does not attempt to free the tree itself. Callers
  1019. * of this function are responsible for freeing the tree.
  1020. *
  1021. * \param tree The tree to destroy.
  1022. */
  1023. static void resource_tree_destroy(struct resource_tree *tree)
  1024. {
  1025. if (tree) {
  1026. tree_node_destroy(tree->root);
  1027. }
  1028. }
  1029. /*!
  1030. * \brief Build a resource tree
  1031. *
  1032. * This function builds a resource tree based on the requested resource in a SUBSCRIBE request.
  1033. *
  1034. * This function also creates a container that has all resources that have been visited during
  1035. * creation of the tree, whether those resources resulted in a tree node being created or not.
  1036. * Keeping this container of visited resources allows for misconfigurations such as loops in
  1037. * the tree or duplicated resources to be detected.
  1038. *
  1039. * \param endpoint The endpoint that sent the SUBSCRIBE request.
  1040. * \param handler The subscription handler for leaf nodes in the tree.
  1041. * \param resource The resource requested in the SUBSCRIBE request.
  1042. * \param tree The tree that is to be built.
  1043. * \param has_eventlist_support
  1044. *
  1045. * \retval 200-299 Successfully subscribed to at least one resource.
  1046. * \retval 300-699 Failure to subscribe to requested resource.
  1047. */
  1048. static int build_resource_tree(struct ast_sip_endpoint *endpoint, const struct ast_sip_subscription_handler *handler,
  1049. const char *resource, struct resource_tree *tree, int has_eventlist_support, pjsip_rx_data *rdata)
  1050. {
  1051. RAII_VAR(struct resource_list *, list, NULL, ao2_cleanup);
  1052. struct resources visited;
  1053. int not_eventlist_but_needs_children = !strcmp(handler->body_type, AST_SIP_DEVICE_FEATURE_SYNC_DATA);
  1054. if ((!has_eventlist_support && !not_eventlist_but_needs_children) || !(list = retrieve_resource_list(resource, handler->event_name))) {
  1055. ast_debug(2, "Subscription '%s->%s' is not to a list\n",
  1056. ast_sorcery_object_get_id(endpoint), resource);
  1057. tree->root = tree_node_alloc(resource, NULL, 0, NULL);
  1058. if (!tree->root) {
  1059. return 500;
  1060. }
  1061. return NEW_SUBSCRIBE(handler->notifier, endpoint, resource, rdata);
  1062. }
  1063. ast_debug(2, "Subscription '%s->%s' is a list\n",
  1064. ast_sorcery_object_get_id(endpoint), resource);
  1065. if (AST_VECTOR_INIT(&visited, AST_VECTOR_SIZE(&list->items))) {
  1066. return 500;
  1067. }
  1068. tree->root = tree_node_alloc(resource, &visited, list->full_state, NULL);
  1069. if (!tree->root) {
  1070. AST_VECTOR_FREE(&visited);
  1071. return 500;
  1072. }
  1073. tree->notification_batch_interval = list->notification_batch_interval;
  1074. build_node_children(endpoint, handler, list, tree->root, &visited, rdata);
  1075. AST_VECTOR_FREE(&visited);
  1076. if (AST_VECTOR_SIZE(&tree->root->children) > 0) {
  1077. return 200;
  1078. } else {
  1079. return 500;
  1080. }
  1081. }
  1082. static void add_subscription(struct sip_subscription_tree *obj)
  1083. {
  1084. AST_RWLIST_WRLOCK(&subscriptions);
  1085. AST_RWLIST_INSERT_TAIL(&subscriptions, obj, next);
  1086. AST_RWLIST_UNLOCK(&subscriptions);
  1087. }
  1088. static void remove_subscription(struct sip_subscription_tree *obj)
  1089. {
  1090. struct sip_subscription_tree *i;
  1091. AST_RWLIST_WRLOCK(&subscriptions);
  1092. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&subscriptions, i, next) {
  1093. if (i == obj) {
  1094. AST_RWLIST_REMOVE_CURRENT(next);
  1095. if (i->root) {
  1096. ast_debug(2, "Removing subscription '%s->%s' from list of subscriptions\n",
  1097. ast_sorcery_object_get_id(i->endpoint), ast_sip_subscription_get_resource_name(i->root));
  1098. }
  1099. break;
  1100. }
  1101. }
  1102. AST_RWLIST_TRAVERSE_SAFE_END;
  1103. AST_RWLIST_UNLOCK(&subscriptions);
  1104. }
  1105. static void destroy_subscription(struct ast_sip_subscription *sub)
  1106. {
  1107. ast_debug(3, "Destroying SIP subscription from '%s->%s'\n",
  1108. sub->tree && sub->tree->endpoint ? ast_sorcery_object_get_id(sub->tree->endpoint) : "Unknown",
  1109. sub->resource);
  1110. ast_free(sub->body_text);
  1111. AST_VECTOR_FREE(&sub->children);
  1112. ao2_cleanup(sub->datastores);
  1113. ast_json_unref(sub->persistence_data);
  1114. ast_free(sub->display_name);
  1115. ast_free(sub);
  1116. }
  1117. static void destroy_subscriptions(struct ast_sip_subscription *root)
  1118. {
  1119. int i;
  1120. if (!root) {
  1121. return;
  1122. }
  1123. for (i = 0; i < AST_VECTOR_SIZE(&root->children); ++i) {
  1124. struct ast_sip_subscription *child;
  1125. child = AST_VECTOR_GET(&root->children, i);
  1126. destroy_subscriptions(child);
  1127. }
  1128. destroy_subscription(root);
  1129. }
  1130. static struct ast_sip_subscription *allocate_subscription(const struct ast_sip_subscription_handler *handler,
  1131. const char *resource, const char *display_name, struct sip_subscription_tree *tree)
  1132. {
  1133. struct ast_sip_subscription *sub;
  1134. pjsip_msg *msg;
  1135. pjsip_sip_uri *request_uri;
  1136. msg = ast_sip_mod_data_get(tree->dlg->mod_data, pubsub_module.id, MOD_DATA_MSG);
  1137. if (!msg) {
  1138. ast_log(LOG_ERROR, "No dialog message saved for SIP subscription. Cannot allocate subscription for resource %s\n", resource);
  1139. return NULL;
  1140. }
  1141. sub = ast_calloc(1, sizeof(*sub) + strlen(resource) + 1);
  1142. if (!sub) {
  1143. return NULL;
  1144. }
  1145. strcpy(sub->resource, resource); /* Safe */
  1146. sub->display_name = ast_strdup(display_name);
  1147. sub->datastores = ast_datastores_alloc();
  1148. if (!sub->datastores) {
  1149. destroy_subscription(sub);
  1150. return NULL;
  1151. }
  1152. sub->body_text = ast_str_create(128);
  1153. if (!sub->body_text) {
  1154. destroy_subscription(sub);
  1155. return NULL;
  1156. }
  1157. sub->uri = pjsip_sip_uri_create(tree->dlg->pool, PJ_FALSE);
  1158. request_uri = pjsip_uri_get_uri(msg->line.req.uri);
  1159. pjsip_sip_uri_assign(tree->dlg->pool, sub->uri, request_uri);
  1160. pj_strdup2(tree->dlg->pool, &sub->uri->user, resource);
  1161. /* If there is any persistence information available for this subscription that was persisted
  1162. * then make it available so that the NOTIFY has the correct state.
  1163. */
  1164. if (tree->persistence && tree->persistence->generator_data) {
  1165. sub->persistence_data = ast_json_ref(ast_json_object_get(tree->persistence->generator_data, resource));
  1166. }
  1167. sub->handler = handler;
  1168. sub->subscription_state = PJSIP_EVSUB_STATE_ACTIVE;
  1169. sub->tree = ao2_bump(tree);
  1170. return sub;
  1171. }
  1172. /*!
  1173. * \brief Create a tree of virtual subscriptions based on a resource tree node.
  1174. *
  1175. * \param handler The handler to supply to leaf subscriptions.
  1176. * \param resource The requested resource for this subscription.
  1177. * \param generator Body generator to use for leaf subscriptions.
  1178. * \param tree The root of the subscription tree.
  1179. * \param current The tree node that corresponds to the subscription being created.
  1180. */
  1181. static struct ast_sip_subscription *create_virtual_subscriptions(const struct ast_sip_subscription_handler *handler,
  1182. const char *resource, struct ast_sip_pubsub_body_generator *generator,
  1183. struct sip_subscription_tree *tree, struct tree_node *current)
  1184. {
  1185. int i;
  1186. struct ast_sip_subscription *sub;
  1187. sub = allocate_subscription(handler, resource, current->display_name, tree);
  1188. if (!sub) {
  1189. return NULL;
  1190. }
  1191. sub->full_state = current->full_state;
  1192. sub->body_generator = generator;
  1193. AST_VECTOR_INIT(&sub->children, AST_VECTOR_SIZE(&current->children));
  1194. for (i = 0; i < AST_VECTOR_SIZE(&current->children); ++i) {
  1195. struct ast_sip_subscription *child;
  1196. struct tree_node *child_node = AST_VECTOR_GET(&current->children, i);
  1197. child = create_virtual_subscriptions(handler, child_node->resource, generator,
  1198. tree, child_node);
  1199. if (!child) {
  1200. ast_debug(1, "Child subscription to resource %s could not be created\n",
  1201. child_node->resource);
  1202. continue;
  1203. }
  1204. if (AST_VECTOR_APPEND(&sub->children, child)) {
  1205. ast_debug(1, "Child subscription to resource %s could not be appended\n",
  1206. child_node->resource);
  1207. destroy_subscription(child);
  1208. /* Have to release tree here too because a ref was added
  1209. * to child that destroy_subscription() doesn't release. */
  1210. ao2_cleanup(tree);
  1211. }
  1212. }
  1213. return sub;
  1214. }
  1215. static void shutdown_subscriptions(struct ast_sip_subscription *sub)
  1216. {
  1217. int i;
  1218. if (!sub) {
  1219. return;
  1220. }
  1221. if (AST_VECTOR_SIZE(&sub->children) > 0) {
  1222. for (i = 0; i < AST_VECTOR_SIZE(&sub->children); ++i) {
  1223. shutdown_subscriptions(AST_VECTOR_GET(&sub->children, i));
  1224. }
  1225. return;
  1226. }
  1227. /* We notify subscription shutdown only on the tree leaves. */
  1228. if (sub->handler->subscription_shutdown) {
  1229. sub->handler->subscription_shutdown(sub);
  1230. }
  1231. }
  1232. static int subscription_unreference_dialog(void *obj)
  1233. {
  1234. struct sip_subscription_tree *sub_tree = obj;
  1235. /* This is why we keep the dialog on the subscription. When the subscription
  1236. * is destroyed, there is no guarantee that the underlying dialog is ready
  1237. * to be destroyed. Furthermore, there's no guarantee in the opposite direction
  1238. * either. The dialog could be destroyed before our subscription is. We fix
  1239. * this problem by keeping a reference to the dialog until it is time to
  1240. * destroy the subscription. We need to have the dialog available when the
  1241. * subscription is destroyed so that we can guarantee that our attempt to
  1242. * remove the serializer will be successful.
  1243. */
  1244. pjsip_dlg_dec_session(sub_tree->dlg, &pubsub_module);
  1245. sub_tree->dlg = NULL;
  1246. return 0;
  1247. }
  1248. static void subscription_tree_destructor(void *obj)
  1249. {
  1250. struct sip_subscription_tree *sub_tree = obj;
  1251. ast_debug(3, "Destroying subscription tree %p '%s->%s'\n",
  1252. sub_tree,
  1253. sub_tree->endpoint ? ast_sorcery_object_get_id(sub_tree->endpoint) : "Unknown",
  1254. sub_tree->root ? sub_tree->root->resource : "Unknown");
  1255. destroy_subscriptions(sub_tree->root);
  1256. if (sub_tree->dlg) {
  1257. ast_sip_push_task_wait_servant(sub_tree->serializer,
  1258. subscription_unreference_dialog, sub_tree);
  1259. }
  1260. ao2_cleanup(sub_tree->endpoint);
  1261. ast_taskprocessor_unreference(sub_tree->serializer);
  1262. ast_module_unref(ast_module_info->self);
  1263. }
  1264. void ast_sip_subscription_destroy(struct ast_sip_subscription *sub)
  1265. {
  1266. ast_debug(3, "Removing subscription %p '%s->%s' reference to subscription tree %p\n",
  1267. sub, ast_sorcery_object_get_id(sub->tree->endpoint), sub->resource, sub->tree);
  1268. ao2_cleanup(sub->tree);
  1269. }
  1270. static void subscription_setup_dialog(struct sip_subscription_tree *sub_tree, pjsip_dialog *dlg)
  1271. {
  1272. sub_tree->dlg = dlg;
  1273. ast_sip_dialog_set_serializer(dlg, sub_tree->serializer);
  1274. ast_sip_dialog_set_endpoint(dlg, sub_tree->endpoint);
  1275. pjsip_evsub_set_mod_data(sub_tree->evsub, pubsub_module.id, sub_tree);
  1276. pjsip_dlg_inc_session(dlg, &pubsub_module);
  1277. }
  1278. static struct sip_subscription_tree *allocate_subscription_tree(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata)
  1279. {
  1280. struct sip_subscription_tree *sub_tree;
  1281. sub_tree = ao2_alloc(sizeof *sub_tree, subscription_tree_destructor);
  1282. if (!sub_tree) {
  1283. return NULL;
  1284. }
  1285. ast_module_ref(ast_module_info->self);
  1286. if (rdata) {
  1287. /*
  1288. * We must continue using the serializer that the original
  1289. * SUBSCRIBE came in on for the dialog. There may be
  1290. * retransmissions already enqueued in the original
  1291. * serializer that can result in reentrancy and message
  1292. * sequencing problems.
  1293. */
  1294. sub_tree->serializer = ast_sip_get_distributor_serializer(rdata);
  1295. } else {
  1296. char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
  1297. /* Create name with seq number appended. */
  1298. ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/pubsub/%s",
  1299. ast_sorcery_object_get_id(endpoint));
  1300. sub_tree->serializer = ast_sip_create_serializer(tps_name);
  1301. }
  1302. if (!sub_tree->serializer) {
  1303. ao2_ref(sub_tree, -1);
  1304. return NULL;
  1305. }
  1306. sub_tree->endpoint = ao2_bump(endpoint);
  1307. sub_tree->notify_sched_id = -1;
  1308. return sub_tree;
  1309. }
  1310. /*!
  1311. * \brief Create a subscription tree based on a resource tree.
  1312. *
  1313. * Using the previously-determined valid resources in the provided resource tree,
  1314. * a corresponding tree of ast_sip_subscriptions are created. The root of the
  1315. * subscription tree is a real subscription, and the rest in the tree are
  1316. * virtual subscriptions.
  1317. *
  1318. * \param handler The handler to use for leaf subscriptions
  1319. * \param endpoint The endpoint that sent the SUBSCRIBE request
  1320. * \param rdata The SUBSCRIBE content
  1321. * \param resource The requested resource in the SUBSCRIBE request
  1322. * \param generator The body generator to use in leaf subscriptions
  1323. * \param tree The resource tree on which the subscription tree is based
  1324. * \param[out] dlg_status The result of attempting to create a dialog
  1325. * \param persistence
  1326. *
  1327. * \retval NULL Could not create the subscription tree
  1328. * \retval non-NULL The root of the created subscription tree
  1329. */
  1330. static struct sip_subscription_tree *create_subscription_tree(const struct ast_sip_subscription_handler *handler,
  1331. struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata, const char *resource,
  1332. struct ast_sip_pubsub_body_generator *generator, struct resource_tree *tree,
  1333. pj_status_t *dlg_status, struct subscription_persistence *persistence)
  1334. {
  1335. struct sip_subscription_tree *sub_tree;
  1336. pjsip_dialog *dlg;
  1337. sub_tree = allocate_subscription_tree(endpoint, rdata);
  1338. if (!sub_tree) {
  1339. *dlg_status = PJ_ENOMEM;
  1340. return NULL;
  1341. }
  1342. sub_tree->role = AST_SIP_NOTIFIER;
  1343. dlg = ast_sip_create_dialog_uas_locked(endpoint, rdata, dlg_status);
  1344. if (!dlg) {
  1345. if (*dlg_status != PJ_EEXISTS) {
  1346. ast_log(LOG_WARNING, "Unable to create dialog for SIP subscription\n");
  1347. }
  1348. ao2_ref(sub_tree, -1);
  1349. return NULL;
  1350. }
  1351. persistence = ast_sip_mod_data_get(rdata->endpt_info.mod_data,
  1352. pubsub_module.id, MOD_DATA_PERSISTENCE);
  1353. if (persistence) {
  1354. /* Update the created dialog with the persisted information */
  1355. pjsip_ua_unregister_dlg(pjsip_ua_instance(), dlg);
  1356. pj_strdup2(dlg->pool, &dlg->local.info->tag, persistence->tag);
  1357. dlg->local.tag_hval = pj_hash_calc_tolower(0, NULL, &dlg->local.info->tag);
  1358. pjsip_ua_register_dlg(pjsip_ua_instance(), dlg);
  1359. dlg->local.cseq = persistence->cseq;
  1360. }
  1361. pjsip_evsub_create_uas(dlg, &pubsub_cb, rdata, 0, &sub_tree->evsub);
  1362. subscription_setup_dialog(sub_tree, dlg);
  1363. /*
  1364. * The evsub and subscription setup both add dialog refs, so the dialog ref that
  1365. * was added when the dialog was created (see ast_sip_create_dialog_uas_lock) can
  1366. * now be removed. The lock should no longer be needed so can be removed too.
  1367. */
  1368. pjsip_dlg_dec_lock(dlg);
  1369. #ifdef HAVE_PJSIP_EVSUB_GRP_LOCK
  1370. pjsip_evsub_add_ref(sub_tree->evsub);
  1371. #endif
  1372. ast_sip_mod_data_set(dlg->pool, dlg->mod_data, pubsub_module.id, MOD_DATA_MSG,
  1373. pjsip_msg_clone(dlg->pool, rdata->msg_info.msg));
  1374. sub_tree->notification_batch_interval = tree->notification_batch_interval;
  1375. /* Persistence information needs to be available for all the subscriptions */
  1376. sub_tree->persistence = ao2_bump(persistence);
  1377. sub_tree->root = create_virtual_subscriptions(handler, resource, generator, sub_tree, tree->root);
  1378. if (AST_VECTOR_SIZE(&sub_tree->root->children) > 0) {
  1379. sub_tree->is_list = 1;
  1380. }
  1381. add_subscription(sub_tree);
  1382. return sub_tree;
  1383. }
  1384. /*! Wrapper structure for initial_notify_task */
  1385. struct initial_notify_data {
  1386. struct sip_subscription_tree *sub_tree;
  1387. unsigned int expires;
  1388. };
  1389. static int initial_notify_task(void *obj);
  1390. static int send_notify(struct sip_subscription_tree *sub_tree, unsigned int force_full_state);
  1391. /*! Persistent subscription recreation continuation under distributor serializer data */
  1392. struct persistence_recreate_data {
  1393. struct subscription_persistence *persistence;
  1394. pjsip_rx_data *rdata;
  1395. };
  1396. /*!
  1397. * \internal
  1398. * \brief subscription_persistence_recreate continuation under distributor serializer.
  1399. * \since 13.10.0
  1400. *
  1401. * \retval 0 on success.
  1402. * \retval -1 on error.
  1403. */
  1404. static int sub_persistence_recreate(void *obj)
  1405. {
  1406. struct persistence_recreate_data *recreate_data = obj;
  1407. struct subscription_persistence *persistence = recreate_data->persistence;
  1408. pjsip_rx_data *rdata = recreate_data->rdata;
  1409. struct ast_sip_endpoint *endpoint;
  1410. struct sip_subscription_tree *sub_tree;
  1411. struct ast_sip_pubsub_body_generator *generator;
  1412. struct ast_sip_subscription_handler *handler;
  1413. char *resource;
  1414. size_t resource_size;
  1415. int resp;
  1416. struct resource_tree tree;
  1417. pjsip_expires_hdr *expires_header;
  1418. int64_t expires;
  1419. const pj_str_t *user;
  1420. user = ast_sip_pjsip_uri_get_username(rdata->msg_info.msg->line.req.uri);
  1421. resource_size = pj_strlen(user) + 1;
  1422. resource = ast_alloca(resource_size);
  1423. ast_copy_pj_str(resource, user, resource_size);
  1424. /*
  1425. * We may want to match without any user options getting
  1426. * in the way.
  1427. */
  1428. AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(resource);
  1429. handler = subscription_get_handler_from_rdata(rdata, persistence->endpoint);
  1430. if (!handler || !handler->notifier) {
  1431. ast_log(LOG_WARNING, "Failed recreating '%s' subscription: Could not get subscription handler.\n",
  1432. persistence->endpoint);
  1433. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1434. return 0;
  1435. }
  1436. generator = subscription_get_generator_from_rdata(rdata, handler);
  1437. if (!generator) {
  1438. ast_log(LOG_WARNING, "Failed recreating '%s' subscription: Body generator not available.\n",
  1439. persistence->endpoint);
  1440. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1441. return 0;
  1442. }
  1443. ast_sip_mod_data_set(rdata->tp_info.pool, rdata->endpt_info.mod_data,
  1444. pubsub_module.id, MOD_DATA_PERSISTENCE, persistence);
  1445. /* Getting the endpoint may take some time that can affect the expiration. */
  1446. endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
  1447. persistence->endpoint);
  1448. if (!endpoint) {
  1449. ast_log(LOG_WARNING, "Failed recreating '%s' subscription: The endpoint was not found\n",
  1450. persistence->endpoint);
  1451. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1452. return 0;
  1453. }
  1454. /* Update the expiration header with the new expiration */
  1455. expires_header = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES,
  1456. rdata->msg_info.msg->hdr.next);
  1457. if (!expires_header) {
  1458. expires_header = pjsip_expires_hdr_create(rdata->tp_info.pool, 0);
  1459. if (!expires_header) {
  1460. ast_log(LOG_WARNING, "Failed recreating '%s' subscription: Could not update expires header.\n",
  1461. persistence->endpoint);
  1462. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1463. ao2_ref(endpoint, -1);
  1464. return 0;
  1465. }
  1466. pjsip_msg_add_hdr(rdata->msg_info.msg, (pjsip_hdr *) expires_header);
  1467. }
  1468. expires = (ast_tvdiff_ms(persistence->expires, ast_tvnow()) / 1000);
  1469. if (expires <= 0) {
  1470. /* The subscription expired since we started recreating the subscription. */
  1471. ast_debug(3, "Expired subscription retrived from persistent store '%s' %s\n",
  1472. persistence->endpoint, persistence->tag);
  1473. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1474. ao2_ref(endpoint, -1);
  1475. return 0;
  1476. }
  1477. expires_header->ivalue = expires;
  1478. memset(&tree, 0, sizeof(tree));
  1479. resp = build_resource_tree(endpoint, handler, resource, &tree,
  1480. ast_sip_pubsub_has_eventlist_support(rdata), rdata);
  1481. if (PJSIP_IS_STATUS_IN_CLASS(resp, 200)) {
  1482. pj_status_t dlg_status;
  1483. sub_tree = create_subscription_tree(handler, endpoint, rdata, resource, generator,
  1484. &tree, &dlg_status, persistence);
  1485. if (!sub_tree) {
  1486. if (dlg_status != PJ_EEXISTS) {
  1487. ast_log(LOG_WARNING, "Failed recreating '%s' subscription: Could not create subscription tree.\n",
  1488. persistence->endpoint);
  1489. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1490. }
  1491. } else {
  1492. struct initial_notify_data *ind = ast_malloc(sizeof(*ind));
  1493. if (!ind) {
  1494. pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
  1495. goto error;
  1496. }
  1497. ind->sub_tree = ao2_bump(sub_tree);
  1498. ind->expires = expires_header->ivalue;
  1499. subscription_persistence_update(sub_tree, rdata, SUBSCRIPTION_PERSISTENCE_RECREATED);
  1500. if (ast_sip_push_task(sub_tree->serializer, initial_notify_task, ind)) {
  1501. /* Could not send initial subscribe NOTIFY */
  1502. pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
  1503. ao2_ref(sub_tree, -1);
  1504. ast_free(ind);
  1505. }
  1506. }
  1507. } else {
  1508. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1509. }
  1510. error:
  1511. resource_tree_destroy(&tree);
  1512. ao2_ref(endpoint, -1);
  1513. return 0;
  1514. }
  1515. /*! \brief Callback function to perform the actual recreation of a subscription */
  1516. static int subscription_persistence_recreate(void *obj, void *arg, int flags)
  1517. {
  1518. struct subscription_persistence *persistence = obj;
  1519. pj_pool_t *pool = arg;
  1520. struct ast_taskprocessor *serializer;
  1521. pjsip_rx_data rdata;
  1522. struct persistence_recreate_data recreate_data;
  1523. /* If this subscription used a reliable transport it can't be reestablished so remove it */
  1524. if (persistence->prune_on_boot) {
  1525. ast_debug(3, "Deleting subscription marked as 'prune' from persistent store '%s' %s\n",
  1526. persistence->endpoint, persistence->tag);
  1527. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1528. return 0;
  1529. }
  1530. /* If this subscription has already expired remove it */
  1531. if (ast_tvdiff_ms(persistence->expires, ast_tvnow()) <= 0) {
  1532. ast_debug(3, "Expired subscription retrived from persistent store '%s' %s\n",
  1533. persistence->endpoint, persistence->tag);
  1534. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1535. return 0;
  1536. }
  1537. memset(&rdata, 0, sizeof(rdata));
  1538. pj_pool_reset(pool);
  1539. rdata.tp_info.pool = pool;
  1540. if (ast_sip_create_rdata_with_contact(&rdata, persistence->packet, persistence->src_name,
  1541. persistence->src_port, persistence->transport_type, persistence->local_name,
  1542. persistence->local_port, persistence->contact_uri)) {
  1543. ast_log(LOG_WARNING, "Failed recreating '%s' subscription: The message could not be parsed\n",
  1544. persistence->endpoint);
  1545. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1546. return 0;
  1547. }
  1548. if (rdata.msg_info.msg->type != PJSIP_REQUEST_MSG) {
  1549. ast_log(LOG_NOTICE, "Failed recreating '%s' subscription: Stored a SIP response instead of a request.\n",
  1550. persistence->endpoint);
  1551. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1552. return 0;
  1553. }
  1554. /* Continue the remainder in the distributor serializer */
  1555. serializer = ast_sip_get_distributor_serializer(&rdata);
  1556. if (!serializer) {
  1557. ast_log(LOG_WARNING, "Failed recreating '%s' subscription: Could not get distributor serializer.\n",
  1558. persistence->endpoint);
  1559. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1560. return 0;
  1561. }
  1562. recreate_data.persistence = persistence;
  1563. recreate_data.rdata = &rdata;
  1564. if (ast_sip_push_task_wait_serializer(serializer, sub_persistence_recreate,
  1565. &recreate_data)) {
  1566. ast_log(LOG_WARNING, "Failed recreating '%s' subscription: Could not continue under distributor serializer.\n",
  1567. persistence->endpoint);
  1568. ast_sorcery_delete(ast_sip_get_sorcery(), persistence);
  1569. }
  1570. ast_taskprocessor_unreference(serializer);
  1571. return 0;
  1572. }
  1573. /*! \brief Function which loads and recreates persisted subscriptions upon startup when the system is fully booted */
  1574. static int subscription_persistence_load(void *data)
  1575. {
  1576. struct ao2_container *persisted_subscriptions = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(),
  1577. "subscription_persistence", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  1578. pj_pool_t *pool;
  1579. pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "rtd%p", PJSIP_POOL_RDATA_LEN,
  1580. PJSIP_POOL_RDATA_INC);
  1581. if (!pool) {
  1582. ast_log(LOG_WARNING, "Could not create a memory pool for recreating SIP subscriptions\n");
  1583. return 0;
  1584. }
  1585. ao2_callback(persisted_subscriptions, OBJ_NODATA, subscription_persistence_recreate, pool);
  1586. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  1587. ao2_ref(persisted_subscriptions, -1);
  1588. return 0;
  1589. }
  1590. /*! \brief Event callback which fires subscription persistence recreation when the system is fully booted */
  1591. static void subscription_persistence_event_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
  1592. {
  1593. struct ast_json_payload *payload;
  1594. const char *type;
  1595. if (stasis_message_type(message) != ast_manager_get_generic_type()) {
  1596. return;
  1597. }
  1598. payload = stasis_message_data(message);
  1599. type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
  1600. /* This subscription only responds to the FullyBooted event so that all modules have been loaded when we
  1601. * recreate SIP subscriptions.
  1602. */
  1603. if (strcmp(type, "FullyBooted")) {
  1604. return;
  1605. }
  1606. /* This has to be here so the subscription is recreated when the body generator is available */
  1607. ast_sip_push_task(NULL, subscription_persistence_load, NULL);
  1608. /* Once the system is fully booted we don't care anymore */
  1609. stasis_unsubscribe(sub);
  1610. }
  1611. typedef int (*on_subscription_t)(struct sip_subscription_tree *sub, void *arg);
  1612. static int for_each_subscription(on_subscription_t on_subscription, void *arg)
  1613. {
  1614. int num = 0;
  1615. struct sip_subscription_tree *i;
  1616. if (!on_subscription) {
  1617. return num;
  1618. }
  1619. AST_RWLIST_RDLOCK(&subscriptions);
  1620. AST_RWLIST_TRAVERSE(&subscriptions, i, next) {
  1621. if (on_subscription(i, arg)) {
  1622. break;
  1623. }
  1624. ++num;
  1625. }
  1626. AST_RWLIST_UNLOCK(&subscriptions);
  1627. return num;
  1628. }
  1629. static void sip_subscription_to_ami(struct sip_subscription_tree *sub_tree,
  1630. struct ast_str **buf)
  1631. {
  1632. char str[256];
  1633. struct ast_sip_endpoint_id_configuration *id = &sub_tree->endpoint->id;
  1634. ast_str_append(buf, 0, "Role: %s\r\n",
  1635. sip_subscription_roles_map[sub_tree->role]);
  1636. ast_str_append(buf, 0, "Endpoint: %s\r\n",
  1637. ast_sorcery_object_get_id(sub_tree->endpoint));
  1638. if (sub_tree->dlg) {
  1639. ast_copy_pj_str(str, &sub_tree->dlg->call_id->id, sizeof(str));
  1640. } else {
  1641. ast_copy_string(str, "<unknown>", sizeof(str));
  1642. }
  1643. ast_str_append(buf, 0, "Callid: %s\r\n", str);
  1644. ast_str_append(buf, 0, "State: %s\r\n", pjsip_evsub_get_state_name(sub_tree->evsub));
  1645. ast_callerid_merge(str, sizeof(str),
  1646. S_COR(id->self.name.valid, id->self.name.str, NULL),
  1647. S_COR(id->self.number.valid, id->self.number.str, NULL),
  1648. "Unknown");
  1649. ast_str_append(buf, 0, "Callerid: %s\r\n", str);
  1650. /* XXX This needs to be done recursively for lists */
  1651. if (sub_tree->root->handler->to_ami) {
  1652. sub_tree->root->handler->to_ami(sub_tree->root, buf);
  1653. }
  1654. }
  1655. void *ast_sip_subscription_get_header(const struct ast_sip_subscription *sub, const char *header)
  1656. {
  1657. pjsip_dialog *dlg;
  1658. pjsip_msg *msg;
  1659. pj_str_t name;
  1660. dlg = sub->tree->dlg;
  1661. msg = ast_sip_mod_data_get(dlg->mod_data, pubsub_module.id, MOD_DATA_MSG);
  1662. pj_cstr(&name, header);
  1663. return pjsip_msg_find_hdr_by_name(msg, &name, NULL);
  1664. }
  1665. /* XXX This function is not used. */
  1666. struct ast_sip_subscription *ast_sip_create_subscription(const struct ast_sip_subscription_handler *handler,
  1667. struct ast_sip_endpoint *endpoint, const char *resource)
  1668. {
  1669. struct ast_sip_subscription *sub;
  1670. pjsip_dialog *dlg;
  1671. struct ast_sip_contact *contact;
  1672. pj_str_t event;
  1673. pjsip_tx_data *tdata;
  1674. pjsip_evsub *evsub;
  1675. struct sip_subscription_tree *sub_tree = NULL;
  1676. sub_tree = allocate_subscription_tree(endpoint, NULL);
  1677. if (!sub_tree) {
  1678. return NULL;
  1679. }
  1680. sub = allocate_subscription(handler, resource, NULL, sub_tree);
  1681. if (!sub) {
  1682. ao2_cleanup(sub_tree);
  1683. return NULL;
  1684. }
  1685. contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
  1686. if (!contact || ast_strlen_zero(contact->uri)) {
  1687. ast_log(LOG_WARNING, "No contacts configured for endpoint %s. Unable to create SIP subsription\n",
  1688. ast_sorcery_object_get_id(endpoint));
  1689. ao2_ref(sub_tree, -1);
  1690. ao2_cleanup(contact);
  1691. return NULL;
  1692. }
  1693. dlg = ast_sip_create_dialog_uac(endpoint, contact->uri, NULL);
  1694. ao2_cleanup(contact);
  1695. if (!dlg) {
  1696. ast_log(LOG_WARNING, "Unable to create dialog for SIP subscription\n");
  1697. ao2_ref(sub_tree, -1);
  1698. return NULL;
  1699. }
  1700. pj_cstr(&event, handler->event_name);
  1701. pjsip_evsub_create_uac(dlg, &pubsub_cb, &event, 0, &sub_tree->evsub);
  1702. subscription_setup_dialog(sub_tree, dlg);
  1703. evsub = sub_tree->evsub;
  1704. if (pjsip_evsub_initiate(evsub, NULL, -1, &tdata) == PJ_SUCCESS) {
  1705. pjsip_evsub_send_request(sub_tree->evsub, tdata);
  1706. } else {
  1707. /* pjsip_evsub_terminate will result in pubsub_on_evsub_state,
  1708. * being called and terminating the subscription. Therefore, we don't
  1709. * need to decrease the reference count of sub here.
  1710. */
  1711. pjsip_evsub_terminate(evsub, PJ_TRUE);
  1712. ao2_ref(sub_tree, -1);
  1713. return NULL;
  1714. }
  1715. add_subscription(sub_tree);
  1716. return sub;
  1717. }
  1718. pjsip_dialog *ast_sip_subscription_get_dialog(struct ast_sip_subscription *sub)
  1719. {
  1720. ast_assert(sub->tree->dlg != NULL);
  1721. return sub->tree->dlg;
  1722. }
  1723. struct ast_sip_endpoint *ast_sip_subscription_get_endpoint(struct ast_sip_subscription *sub)
  1724. {
  1725. ast_assert(sub->tree->endpoint != NULL);
  1726. return ao2_bump(sub->tree->endpoint);
  1727. }
  1728. struct ast_taskprocessor *ast_sip_subscription_get_serializer(struct ast_sip_subscription *sub)
  1729. {
  1730. ast_assert(sub->tree->serializer != NULL);
  1731. return sub->tree->serializer;
  1732. }
  1733. /*!
  1734. * \brief Pre-allocate a buffer for the transmission
  1735. *
  1736. * Typically, we let PJSIP do this step for us when we send a request. PJSIP's buffer
  1737. * allocation algorithm is to allocate a buffer of PJSIP_MAX_PKT_LEN bytes and attempt
  1738. * to write the packet to the allocated buffer. If the buffer is too small to hold the
  1739. * packet, then we get told the message is too long to be sent.
  1740. *
  1741. * When dealing with SIP NOTIFY, especially with RLS, it is possible to exceed
  1742. * PJSIP_MAX_PKT_LEN. Rather than accepting the limitation imposed on us by default,
  1743. * we instead take the strategy of pre-allocating the buffer, testing for ourselves
  1744. * if the message will fit, and resizing the buffer as required.
  1745. *
  1746. * The limit we impose is double that of the maximum packet length.
  1747. *
  1748. * \param tdata The tdata onto which to allocate a buffer
  1749. * \retval 0 Success
  1750. * \retval -1 The message is too large
  1751. */
  1752. static int allocate_tdata_buffer(pjsip_tx_data *tdata)
  1753. {
  1754. int buf_size;
  1755. int size = -1;
  1756. char *buf;
  1757. for (buf_size = PJSIP_MAX_PKT_LEN; size == -1 && buf_size < (PJSIP_MAX_PKT_LEN * 2); buf_size *= 2) {
  1758. buf = pj_pool_alloc(tdata->pool, buf_size);
  1759. size = pjsip_msg_print(tdata->msg, buf, buf_size);
  1760. }
  1761. if (size == -1) {
  1762. return -1;
  1763. }
  1764. tdata->buf.start = buf;
  1765. tdata->buf.cur = tdata->buf.start;
  1766. tdata->buf.end = tdata->buf.start + buf_size;
  1767. return 0;
  1768. }
  1769. static int sip_subscription_send_request(struct sip_subscription_tree *sub_tree, pjsip_tx_data *tdata)
  1770. {
  1771. #ifdef TEST_FRAMEWORK
  1772. struct ast_sip_endpoint *endpoint = sub_tree->endpoint;
  1773. pjsip_evsub *evsub = sub_tree->evsub;
  1774. #endif
  1775. int res;
  1776. if (allocate_tdata_buffer(tdata)) {
  1777. ast_log(LOG_ERROR, "SIP request %s is too large to send.\n", tdata->info);
  1778. pjsip_tx_data_dec_ref(tdata);
  1779. return -1;
  1780. }
  1781. res = pjsip_evsub_send_request(sub_tree->evsub, tdata);
  1782. subscription_persistence_update(sub_tree, NULL, SUBSCRIPTION_PERSISTENCE_SEND_REQUEST);
  1783. ast_test_suite_event_notify("SUBSCRIPTION_STATE_SET",
  1784. "StateText: %s\r\n"
  1785. "Endpoint: %s\r\n",
  1786. pjsip_evsub_get_state_name(evsub),
  1787. ast_sorcery_object_get_id(endpoint));
  1788. return (res == PJ_SUCCESS ? 0 : -1);
  1789. }
  1790. /*!
  1791. * \brief Add a resource XML element to an RLMI body
  1792. *
  1793. * Each resource element represents a subscribed resource in the list. This function currently
  1794. * will unconditionally add an instance element to each created resource element. Instance
  1795. * elements refer to later parts in the multipart body.
  1796. *
  1797. * \param pool PJLIB allocation pool
  1798. * \param rlmi
  1799. * \param cid Content-ID header of the resource
  1800. * \param resource_name Name of the resource
  1801. * \param resource_uri URI of the resource
  1802. * \param state State of the subscribed resource
  1803. */
  1804. static void add_rlmi_resource(pj_pool_t *pool, pj_xml_node *rlmi, const pjsip_generic_string_hdr *cid,
  1805. const char *resource_name, const pjsip_sip_uri *resource_uri, pjsip_evsub_state state)
  1806. {
  1807. static pj_str_t cid_name = { "cid", 3 };
  1808. pj_xml_node *resource;
  1809. pj_xml_node *name;
  1810. pj_xml_node *instance;
  1811. pj_xml_attr *cid_attr;
  1812. char id[6];
  1813. char uri[PJSIP_MAX_URL_SIZE];
  1814. char name_sanitized[PJSIP_MAX_URL_SIZE];
  1815. /* This creates a string representing the Content-ID without the enclosing < > */
  1816. const pj_str_t cid_stripped = {
  1817. .ptr = cid->hvalue.ptr + 1,
  1818. .slen = cid->hvalue.slen - 2,
  1819. };
  1820. resource = ast_sip_presence_xml_create_node(pool, rlmi, "resource");
  1821. name = ast_sip_presence_xml_create_node(pool, resource, "name");
  1822. instance = ast_sip_presence_xml_create_node(pool, resource, "instance");
  1823. pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, resource_uri, uri, sizeof(uri));
  1824. ast_sip_presence_xml_create_attr(pool, resource, "uri", uri);
  1825. ast_sip_sanitize_xml(resource_name, name_sanitized, sizeof(name_sanitized));
  1826. pj_strdup2(pool, &name->content, name_sanitized);
  1827. ast_generate_random_string(id, sizeof(id));
  1828. ast_sip_presence_xml_create_attr(pool, instance, "id", id);
  1829. ast_sip_presence_xml_create_attr(pool, instance, "state",
  1830. state == PJSIP_EVSUB_STATE_TERMINATED ? "terminated" : "active");
  1831. /* Use the PJLIB-util XML library directly here since we are using a
  1832. * pj_str_t
  1833. */
  1834. cid_attr = pj_xml_attr_new(pool, &cid_name, &cid_stripped);
  1835. pj_xml_add_attr(instance, cid_attr);
  1836. }
  1837. /*!
  1838. * \brief A multipart body part and meta-information
  1839. *
  1840. * When creating a multipart body part, the end result (the
  1841. * pjsip_multipart_part) is hard to inspect without undoing
  1842. * a lot of what was done to create it. Therefore, we use this
  1843. * structure to store meta-information about the body part.
  1844. *
  1845. * The main consumer of this is the creator of the RLMI body
  1846. * part of a multipart resource list body.
  1847. */
  1848. struct body_part {
  1849. /*! Content-ID header for the body part */
  1850. pjsip_generic_string_hdr *cid;
  1851. /*! Subscribed resource represented in the body part */
  1852. const char *resource;
  1853. /*! URI for the subscribed body part */
  1854. pjsip_sip_uri *uri;
  1855. /*! Subscription state of the resource represented in the body part */
  1856. pjsip_evsub_state state;
  1857. /*! The actual body part that will be present in the multipart body */
  1858. pjsip_multipart_part *part;
  1859. /*! Display name for the resource */
  1860. const char *display_name;
  1861. };
  1862. /*!
  1863. * \brief Type declaration for container of body part structures
  1864. */
  1865. AST_VECTOR(body_part_list, struct body_part *);
  1866. /*!
  1867. * \brief Create a Content-ID header
  1868. *
  1869. * Content-ID headers are required by RFC2387 for multipart/related
  1870. * bodies. They serve as identifiers for each part of the multipart body.
  1871. *
  1872. * \param pool PJLIB allocation pool
  1873. * \param sub Subscription to a resource
  1874. */
  1875. static pjsip_generic_string_hdr *generate_content_id_hdr(pj_pool_t *pool,
  1876. const struct ast_sip_subscription *sub)
  1877. {
  1878. static const pj_str_t cid_name = { "Content-ID", 10 };
  1879. pjsip_generic_string_hdr *cid;
  1880. char id[6];
  1881. size_t alloc_size;
  1882. pj_str_t cid_value;
  1883. /* '<' + '@' + '>' = 3. pj_str_t does not require a null-terminator */
  1884. alloc_size = sizeof(id) + pj_strlen(&sub->uri->host) + 3;
  1885. cid_value.ptr = pj_pool_alloc(pool, alloc_size);
  1886. cid_value.slen = sprintf(cid_value.ptr, "<%s@%.*s>",
  1887. ast_generate_random_string(id, sizeof(id)),
  1888. (int) pj_strlen(&sub->uri->host), pj_strbuf(&sub->uri->host));
  1889. cid = pjsip_generic_string_hdr_create(pool, &cid_name, &cid_value);
  1890. return cid;
  1891. }
  1892. static int rlmi_print_body(struct pjsip_msg_body *msg_body, char *buf, pj_size_t size)
  1893. {
  1894. int num_printed;
  1895. pj_xml_node *rlmi = msg_body->data;
  1896. num_printed = pj_xml_print(rlmi, buf, size, PJ_TRUE);
  1897. if (num_printed <= AST_PJSIP_XML_PROLOG_LEN) {
  1898. return -1;
  1899. }
  1900. return num_printed;
  1901. }
  1902. static void *rlmi_clone_data(pj_pool_t *pool, const void *data, unsigned len)
  1903. {
  1904. const pj_xml_node *rlmi = data;
  1905. return pj_xml_clone(pool, rlmi);
  1906. }
  1907. /*!
  1908. * \brief Create an RLMI body part for a multipart resource list body
  1909. *
  1910. * RLMI (Resource list meta information) is a special body type that lists
  1911. * the subscribed resources and tells subscribers the number of subscribed
  1912. * resources and what other body parts are in the multipart body. The
  1913. * RLMI body also has a version number that a subscriber can use to ensure
  1914. * that the locally-stored state corresponds to server state.
  1915. *
  1916. * \param pool The allocation pool
  1917. * \param sub The subscription representing the subscribed resource list
  1918. * \param body_parts A container of body parts that RLMI will refer to
  1919. * \param full_state Indicates whether this is a full or partial state notification
  1920. * \return The multipart part representing the RLMI body
  1921. */
  1922. static pjsip_multipart_part *build_rlmi_body(pj_pool_t *pool, struct ast_sip_subscription *sub,
  1923. struct body_part_list *body_parts, unsigned int full_state)
  1924. {
  1925. pj_xml_node *rlmi;
  1926. pj_xml_node *name;
  1927. pjsip_multipart_part *rlmi_part;
  1928. char version_str[32];
  1929. char uri[PJSIP_MAX_URL_SIZE];
  1930. pjsip_generic_string_hdr *cid;
  1931. int i;
  1932. rlmi = ast_sip_presence_xml_create_node(pool, NULL, "list");
  1933. ast_sip_presence_xml_create_attr(pool, rlmi, "xmlns", "urn:ietf:params:xml:ns:rlmi");
  1934. ast_sip_subscription_get_local_uri(sub, uri, sizeof(uri));
  1935. ast_sip_presence_xml_create_attr(pool, rlmi, "uri", uri);
  1936. snprintf(version_str, sizeof(version_str), "%u", sub->version++);
  1937. ast_sip_presence_xml_create_attr(pool, rlmi, "version", version_str);
  1938. ast_sip_presence_xml_create_attr(pool, rlmi, "fullState", full_state ? "true" : "false");
  1939. name = ast_sip_presence_xml_create_node(pool, rlmi, "name");
  1940. pj_strdup2(pool, &name->content, ast_sip_subscription_get_resource_name(sub));
  1941. for (i = 0; i < AST_VECTOR_SIZE(body_parts); ++i) {
  1942. const struct body_part *part = AST_VECTOR_GET(body_parts, i);
  1943. add_rlmi_resource(pool, rlmi, part->cid, S_OR(part->display_name, part->resource), part->uri, part->state);
  1944. }
  1945. rlmi_part = pjsip_multipart_create_part(pool);
  1946. rlmi_part->body = PJ_POOL_ZALLOC_T(pool, pjsip_msg_body);
  1947. pjsip_media_type_cp(pool, &rlmi_part->body->content_type, &rlmi_media_type);
  1948. rlmi_part->body->data = pj_xml_clone(pool, rlmi);
  1949. rlmi_part->body->clone_data = rlmi_clone_data;
  1950. rlmi_part->body->print_body = rlmi_print_body;
  1951. cid = generate_content_id_hdr(pool, sub);
  1952. pj_list_insert_before(&rlmi_part->hdr, cid);
  1953. return rlmi_part;
  1954. }
  1955. static pjsip_msg_body *generate_notify_body(pj_pool_t *pool, struct ast_sip_subscription *root,
  1956. unsigned int force_full_state);
  1957. /*!
  1958. * \brief Destroy a list of body parts
  1959. *
  1960. * \param parts The container of parts to destroy
  1961. */
  1962. static void free_body_parts(struct body_part_list *parts)
  1963. {
  1964. int i;
  1965. for (i = 0; i < AST_VECTOR_SIZE(parts); ++i) {
  1966. struct body_part *part = AST_VECTOR_GET(parts, i);
  1967. ast_free(part);
  1968. }
  1969. AST_VECTOR_FREE(parts);
  1970. }
  1971. /*!
  1972. * \brief Allocate and initialize a body part structure
  1973. *
  1974. * \param pool PJLIB allocation pool
  1975. * \param sub Subscription representing a subscribed resource
  1976. */
  1977. static struct body_part *allocate_body_part(pj_pool_t *pool, const struct ast_sip_subscription *sub)
  1978. {
  1979. struct body_part *bp;
  1980. bp = ast_calloc(1, sizeof(*bp));
  1981. if (!bp) {
  1982. return NULL;
  1983. }
  1984. bp->cid = generate_content_id_hdr(pool, sub);
  1985. bp->resource = sub->resource;
  1986. bp->state = sub->subscription_state;
  1987. bp->uri = sub->uri;
  1988. bp->display_name = sub->display_name;
  1989. return bp;
  1990. }
  1991. /*!
  1992. * \brief Create a multipart body part for a subscribed resource
  1993. *
  1994. * \param pool PJLIB allocation pool
  1995. * \param sub The subscription representing a subscribed resource
  1996. * \param parts A vector of parts to append the created part to.
  1997. * \param use_full_state Unused locally, but may be passed to other functions
  1998. */
  1999. static void build_body_part(pj_pool_t *pool, struct ast_sip_subscription *sub,
  2000. struct body_part_list *parts, unsigned int use_full_state)
  2001. {
  2002. struct body_part *bp;
  2003. pjsip_msg_body *body;
  2004. bp = allocate_body_part(pool, sub);
  2005. if (!bp) {
  2006. return;
  2007. }
  2008. body = generate_notify_body(pool, sub, use_full_state);
  2009. if (!body) {
  2010. /* Partial state was requested and the resource has not changed state */
  2011. ast_free(bp);
  2012. return;
  2013. }
  2014. bp->part = pjsip_multipart_create_part(pool);
  2015. bp->part->body = body;
  2016. pj_list_insert_before(&bp->part->hdr, bp->cid);
  2017. if (AST_VECTOR_APPEND(parts, bp)) {
  2018. ast_free(bp);
  2019. }
  2020. }
  2021. /*!
  2022. * \brief Create and initialize the PJSIP multipart body structure for a resource list subscription
  2023. *
  2024. * \param pool
  2025. * \return The multipart message body
  2026. */
  2027. static pjsip_msg_body *create_multipart_body(pj_pool_t *pool)
  2028. {
  2029. pjsip_media_type media_type;
  2030. pjsip_param *media_type_param;
  2031. char boundary[6];
  2032. pj_str_t pj_boundary;
  2033. pjsip_media_type_init2(&media_type, "multipart", "related");
  2034. media_type_param = pj_pool_alloc(pool, sizeof(*media_type_param));
  2035. pj_list_init(media_type_param);
  2036. pj_strdup2(pool, &media_type_param->name, "type");
  2037. pj_strdup2(pool, &media_type_param->value, "\"application/rlmi+xml\"");
  2038. pj_list_insert_before(&media_type.param, media_type_param);
  2039. pj_cstr(&pj_boundary, ast_generate_random_string(boundary, sizeof(boundary)));
  2040. return pjsip_multipart_create(pool, &media_type, &pj_boundary);
  2041. }
  2042. /*!
  2043. * \brief Create a resource list body for NOTIFY requests
  2044. *
  2045. * Resource list bodies are multipart/related bodies. The first part of the multipart body
  2046. * is an RLMI body that describes the rest of the parts to come. The other parts of the body
  2047. * convey state of individual subscribed resources.
  2048. *
  2049. * \param pool PJLIB allocation pool
  2050. * \param sub Subscription details from which to generate body
  2051. * \param force_full_state If true, ignore resource list settings and send a full state notification
  2052. * \return The generated multipart/related body
  2053. */
  2054. static pjsip_msg_body *generate_list_body(pj_pool_t *pool, struct ast_sip_subscription *sub,
  2055. unsigned int force_full_state)
  2056. {
  2057. int i;
  2058. pjsip_multipart_part *rlmi_part;
  2059. pjsip_msg_body *multipart;
  2060. struct body_part_list body_parts;
  2061. unsigned int use_full_state = force_full_state ? 1 : sub->full_state;
  2062. if (AST_VECTOR_INIT(&body_parts, AST_VECTOR_SIZE(&sub->children))) {
  2063. return NULL;
  2064. }
  2065. for (i = 0; i < AST_VECTOR_SIZE(&sub->children); ++i) {
  2066. build_body_part(pool, AST_VECTOR_GET(&sub->children, i), &body_parts, use_full_state);
  2067. }
  2068. /* This can happen if issuing partial state and no children of the list have changed state */
  2069. if (AST_VECTOR_SIZE(&body_parts) == 0) {
  2070. free_body_parts(&body_parts);
  2071. return NULL;
  2072. }
  2073. multipart = create_multipart_body(pool);
  2074. rlmi_part = build_rlmi_body(pool, sub, &body_parts, use_full_state);
  2075. if (!rlmi_part) {
  2076. free_body_parts(&body_parts);
  2077. return NULL;
  2078. }
  2079. pjsip_multipart_add_part(pool, multipart, rlmi_part);
  2080. for (i = 0; i < AST_VECTOR_SIZE(&body_parts); ++i) {
  2081. pjsip_multipart_add_part(pool, multipart, AST_VECTOR_GET(&body_parts, i)->part);
  2082. }
  2083. free_body_parts(&body_parts);
  2084. return multipart;
  2085. }
  2086. /*!
  2087. * \brief Create the body for a NOTIFY request.
  2088. *
  2089. * \param pool The pool used for allocations
  2090. * \param root The root of the subscription tree
  2091. * \param force_full_state If true, ignore resource list settings and send a full state notification
  2092. */
  2093. static pjsip_msg_body *generate_notify_body(pj_pool_t *pool, struct ast_sip_subscription *root,
  2094. unsigned int force_full_state)
  2095. {
  2096. pjsip_msg_body *body;
  2097. if (AST_VECTOR_SIZE(&root->children) == 0) {
  2098. if (force_full_state || root->body_changed) {
  2099. /* Not a list. We've already generated the body and saved it on the subscription.
  2100. * Use that directly.
  2101. */
  2102. pj_str_t type;
  2103. pj_str_t subtype;
  2104. pj_str_t text;
  2105. pj_cstr(&type, ast_sip_subscription_get_body_type(root));
  2106. pj_cstr(&subtype, ast_sip_subscription_get_body_subtype(root));
  2107. pj_cstr(&text, ast_str_buffer(root->body_text));
  2108. body = pjsip_msg_body_create(pool, &type, &subtype, &text);
  2109. root->body_changed = 0;
  2110. } else {
  2111. body = NULL;
  2112. }
  2113. } else {
  2114. body = generate_list_body(pool, root, force_full_state);
  2115. }
  2116. return body;
  2117. }
  2118. /*!
  2119. * \brief Shortcut method to create a Require: eventlist header
  2120. */
  2121. static pjsip_require_hdr *create_require_eventlist(pj_pool_t *pool)
  2122. {
  2123. pjsip_require_hdr *require;
  2124. require = pjsip_require_hdr_create(pool);
  2125. pj_strdup2(pool, &require->values[0], "eventlist");
  2126. require->count = 1;
  2127. return require;
  2128. }
  2129. static void set_state_terminated(struct ast_sip_subscription *sub)
  2130. {
  2131. int i;
  2132. sub->subscription_state = PJSIP_EVSUB_STATE_TERMINATED;
  2133. for (i = 0; i < AST_VECTOR_SIZE(&sub->children); ++i) {
  2134. set_state_terminated(AST_VECTOR_GET(&sub->children, i));
  2135. }
  2136. }
  2137. /*!
  2138. * \brief Send a NOTIFY request to a subscriber
  2139. *
  2140. * \pre sub_tree->dlg is locked
  2141. *
  2142. * \param sub_tree The subscription tree representing the subscription
  2143. * \param force_full_state If true, ignore resource list settings and send full resource list state.
  2144. * \retval 0 Success
  2145. * \retval non-zero Failure
  2146. */
  2147. static int send_notify(struct sip_subscription_tree *sub_tree, unsigned int force_full_state)
  2148. {
  2149. pjsip_evsub *evsub = sub_tree->evsub;
  2150. pjsip_tx_data *tdata;
  2151. if (ast_shutdown_final()
  2152. && sub_tree->root->subscription_state == PJSIP_EVSUB_STATE_TERMINATED
  2153. && sub_tree->persistence) {
  2154. return 0;
  2155. }
  2156. if (pjsip_evsub_notify(evsub, sub_tree->root->subscription_state,
  2157. NULL, NULL, &tdata) != PJ_SUCCESS) {
  2158. return -1;
  2159. }
  2160. tdata->msg->body = generate_notify_body(tdata->pool, sub_tree->root, force_full_state);
  2161. if (!tdata->msg->body) {
  2162. pjsip_tx_data_dec_ref(tdata);
  2163. return -1;
  2164. }
  2165. if (sub_tree->is_list) {
  2166. pjsip_require_hdr *require = create_require_eventlist(tdata->pool);
  2167. pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *) require);
  2168. }
  2169. if (sub_tree->root->handler->notifier->notify_created) {
  2170. /* The module for this event wants a callback to the pjsip_tx_data,
  2171. * e.g. so it can add custom headers or do something custom to the response. */
  2172. sub_tree->root->handler->notifier->notify_created(sub_tree->root, tdata);
  2173. }
  2174. if (sip_subscription_send_request(sub_tree, tdata)) {
  2175. /* do not call pjsip_tx_data_dec_ref(tdata). The pjsip_dlg_send_request deletes the message on error */
  2176. return -1;
  2177. }
  2178. sub_tree->send_scheduled_notify = 0;
  2179. return 0;
  2180. }
  2181. static int serialized_send_notify(void *userdata)
  2182. {
  2183. struct sip_subscription_tree *sub_tree = userdata;
  2184. pjsip_dialog *dlg = sub_tree->dlg;
  2185. pjsip_dlg_inc_lock(dlg);
  2186. sub_tree->notify_sched_id = -1;
  2187. /* It's possible that between when the notification was scheduled
  2188. * and now a new SUBSCRIBE arrived requiring full state to be
  2189. * sent out in an immediate NOTIFY. It's also possible that we're
  2190. * already processing a terminate. If that has happened, we need to
  2191. * bail out here instead of sending the batched NOTIFY.
  2192. */
  2193. if (sub_tree->state >= SIP_SUB_TREE_TERMINATE_IN_PROGRESS
  2194. || !sub_tree->send_scheduled_notify) {
  2195. pjsip_dlg_dec_lock(dlg);
  2196. ao2_cleanup(sub_tree);
  2197. return 0;
  2198. }
  2199. if (sub_tree->root->subscription_state == PJSIP_EVSUB_STATE_TERMINATED) {
  2200. sub_tree->state = SIP_SUB_TREE_TERMINATE_IN_PROGRESS;
  2201. }
  2202. send_notify(sub_tree, 0);
  2203. ast_test_suite_event_notify(
  2204. sub_tree->state == SIP_SUB_TREE_TERMINATED
  2205. ? "SUBSCRIPTION_TERMINATED" : "SUBSCRIPTION_STATE_CHANGED",
  2206. "Resource: %s", sub_tree->root->resource);
  2207. pjsip_dlg_dec_lock(dlg);
  2208. ao2_cleanup(sub_tree);
  2209. return 0;
  2210. }
  2211. static int sched_cb(const void *data)
  2212. {
  2213. struct sip_subscription_tree *sub_tree = (struct sip_subscription_tree *) data;
  2214. /* We don't need to bump the refcount of sub_tree since we bumped it when scheduling this task */
  2215. if (ast_sip_push_task(sub_tree->serializer, serialized_send_notify, sub_tree)) {
  2216. ao2_cleanup(sub_tree);
  2217. }
  2218. return 0;
  2219. }
  2220. static int schedule_notification(struct sip_subscription_tree *sub_tree)
  2221. {
  2222. /* There's already a notification scheduled */
  2223. if (sub_tree->notify_sched_id > -1) {
  2224. return 0;
  2225. }
  2226. sub_tree->send_scheduled_notify = 1;
  2227. sub_tree->notify_sched_id = ast_sched_add(sched, sub_tree->notification_batch_interval, sched_cb, ao2_bump(sub_tree));
  2228. if (sub_tree->notify_sched_id < 0) {
  2229. ao2_cleanup(sub_tree);
  2230. return -1;
  2231. }
  2232. return 0;
  2233. }
  2234. int ast_sip_subscription_notify(struct ast_sip_subscription *sub, struct ast_sip_body_data *notify_data,
  2235. int terminate)
  2236. {
  2237. int res;
  2238. pjsip_dialog *dlg = sub->tree->dlg;
  2239. pjsip_dlg_inc_lock(dlg);
  2240. if (sub->tree->state != SIP_SUB_TREE_NORMAL) {
  2241. pjsip_dlg_dec_lock(dlg);
  2242. return 0;
  2243. }
  2244. if (ast_sip_pubsub_generate_body_content(ast_sip_subscription_get_body_type(sub),
  2245. ast_sip_subscription_get_body_subtype(sub), notify_data, &sub->body_text)) {
  2246. pjsip_dlg_dec_lock(dlg);
  2247. return -1;
  2248. }
  2249. sub->body_changed = 1;
  2250. if (terminate) {
  2251. sub->subscription_state = PJSIP_EVSUB_STATE_TERMINATED;
  2252. sub->tree->state = SIP_SUB_TREE_TERMINATE_PENDING;
  2253. }
  2254. if (sub->tree->notification_batch_interval) {
  2255. res = schedule_notification(sub->tree);
  2256. } else {
  2257. /* See the note in pubsub_on_rx_refresh() for why sub->tree is refbumped here */
  2258. ao2_ref(sub->tree, +1);
  2259. if (terminate) {
  2260. sub->tree->state = SIP_SUB_TREE_TERMINATE_IN_PROGRESS;
  2261. }
  2262. res = send_notify(sub->tree, 0);
  2263. ast_test_suite_event_notify(terminate ? "SUBSCRIPTION_TERMINATED" : "SUBSCRIPTION_STATE_CHANGED",
  2264. "Resource: %s",
  2265. sub->tree->root->resource);
  2266. ao2_ref(sub->tree, -1);
  2267. }
  2268. pjsip_dlg_dec_lock(dlg);
  2269. return res;
  2270. }
  2271. pjsip_sip_uri *ast_sip_subscription_get_sip_uri(struct ast_sip_subscription *sub)
  2272. {
  2273. return sub->uri;
  2274. }
  2275. void ast_sip_subscription_get_local_uri(struct ast_sip_subscription *sub, char *buf, size_t size)
  2276. {
  2277. pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, sub->uri, buf, size);
  2278. }
  2279. void ast_sip_subscription_get_remote_uri(struct ast_sip_subscription *sub, char *buf, size_t size)
  2280. {
  2281. pjsip_dialog *dlg;
  2282. pjsip_sip_uri *uri;
  2283. dlg = sub->tree->dlg;
  2284. uri = pjsip_uri_get_uri(dlg->remote.info->uri);
  2285. if (pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, uri, buf, size) < 0) {
  2286. *buf = '\0';
  2287. }
  2288. }
  2289. const char *ast_sip_subscription_get_resource_name(struct ast_sip_subscription *sub)
  2290. {
  2291. return sub->resource;
  2292. }
  2293. int ast_sip_subscription_is_terminated(const struct ast_sip_subscription *sub)
  2294. {
  2295. return sub->subscription_state == PJSIP_EVSUB_STATE_TERMINATED ? 1 : 0;
  2296. }
  2297. static int sip_subscription_accept(struct sip_subscription_tree *sub_tree, pjsip_rx_data *rdata, int response)
  2298. {
  2299. pjsip_hdr res_hdr;
  2300. /* If this is a persistence recreation the subscription has already been accepted */
  2301. if (ast_sip_mod_data_get(rdata->endpt_info.mod_data, pubsub_module.id, MOD_DATA_PERSISTENCE)) {
  2302. return 0;
  2303. }
  2304. pj_list_init(&res_hdr);
  2305. if (sub_tree->is_list) {
  2306. /* If subscribing to a list, our response has to have a Require: eventlist header in it */
  2307. pj_list_insert_before(&res_hdr, create_require_eventlist(rdata->tp_info.pool));
  2308. }
  2309. return pjsip_evsub_accept(sub_tree->evsub, rdata, response, &res_hdr) == PJ_SUCCESS ? 0 : -1;
  2310. }
  2311. struct ast_datastore *ast_sip_subscription_alloc_datastore(const struct ast_datastore_info *info, const char *uid)
  2312. {
  2313. return ast_datastores_alloc_datastore(info, uid);
  2314. }
  2315. int ast_sip_subscription_add_datastore(struct ast_sip_subscription *subscription, struct ast_datastore *datastore)
  2316. {
  2317. return ast_datastores_add(subscription->datastores, datastore);
  2318. }
  2319. struct ast_datastore *ast_sip_subscription_get_datastore(struct ast_sip_subscription *subscription, const char *name)
  2320. {
  2321. return ast_datastores_find(subscription->datastores, name);
  2322. }
  2323. void ast_sip_subscription_remove_datastore(struct ast_sip_subscription *subscription, const char *name)
  2324. {
  2325. ast_datastores_remove(subscription->datastores, name);
  2326. }
  2327. struct ao2_container *ast_sip_subscription_get_datastores(const struct ast_sip_subscription *subscription)
  2328. {
  2329. return subscription->datastores;
  2330. }
  2331. int ast_sip_publication_add_datastore(struct ast_sip_publication *publication, struct ast_datastore *datastore)
  2332. {
  2333. return ast_datastores_add(publication->datastores, datastore);
  2334. }
  2335. struct ast_datastore *ast_sip_publication_get_datastore(struct ast_sip_publication *publication, const char *name)
  2336. {
  2337. return ast_datastores_find(publication->datastores, name);
  2338. }
  2339. void ast_sip_publication_remove_datastore(struct ast_sip_publication *publication, const char *name)
  2340. {
  2341. ast_datastores_remove(publication->datastores, name);
  2342. }
  2343. struct ao2_container *ast_sip_publication_get_datastores(const struct ast_sip_publication *publication)
  2344. {
  2345. return publication->datastores;
  2346. }
  2347. void ast_sip_subscription_set_persistence_data(struct ast_sip_subscription *subscription, struct ast_json *persistence_data)
  2348. {
  2349. ast_json_unref(subscription->persistence_data);
  2350. subscription->persistence_data = persistence_data;
  2351. if (subscription->tree->persistence) {
  2352. if (!subscription->tree->persistence->generator_data) {
  2353. subscription->tree->persistence->generator_data = ast_json_object_create();
  2354. if (!subscription->tree->persistence->generator_data) {
  2355. return;
  2356. }
  2357. }
  2358. ast_json_object_set(subscription->tree->persistence->generator_data, subscription->resource,
  2359. ast_json_ref(persistence_data));
  2360. }
  2361. }
  2362. const struct ast_json *ast_sip_subscription_get_persistence_data(const struct ast_sip_subscription *subscription)
  2363. {
  2364. return subscription->persistence_data;
  2365. }
  2366. AST_RWLIST_HEAD_STATIC(publish_handlers, ast_sip_publish_handler);
  2367. static int publication_hash_fn(const void *obj, const int flags)
  2368. {
  2369. const struct ast_sip_publication *publication = obj;
  2370. const int *entity_tag = obj;
  2371. return flags & OBJ_KEY ? *entity_tag : publication->entity_tag;
  2372. }
  2373. static int publication_cmp_fn(void *obj, void *arg, int flags)
  2374. {
  2375. const struct ast_sip_publication *publication1 = obj;
  2376. const struct ast_sip_publication *publication2 = arg;
  2377. const int *entity_tag = arg;
  2378. return (publication1->entity_tag == (flags & OBJ_KEY ? *entity_tag : publication2->entity_tag) ?
  2379. CMP_MATCH | CMP_STOP : 0);
  2380. }
  2381. static void publish_add_handler(struct ast_sip_publish_handler *handler)
  2382. {
  2383. AST_RWLIST_WRLOCK(&publish_handlers);
  2384. AST_RWLIST_INSERT_TAIL(&publish_handlers, handler, next);
  2385. AST_RWLIST_UNLOCK(&publish_handlers);
  2386. }
  2387. int ast_sip_register_publish_handler(struct ast_sip_publish_handler *handler)
  2388. {
  2389. if (ast_strlen_zero(handler->event_name)) {
  2390. ast_log(LOG_ERROR, "No event package specified for publish handler. Cannot register\n");
  2391. return -1;
  2392. }
  2393. handler->publications = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
  2394. PUBLICATIONS_BUCKETS, publication_hash_fn, NULL, publication_cmp_fn);
  2395. if (!handler->publications) {
  2396. ast_log(LOG_ERROR, "Could not allocate publications container for event '%s'\n",
  2397. handler->event_name);
  2398. return -1;
  2399. }
  2400. publish_add_handler(handler);
  2401. return 0;
  2402. }
  2403. void ast_sip_unregister_publish_handler(struct ast_sip_publish_handler *handler)
  2404. {
  2405. struct ast_sip_publish_handler *iter;
  2406. AST_RWLIST_WRLOCK(&publish_handlers);
  2407. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&publish_handlers, iter, next) {
  2408. if (handler == iter) {
  2409. AST_RWLIST_REMOVE_CURRENT(next);
  2410. ao2_cleanup(handler->publications);
  2411. break;
  2412. }
  2413. }
  2414. AST_RWLIST_TRAVERSE_SAFE_END;
  2415. AST_RWLIST_UNLOCK(&publish_handlers);
  2416. }
  2417. AST_RWLIST_HEAD_STATIC(subscription_handlers, ast_sip_subscription_handler);
  2418. static void sub_add_handler(struct ast_sip_subscription_handler *handler)
  2419. {
  2420. AST_RWLIST_WRLOCK(&subscription_handlers);
  2421. AST_RWLIST_INSERT_TAIL(&subscription_handlers, handler, next);
  2422. AST_RWLIST_UNLOCK(&subscription_handlers);
  2423. }
  2424. static struct ast_sip_subscription_handler *find_sub_handler_for_event_name(const char *event_name)
  2425. {
  2426. struct ast_sip_subscription_handler *iter;
  2427. AST_RWLIST_RDLOCK(&subscription_handlers);
  2428. AST_RWLIST_TRAVERSE(&subscription_handlers, iter, next) {
  2429. if (!strcmp(iter->event_name, event_name)) {
  2430. break;
  2431. }
  2432. }
  2433. AST_RWLIST_UNLOCK(&subscription_handlers);
  2434. return iter;
  2435. }
  2436. int ast_sip_register_subscription_handler(struct ast_sip_subscription_handler *handler)
  2437. {
  2438. pj_str_t event;
  2439. pj_str_t accept[AST_SIP_MAX_ACCEPT] = { {0, }, };
  2440. struct ast_sip_subscription_handler *existing;
  2441. int i = 0;
  2442. if (ast_strlen_zero(handler->event_name)) {
  2443. ast_log(LOG_ERROR, "No event package specified for subscription handler. Cannot register\n");
  2444. return -1;
  2445. }
  2446. existing = find_sub_handler_for_event_name(handler->event_name);
  2447. if (existing) {
  2448. ast_log(LOG_ERROR,
  2449. "Unable to register subscription handler for event %s. A handler is already registered\n",
  2450. handler->event_name);
  2451. return -1;
  2452. }
  2453. for (i = 0; i < AST_SIP_MAX_ACCEPT && !ast_strlen_zero(handler->accept[i]); ++i) {
  2454. pj_cstr(&accept[i], handler->accept[i]);
  2455. }
  2456. pj_cstr(&event, handler->event_name);
  2457. pjsip_evsub_register_pkg(&pubsub_module, &event, DEFAULT_EXPIRES, i, accept);
  2458. sub_add_handler(handler);
  2459. return 0;
  2460. }
  2461. void ast_sip_unregister_subscription_handler(struct ast_sip_subscription_handler *handler)
  2462. {
  2463. struct ast_sip_subscription_handler *iter;
  2464. AST_RWLIST_WRLOCK(&subscription_handlers);
  2465. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&subscription_handlers, iter, next) {
  2466. if (handler == iter) {
  2467. AST_RWLIST_REMOVE_CURRENT(next);
  2468. break;
  2469. }
  2470. }
  2471. AST_RWLIST_TRAVERSE_SAFE_END;
  2472. AST_RWLIST_UNLOCK(&subscription_handlers);
  2473. }
  2474. static struct ast_sip_pubsub_body_generator *find_body_generator_type_subtype_nolock(const char *type, const char *subtype)
  2475. {
  2476. struct ast_sip_pubsub_body_generator *gen;
  2477. AST_LIST_TRAVERSE(&body_generators, gen, list) {
  2478. if (!strcmp(gen->type, type)
  2479. && !strcmp(gen->subtype, subtype)) {
  2480. break;
  2481. }
  2482. }
  2483. return gen;
  2484. }
  2485. static struct ast_sip_pubsub_body_generator *find_body_generator_type_subtype(const char *type, const char *subtype)
  2486. {
  2487. struct ast_sip_pubsub_body_generator *gen;
  2488. AST_RWLIST_RDLOCK(&body_generators);
  2489. gen = find_body_generator_type_subtype_nolock(type, subtype);
  2490. AST_RWLIST_UNLOCK(&body_generators);
  2491. return gen;
  2492. }
  2493. static struct ast_sip_pubsub_body_generator *find_body_generator_accept(const char *accept)
  2494. {
  2495. char *accept_copy = ast_strdupa(accept);
  2496. char *subtype = accept_copy;
  2497. char *type = strsep(&subtype, "/");
  2498. if (ast_strlen_zero(type) || ast_strlen_zero(subtype)) {
  2499. return NULL;
  2500. }
  2501. return find_body_generator_type_subtype(type, subtype);
  2502. }
  2503. static struct ast_sip_pubsub_body_generator *find_body_generator(char accept[AST_SIP_MAX_ACCEPT][64],
  2504. size_t num_accept, const char *body_type)
  2505. {
  2506. int i;
  2507. struct ast_sip_pubsub_body_generator *generator = NULL;
  2508. for (i = 0; i < num_accept; ++i) {
  2509. generator = find_body_generator_accept(accept[i]);
  2510. if (generator) {
  2511. ast_debug(3, "Body generator %p found for accept type %s\n", generator, accept[i]);
  2512. if (strcmp(generator->body_type, body_type)) {
  2513. ast_log(LOG_WARNING, "Body generator '%s/%s'(%p) does not accept the type of data this event generates\n",
  2514. generator->type, generator->subtype, generator);
  2515. generator = NULL;
  2516. continue;
  2517. }
  2518. break;
  2519. } else {
  2520. ast_debug(3, "No body generator found for accept type %s\n", accept[i]);
  2521. }
  2522. }
  2523. return generator;
  2524. }
  2525. static int generate_initial_notify(struct ast_sip_subscription *sub)
  2526. {
  2527. void *notify_data;
  2528. int res;
  2529. struct ast_sip_body_data data = {
  2530. .body_type = sub->handler->body_type,
  2531. };
  2532. if (AST_VECTOR_SIZE(&sub->children) > 0) {
  2533. int i;
  2534. for (i = 0; i < AST_VECTOR_SIZE(&sub->children); ++i) {
  2535. if (generate_initial_notify(AST_VECTOR_GET(&sub->children, i))) {
  2536. return -1;
  2537. }
  2538. }
  2539. return 0;
  2540. }
  2541. /* We notify subscription establishment only on the tree leaves. */
  2542. if (sub->handler->notifier->subscription_established(sub)) {
  2543. return -1;
  2544. }
  2545. notify_data = sub->handler->notifier->get_notify_data(sub);
  2546. if (!notify_data) {
  2547. ast_debug(3, "No notify data, not generating any body content\n");
  2548. return -1;
  2549. }
  2550. data.body_data = notify_data;
  2551. res = ast_sip_pubsub_generate_body_content(ast_sip_subscription_get_body_type(sub),
  2552. ast_sip_subscription_get_body_subtype(sub), &data, &sub->body_text);
  2553. ao2_cleanup(notify_data);
  2554. return res;
  2555. }
  2556. static int pubsub_on_refresh_timeout(void *userdata);
  2557. static int initial_notify_task(void * obj)
  2558. {
  2559. struct initial_notify_data *ind = obj;
  2560. if (generate_initial_notify(ind->sub_tree->root)) {
  2561. pjsip_evsub_terminate(ind->sub_tree->evsub, PJ_TRUE);
  2562. } else {
  2563. send_notify(ind->sub_tree, 1);
  2564. ast_test_suite_event_notify("SUBSCRIPTION_ESTABLISHED",
  2565. "Resource: %s",
  2566. ind->sub_tree->root->resource);
  2567. }
  2568. if (ind->expires != PJSIP_EXPIRES_NOT_SPECIFIED) {
  2569. char *name = ast_alloca(strlen("->/ ") +
  2570. strlen(ind->sub_tree->persistence->endpoint) +
  2571. strlen(ind->sub_tree->root->resource) +
  2572. strlen(ind->sub_tree->root->handler->event_name) +
  2573. ind->sub_tree->dlg->call_id->id.slen + 1);
  2574. sprintf(name, "%s->%s/%s %.*s", ind->sub_tree->persistence->endpoint,
  2575. ind->sub_tree->root->resource, ind->sub_tree->root->handler->event_name,
  2576. (int)ind->sub_tree->dlg->call_id->id.slen, ind->sub_tree->dlg->call_id->id.ptr);
  2577. ast_debug(3, "Scheduling timer: %s\n", name);
  2578. ind->sub_tree->expiration_task = ast_sip_schedule_task(ind->sub_tree->serializer,
  2579. ind->expires * 1000, pubsub_on_refresh_timeout, name,
  2580. ind->sub_tree, AST_SIP_SCHED_TASK_FIXED | AST_SIP_SCHED_TASK_DATA_AO2);
  2581. if (!ind->sub_tree->expiration_task) {
  2582. ast_log(LOG_ERROR, "Unable to create expiration timer of %d seconds for %s\n",
  2583. ind->expires, name);
  2584. }
  2585. }
  2586. ao2_ref(ind->sub_tree, -1);
  2587. ast_free(ind);
  2588. return 0;
  2589. }
  2590. static pj_bool_t pubsub_on_rx_subscribe_request(pjsip_rx_data *rdata)
  2591. {
  2592. pjsip_expires_hdr *expires_header;
  2593. struct ast_sip_subscription_handler *handler;
  2594. RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
  2595. struct sip_subscription_tree *sub_tree;
  2596. struct ast_sip_pubsub_body_generator *generator;
  2597. char *resource;
  2598. pjsip_uri *request_uri;
  2599. size_t resource_size;
  2600. int resp;
  2601. struct resource_tree tree;
  2602. pj_status_t dlg_status;
  2603. const pj_str_t *user;
  2604. endpoint = ast_pjsip_rdata_get_endpoint(rdata);
  2605. ast_assert(endpoint != NULL);
  2606. if (!endpoint->subscription.allow) {
  2607. ast_log(LOG_WARNING, "Subscriptions not permitted for endpoint %s.\n", ast_sorcery_object_get_id(endpoint));
  2608. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 603, NULL, NULL, NULL);
  2609. return PJ_TRUE;
  2610. }
  2611. request_uri = rdata->msg_info.msg->line.req.uri;
  2612. if (!ast_sip_is_uri_sip_sips(request_uri)) {
  2613. char uri_str[PJSIP_MAX_URL_SIZE];
  2614. pjsip_uri_print(PJSIP_URI_IN_REQ_URI, request_uri, uri_str, sizeof(uri_str));
  2615. ast_log(LOG_WARNING, "Request URI '%s' is not a sip: or sips: URI.\n", uri_str);
  2616. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 416, NULL, NULL, NULL);
  2617. return PJ_TRUE;
  2618. }
  2619. user = ast_sip_pjsip_uri_get_username(request_uri);
  2620. resource_size = pj_strlen(user) + 1;
  2621. resource = ast_alloca(resource_size);
  2622. ast_copy_pj_str(resource, user, resource_size);
  2623. /*
  2624. * We may want to match without any user options getting
  2625. * in the way.
  2626. */
  2627. AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(resource);
  2628. expires_header = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, rdata->msg_info.msg->hdr.next);
  2629. if (expires_header) {
  2630. if (expires_header->ivalue == 0) {
  2631. ast_debug(1, "Subscription request from endpoint %s rejected. Expiration of 0 is invalid\n",
  2632. ast_sorcery_object_get_id(endpoint));
  2633. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 400, NULL, NULL, NULL);
  2634. return PJ_TRUE;
  2635. }
  2636. if (expires_header->ivalue < endpoint->subscription.minexpiry) {
  2637. ast_log(LOG_WARNING, "Subscription expiration %d is too brief for endpoint %s. Minimum is %u\n",
  2638. expires_header->ivalue, ast_sorcery_object_get_id(endpoint), endpoint->subscription.minexpiry);
  2639. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 423, NULL, NULL, NULL);
  2640. return PJ_TRUE;
  2641. }
  2642. }
  2643. handler = subscription_get_handler_from_rdata(rdata, ast_sorcery_object_get_id(endpoint));
  2644. if (!handler) {
  2645. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 489, NULL, NULL, NULL);
  2646. return PJ_TRUE;
  2647. }
  2648. generator = subscription_get_generator_from_rdata(rdata, handler);
  2649. if (!generator) {
  2650. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 489, NULL, NULL, NULL);
  2651. return PJ_TRUE;
  2652. }
  2653. memset(&tree, 0, sizeof(tree));
  2654. resp = build_resource_tree(endpoint, handler, resource, &tree,
  2655. ast_sip_pubsub_has_eventlist_support(rdata), rdata);
  2656. if (!PJSIP_IS_STATUS_IN_CLASS(resp, 200)) {
  2657. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, resp, NULL, NULL, NULL);
  2658. resource_tree_destroy(&tree);
  2659. return PJ_TRUE;
  2660. }
  2661. sub_tree = create_subscription_tree(handler, endpoint, rdata, resource, generator, &tree, &dlg_status, NULL);
  2662. if (!sub_tree) {
  2663. if (dlg_status != PJ_EEXISTS) {
  2664. ast_debug(3, "No dialog exists, rejecting\n");
  2665. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
  2666. }
  2667. } else {
  2668. struct initial_notify_data *ind = ast_malloc(sizeof(*ind));
  2669. if (!ind) {
  2670. pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
  2671. resource_tree_destroy(&tree);
  2672. return PJ_TRUE;
  2673. }
  2674. ind->sub_tree = ao2_bump(sub_tree);
  2675. /* Since this is a normal subscribe, pjproject takes care of the timer */
  2676. ind->expires = PJSIP_EXPIRES_NOT_SPECIFIED;
  2677. sub_tree->persistence = subscription_persistence_create(sub_tree);
  2678. subscription_persistence_update(sub_tree, rdata, SUBSCRIPTION_PERSISTENCE_CREATED);
  2679. sip_subscription_accept(sub_tree, rdata, resp);
  2680. if (ast_sip_push_task(sub_tree->serializer, initial_notify_task, ind)) {
  2681. pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
  2682. ao2_ref(sub_tree, -1);
  2683. ast_free(ind);
  2684. }
  2685. }
  2686. resource_tree_destroy(&tree);
  2687. return PJ_TRUE;
  2688. }
  2689. static struct ast_sip_publish_handler *find_pub_handler(const char *event)
  2690. {
  2691. struct ast_sip_publish_handler *iter = NULL;
  2692. AST_RWLIST_RDLOCK(&publish_handlers);
  2693. AST_RWLIST_TRAVERSE(&publish_handlers, iter, next) {
  2694. if (strcmp(event, iter->event_name)) {
  2695. ast_debug(3, "Event %s does not match %s\n", event, iter->event_name);
  2696. continue;
  2697. }
  2698. ast_debug(3, "Event name match: %s = %s\n", event, iter->event_name);
  2699. break;
  2700. }
  2701. AST_RWLIST_UNLOCK(&publish_handlers);
  2702. return iter;
  2703. }
  2704. static enum sip_publish_type determine_sip_publish_type(pjsip_rx_data *rdata,
  2705. pjsip_generic_string_hdr *etag_hdr, unsigned int *expires, int *entity_id)
  2706. {
  2707. pjsip_expires_hdr *expires_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL);
  2708. if (etag_hdr) {
  2709. char etag[pj_strlen(&etag_hdr->hvalue) + 1];
  2710. ast_copy_pj_str(etag, &etag_hdr->hvalue, sizeof(etag));
  2711. if (sscanf(etag, "%30d", entity_id) != 1) {
  2712. return SIP_PUBLISH_UNKNOWN;
  2713. }
  2714. }
  2715. *expires = expires_hdr ? expires_hdr->ivalue : DEFAULT_PUBLISH_EXPIRES;
  2716. if (!(*expires)) {
  2717. return SIP_PUBLISH_REMOVE;
  2718. } else if (!etag_hdr && rdata->msg_info.msg->body) {
  2719. return SIP_PUBLISH_INITIAL;
  2720. } else if (etag_hdr && !rdata->msg_info.msg->body) {
  2721. return SIP_PUBLISH_REFRESH;
  2722. } else if (etag_hdr && rdata->msg_info.msg->body) {
  2723. return SIP_PUBLISH_MODIFY;
  2724. }
  2725. return SIP_PUBLISH_UNKNOWN;
  2726. }
  2727. /*! \brief Internal destructor for publications */
  2728. static void publication_destroy_fn(void *obj)
  2729. {
  2730. struct ast_sip_publication *publication = obj;
  2731. ast_debug(3, "Destroying SIP publication\n");
  2732. ao2_cleanup(publication->datastores);
  2733. ao2_cleanup(publication->endpoint);
  2734. ast_module_unref(ast_module_info->self);
  2735. }
  2736. static struct ast_sip_publication *sip_create_publication(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata,
  2737. const char *resource, const char *event_configuration_name)
  2738. {
  2739. struct ast_sip_publication *publication;
  2740. pjsip_expires_hdr *expires_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL);
  2741. size_t resource_len = strlen(resource) + 1, event_configuration_name_len = strlen(event_configuration_name) + 1;
  2742. char *dst;
  2743. ast_assert(endpoint != NULL);
  2744. if (!(publication = ao2_alloc(sizeof(*publication) + resource_len + event_configuration_name_len, publication_destroy_fn))) {
  2745. return NULL;
  2746. }
  2747. ast_module_ref(ast_module_info->self);
  2748. if (!(publication->datastores = ast_datastores_alloc())) {
  2749. ao2_ref(publication, -1);
  2750. return NULL;
  2751. }
  2752. publication->entity_tag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
  2753. ao2_ref(endpoint, +1);
  2754. publication->endpoint = endpoint;
  2755. publication->expires = expires_hdr ? expires_hdr->ivalue : DEFAULT_PUBLISH_EXPIRES;
  2756. publication->sched_id = -1;
  2757. dst = publication->data;
  2758. publication->resource = strcpy(dst, resource);
  2759. dst += resource_len;
  2760. publication->event_configuration_name = strcpy(dst, event_configuration_name);
  2761. return publication;
  2762. }
  2763. static int sip_publication_respond(struct ast_sip_publication *pub, int status_code,
  2764. pjsip_rx_data *rdata)
  2765. {
  2766. pjsip_tx_data *tdata;
  2767. pjsip_transaction *tsx;
  2768. if (pjsip_endpt_create_response(ast_sip_get_pjsip_endpoint(), rdata, status_code, NULL, &tdata) != PJ_SUCCESS) {
  2769. return -1;
  2770. }
  2771. if (PJSIP_IS_STATUS_IN_CLASS(status_code, 200)) {
  2772. char buf[30];
  2773. snprintf(buf, sizeof(buf), "%d", pub->entity_tag);
  2774. ast_sip_add_header(tdata, "SIP-ETag", buf);
  2775. snprintf(buf, sizeof(buf), "%d", pub->expires);
  2776. ast_sip_add_header(tdata, "Expires", buf);
  2777. }
  2778. if (pjsip_tsx_create_uas(&pubsub_module, rdata, &tsx) != PJ_SUCCESS) {
  2779. pjsip_tx_data_dec_ref(tdata);
  2780. return -1;
  2781. }
  2782. pjsip_tsx_recv_msg(tsx, rdata);
  2783. if (pjsip_tsx_send_msg(tsx, tdata) != PJ_SUCCESS) {
  2784. pjsip_tx_data_dec_ref(tdata);
  2785. return -1;
  2786. }
  2787. return 0;
  2788. }
  2789. static struct ast_sip_publication *publish_request_initial(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata,
  2790. struct ast_sip_publish_handler *handler)
  2791. {
  2792. struct ast_sip_publication *publication;
  2793. char *resource_name;
  2794. size_t resource_size;
  2795. RAII_VAR(struct ast_sip_publication_resource *, resource, NULL, ao2_cleanup);
  2796. struct ast_variable *event_configuration_name = NULL;
  2797. pjsip_uri *request_uri;
  2798. int resp;
  2799. const pj_str_t *user;
  2800. request_uri = rdata->msg_info.msg->line.req.uri;
  2801. if (!ast_sip_is_uri_sip_sips(request_uri)) {
  2802. char uri_str[PJSIP_MAX_URL_SIZE];
  2803. pjsip_uri_print(PJSIP_URI_IN_REQ_URI, request_uri, uri_str, sizeof(uri_str));
  2804. ast_log(LOG_WARNING, "Request URI '%s' is not a sip: or sips: URI.\n", uri_str);
  2805. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 416, NULL, NULL, NULL);
  2806. return NULL;
  2807. }
  2808. user = ast_sip_pjsip_uri_get_username(request_uri);
  2809. resource_size = pj_strlen(user) + 1;
  2810. resource_name = ast_alloca(resource_size);
  2811. ast_copy_pj_str(resource_name, user, resource_size);
  2812. /*
  2813. * We may want to match without any user options getting
  2814. * in the way.
  2815. */
  2816. AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(resource_name);
  2817. resource = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "inbound-publication", resource_name);
  2818. if (!resource) {
  2819. ast_debug(1, "No 'inbound-publication' defined for resource '%s'\n", resource_name);
  2820. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 404, NULL, NULL, NULL);
  2821. return NULL;
  2822. }
  2823. if (!ast_strlen_zero(resource->endpoint) && strcmp(resource->endpoint, ast_sorcery_object_get_id(endpoint))) {
  2824. ast_debug(1, "Resource %s has a defined endpoint '%s', but does not match endpoint '%s' that received the request\n",
  2825. resource_name, resource->endpoint, ast_sorcery_object_get_id(endpoint));
  2826. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
  2827. return NULL;
  2828. }
  2829. for (event_configuration_name = resource->events; event_configuration_name; event_configuration_name = event_configuration_name->next) {
  2830. if (!strcmp(event_configuration_name->name, handler->event_name)) {
  2831. break;
  2832. }
  2833. }
  2834. if (!event_configuration_name) {
  2835. ast_debug(1, "Event '%s' is not configured for '%s'\n", handler->event_name, resource_name);
  2836. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 404, NULL, NULL, NULL);
  2837. return NULL;
  2838. }
  2839. resp = handler->new_publication(endpoint, resource_name, event_configuration_name->value);
  2840. if (!PJSIP_IS_STATUS_IN_CLASS(resp, 200)) {
  2841. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, resp, NULL, NULL, NULL);
  2842. return NULL;
  2843. }
  2844. publication = sip_create_publication(endpoint, rdata, S_OR(resource_name, ""), event_configuration_name->value);
  2845. if (!publication) {
  2846. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 503, NULL, NULL, NULL);
  2847. return NULL;
  2848. }
  2849. publication->handler = handler;
  2850. if (publication->handler->publication_state_change(publication, rdata->msg_info.msg->body,
  2851. AST_SIP_PUBLISH_STATE_INITIALIZED)) {
  2852. ast_debug(3, "Publication state change failed\n");
  2853. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
  2854. ao2_cleanup(publication);
  2855. return NULL;
  2856. }
  2857. sip_publication_respond(publication, resp, rdata);
  2858. return publication;
  2859. }
  2860. static int publish_expire_callback(void *data)
  2861. {
  2862. RAII_VAR(struct ast_sip_publication *, publication, data, ao2_cleanup);
  2863. if (publication->handler->publish_expire) {
  2864. publication->handler->publish_expire(publication);
  2865. }
  2866. return 0;
  2867. }
  2868. static int publish_expire(const void *data)
  2869. {
  2870. struct ast_sip_publication *publication = (struct ast_sip_publication*)data;
  2871. ao2_unlink(publication->handler->publications, publication);
  2872. publication->sched_id = -1;
  2873. if (ast_sip_push_task(NULL, publish_expire_callback, publication)) {
  2874. ao2_cleanup(publication);
  2875. }
  2876. return 0;
  2877. }
  2878. static pj_bool_t pubsub_on_rx_publish_request(pjsip_rx_data *rdata)
  2879. {
  2880. pjsip_event_hdr *event_header;
  2881. struct ast_sip_publish_handler *handler;
  2882. RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
  2883. char event[32];
  2884. static const pj_str_t str_sip_if_match = { "SIP-If-Match", 12 };
  2885. pjsip_generic_string_hdr *etag_hdr = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_sip_if_match, NULL);
  2886. enum sip_publish_type publish_type;
  2887. RAII_VAR(struct ast_sip_publication *, publication, NULL, ao2_cleanup);
  2888. unsigned int expires = 0;
  2889. int entity_id, response = 0;
  2890. endpoint = ast_pjsip_rdata_get_endpoint(rdata);
  2891. ast_assert(endpoint != NULL);
  2892. event_header = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_event_name, rdata->msg_info.msg->hdr.next);
  2893. if (!event_header) {
  2894. ast_log(LOG_WARNING, "Incoming PUBLISH request from %s with no Event header\n",
  2895. ast_sorcery_object_get_id(endpoint));
  2896. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 489, NULL, NULL, NULL);
  2897. return PJ_TRUE;
  2898. }
  2899. ast_copy_pj_str(event, &event_header->event_type, sizeof(event));
  2900. handler = find_pub_handler(event);
  2901. if (!handler) {
  2902. ast_log(LOG_WARNING, "No registered publish handler for event %s from %s\n", event,
  2903. ast_sorcery_object_get_id(endpoint));
  2904. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 489, NULL, NULL, NULL);
  2905. return PJ_TRUE;
  2906. }
  2907. publish_type = determine_sip_publish_type(rdata, etag_hdr, &expires, &entity_id);
  2908. /* If this is not an initial publish ensure that a publication is present */
  2909. if ((publish_type != SIP_PUBLISH_INITIAL) && (publish_type != SIP_PUBLISH_UNKNOWN)) {
  2910. if (!(publication = ao2_find(handler->publications, &entity_id, OBJ_KEY | OBJ_UNLINK))) {
  2911. static const pj_str_t str_conditional_request_failed = { "Conditional Request Failed", 26 };
  2912. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 412, &str_conditional_request_failed,
  2913. NULL, NULL);
  2914. return PJ_TRUE;
  2915. }
  2916. /* Per the RFC every response has to have a new entity tag */
  2917. publication->entity_tag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
  2918. /* Update the expires here so that the created responses will contain the correct value */
  2919. publication->expires = expires;
  2920. }
  2921. switch (publish_type) {
  2922. case SIP_PUBLISH_INITIAL:
  2923. publication = publish_request_initial(endpoint, rdata, handler);
  2924. break;
  2925. case SIP_PUBLISH_REFRESH:
  2926. case SIP_PUBLISH_MODIFY:
  2927. if (handler->publication_state_change(publication, rdata->msg_info.msg->body,
  2928. AST_SIP_PUBLISH_STATE_ACTIVE)) {
  2929. /* If an error occurs we want to terminate the publication */
  2930. expires = 0;
  2931. }
  2932. response = 200;
  2933. break;
  2934. case SIP_PUBLISH_REMOVE:
  2935. handler->publication_state_change(publication, rdata->msg_info.msg->body,
  2936. AST_SIP_PUBLISH_STATE_TERMINATED);
  2937. response = 200;
  2938. break;
  2939. case SIP_PUBLISH_UNKNOWN:
  2940. default:
  2941. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 400, NULL, NULL, NULL);
  2942. break;
  2943. }
  2944. if (publication) {
  2945. if (expires) {
  2946. ao2_link(handler->publications, publication);
  2947. AST_SCHED_REPLACE_UNREF(publication->sched_id, sched, expires * 1000, publish_expire, publication,
  2948. ao2_ref(_data, -1), ao2_ref(publication, -1), ao2_ref(publication, +1));
  2949. } else {
  2950. AST_SCHED_DEL_UNREF(sched, publication->sched_id, ao2_ref(publication, -1));
  2951. }
  2952. }
  2953. if (response) {
  2954. sip_publication_respond(publication, response, rdata);
  2955. }
  2956. return PJ_TRUE;
  2957. }
  2958. struct ast_sip_endpoint *ast_sip_publication_get_endpoint(struct ast_sip_publication *pub)
  2959. {
  2960. return pub->endpoint;
  2961. }
  2962. const char *ast_sip_publication_get_resource(const struct ast_sip_publication *pub)
  2963. {
  2964. return pub->resource;
  2965. }
  2966. const char *ast_sip_publication_get_event_configuration(const struct ast_sip_publication *pub)
  2967. {
  2968. return pub->event_configuration_name;
  2969. }
  2970. int ast_sip_pubsub_is_body_generator_registered(const char *type, const char *subtype)
  2971. {
  2972. return !!find_body_generator_type_subtype(type, subtype);
  2973. }
  2974. int ast_sip_pubsub_register_body_generator(struct ast_sip_pubsub_body_generator *generator)
  2975. {
  2976. struct ast_sip_pubsub_body_generator *existing;
  2977. pj_str_t accept;
  2978. pj_size_t accept_len;
  2979. AST_RWLIST_WRLOCK(&body_generators);
  2980. existing = find_body_generator_type_subtype_nolock(generator->type, generator->subtype);
  2981. if (existing) {
  2982. AST_RWLIST_UNLOCK(&body_generators);
  2983. ast_log(LOG_WARNING, "A body generator for %s/%s is already registered.\n",
  2984. generator->type, generator->subtype);
  2985. return -1;
  2986. }
  2987. AST_LIST_INSERT_HEAD(&body_generators, generator, list);
  2988. AST_RWLIST_UNLOCK(&body_generators);
  2989. /* Lengths of type and subtype plus a slash. */
  2990. accept_len = strlen(generator->type) + strlen(generator->subtype) + 1;
  2991. /* Add room for null terminator that sprintf() will set. */
  2992. pj_strset(&accept, ast_alloca(accept_len + 1), accept_len);
  2993. sprintf((char *) pj_strbuf(&accept), "%s/%s", generator->type, generator->subtype);/* Safe */
  2994. pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), &pubsub_module,
  2995. PJSIP_H_ACCEPT, NULL, 1, &accept);
  2996. return 0;
  2997. }
  2998. void ast_sip_pubsub_unregister_body_generator(struct ast_sip_pubsub_body_generator *generator)
  2999. {
  3000. struct ast_sip_pubsub_body_generator *iter;
  3001. AST_RWLIST_WRLOCK(&body_generators);
  3002. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&body_generators, iter, list) {
  3003. if (iter == generator) {
  3004. AST_LIST_REMOVE_CURRENT(list);
  3005. break;
  3006. }
  3007. }
  3008. AST_RWLIST_TRAVERSE_SAFE_END;
  3009. AST_RWLIST_UNLOCK(&body_generators);
  3010. }
  3011. int ast_sip_pubsub_register_body_supplement(struct ast_sip_pubsub_body_supplement *supplement)
  3012. {
  3013. AST_RWLIST_WRLOCK(&body_supplements);
  3014. AST_RWLIST_INSERT_TAIL(&body_supplements, supplement, list);
  3015. AST_RWLIST_UNLOCK(&body_supplements);
  3016. return 0;
  3017. }
  3018. void ast_sip_pubsub_unregister_body_supplement(struct ast_sip_pubsub_body_supplement *supplement)
  3019. {
  3020. struct ast_sip_pubsub_body_supplement *iter;
  3021. AST_RWLIST_WRLOCK(&body_supplements);
  3022. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&body_supplements, iter, list) {
  3023. if (iter == supplement) {
  3024. AST_LIST_REMOVE_CURRENT(list);
  3025. break;
  3026. }
  3027. }
  3028. AST_RWLIST_TRAVERSE_SAFE_END;
  3029. AST_RWLIST_UNLOCK(&body_supplements);
  3030. }
  3031. const char *ast_sip_subscription_get_body_type(struct ast_sip_subscription *sub)
  3032. {
  3033. return sub->body_generator->type;
  3034. }
  3035. const char *ast_sip_subscription_get_body_subtype(struct ast_sip_subscription *sub)
  3036. {
  3037. return sub->body_generator->subtype;
  3038. }
  3039. int ast_sip_pubsub_generate_body_content(const char *type, const char *subtype,
  3040. struct ast_sip_body_data *data, struct ast_str **str)
  3041. {
  3042. struct ast_sip_pubsub_body_supplement *supplement;
  3043. struct ast_sip_pubsub_body_generator *generator;
  3044. int res = 0;
  3045. void *body;
  3046. generator = find_body_generator_type_subtype(type, subtype);
  3047. if (!generator) {
  3048. ast_log(LOG_WARNING, "Unable to find a body generator for %s/%s\n",
  3049. type, subtype);
  3050. return -1;
  3051. }
  3052. if (strcmp(data->body_type, generator->body_type)) {
  3053. ast_log(LOG_WARNING, "%s/%s body generator does not accept the type of data provided\n",
  3054. type, subtype);
  3055. return -1;
  3056. }
  3057. body = generator->allocate_body(data->body_data);
  3058. if (!body) {
  3059. ast_log(LOG_WARNING, "%s/%s body generator could not to allocate a body\n",
  3060. type, subtype);
  3061. return -1;
  3062. }
  3063. if (generator->generate_body_content(body, data->body_data)) {
  3064. res = -1;
  3065. goto end;
  3066. }
  3067. AST_RWLIST_RDLOCK(&body_supplements);
  3068. AST_RWLIST_TRAVERSE(&body_supplements, supplement, list) {
  3069. if (!strcmp(generator->type, supplement->type) &&
  3070. !strcmp(generator->subtype, supplement->subtype)) {
  3071. res = supplement->supplement_body(body, data->body_data);
  3072. if (res) {
  3073. break;
  3074. }
  3075. }
  3076. }
  3077. AST_RWLIST_UNLOCK(&body_supplements);
  3078. if (!res) {
  3079. generator->to_string(body, str);
  3080. }
  3081. end:
  3082. if (generator->destroy_body) {
  3083. generator->destroy_body(body);
  3084. }
  3085. return res;
  3086. }
  3087. struct simple_message_summary {
  3088. int messages_waiting;
  3089. int voice_messages_new;
  3090. int voice_messages_old;
  3091. int voice_messages_urgent_new;
  3092. int voice_messages_urgent_old;
  3093. char message_account[PJSIP_MAX_URL_SIZE];
  3094. };
  3095. static int parse_simple_message_summary(char *body,
  3096. struct simple_message_summary *summary)
  3097. {
  3098. char *line;
  3099. char *buffer;
  3100. int found_counts = 0;
  3101. if (ast_strlen_zero(body) || !summary) {
  3102. return -1;
  3103. }
  3104. buffer = ast_strdupa(body);
  3105. memset(summary, 0, sizeof(*summary));
  3106. while ((line = ast_read_line_from_buffer(&buffer))) {
  3107. line = ast_str_to_lower(line);
  3108. if (sscanf(line, "voice-message: %d/%d (%d/%d)",
  3109. &summary->voice_messages_new, &summary->voice_messages_old,
  3110. &summary->voice_messages_urgent_new, &summary->voice_messages_urgent_old)) {
  3111. found_counts = 1;
  3112. } else {
  3113. sscanf(line, "message-account: %s", summary->message_account);
  3114. }
  3115. }
  3116. return !found_counts;
  3117. }
  3118. static pj_bool_t pubsub_on_rx_mwi_notify_request(pjsip_rx_data *rdata)
  3119. {
  3120. RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
  3121. struct simple_message_summary summary;
  3122. const char *endpoint_name;
  3123. char *atsign;
  3124. char *context;
  3125. char *body;
  3126. char *mailbox;
  3127. int rc;
  3128. endpoint = ast_pjsip_rdata_get_endpoint(rdata);
  3129. if (!endpoint) {
  3130. ast_debug(1, "Incoming MWI: Endpoint not found in rdata (%p)\n", rdata);
  3131. rc = 404;
  3132. goto error;
  3133. }
  3134. endpoint_name = ast_sorcery_object_get_id(endpoint);
  3135. ast_debug(1, "Incoming MWI: Found endpoint: %s\n", endpoint_name);
  3136. if (ast_strlen_zero(endpoint->incoming_mwi_mailbox)) {
  3137. ast_debug(1, "Incoming MWI: No incoming mailbox specified for endpoint '%s'\n", endpoint_name);
  3138. ast_test_suite_event_notify("PUBSUB_NO_INCOMING_MWI_MAILBOX",
  3139. "Endpoint: %s", endpoint_name);
  3140. rc = 404;
  3141. goto error;
  3142. }
  3143. mailbox = ast_strdupa(endpoint->incoming_mwi_mailbox);
  3144. atsign = strchr(mailbox, '@');
  3145. if (!atsign) {
  3146. ast_debug(1, "Incoming MWI: No '@' found in endpoint %s's incoming mailbox '%s'. Can't parse context\n",
  3147. endpoint_name, endpoint->incoming_mwi_mailbox);
  3148. rc = 404;
  3149. goto error;
  3150. }
  3151. *atsign = '\0';
  3152. context = atsign + 1;
  3153. body = ast_alloca(rdata->msg_info.msg->body->len + 1);
  3154. rdata->msg_info.msg->body->print_body(rdata->msg_info.msg->body, body,
  3155. rdata->msg_info.msg->body->len + 1);
  3156. if (parse_simple_message_summary(body, &summary) != 0) {
  3157. ast_debug(1, "Incoming MWI: Endpoint: '%s' There was an issue getting message info from body '%s'\n",
  3158. ast_sorcery_object_get_id(endpoint), body);
  3159. rc = 404;
  3160. goto error;
  3161. }
  3162. if (ast_publish_mwi_state(mailbox, context,
  3163. summary.voice_messages_new, summary.voice_messages_old)) {
  3164. ast_log(LOG_ERROR, "Incoming MWI: Endpoint: '%s' Could not publish MWI to stasis. "
  3165. "Mailbox: %s Message-Account: %s Voice-Messages: %d/%d (%d/%d)\n",
  3166. endpoint_name, endpoint->incoming_mwi_mailbox, summary.message_account,
  3167. summary.voice_messages_new, summary.voice_messages_old,
  3168. summary.voice_messages_urgent_new, summary.voice_messages_urgent_old);
  3169. rc = 404;
  3170. } else {
  3171. ast_debug(1, "Incoming MWI: Endpoint: '%s' Mailbox: %s Message-Account: %s Voice-Messages: %d/%d (%d/%d)\n",
  3172. endpoint_name, endpoint->incoming_mwi_mailbox, summary.message_account,
  3173. summary.voice_messages_new, summary.voice_messages_old,
  3174. summary.voice_messages_urgent_new, summary.voice_messages_urgent_old);
  3175. ast_test_suite_event_notify("PUBSUB_INCOMING_MWI_PUBLISH",
  3176. "Endpoint: %s\r\n"
  3177. "Mailbox: %s\r\n"
  3178. "MessageAccount: %s\r\n"
  3179. "VoiceMessagesNew: %d\r\n"
  3180. "VoiceMessagesOld: %d\r\n"
  3181. "VoiceMessagesUrgentNew: %d\r\n"
  3182. "VoiceMessagesUrgentOld: %d",
  3183. endpoint_name, endpoint->incoming_mwi_mailbox, summary.message_account,
  3184. summary.voice_messages_new, summary.voice_messages_old,
  3185. summary.voice_messages_urgent_new, summary.voice_messages_urgent_old);
  3186. rc = 200;
  3187. }
  3188. error:
  3189. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, rc, NULL, NULL, NULL);
  3190. return PJ_TRUE;
  3191. }
  3192. static pj_bool_t pubsub_on_rx_notify_request(pjsip_rx_data *rdata)
  3193. {
  3194. if (rdata->msg_info.msg->body &&
  3195. ast_sip_is_content_type(&rdata->msg_info.msg->body->content_type,
  3196. "application", "simple-message-summary")) {
  3197. return pubsub_on_rx_mwi_notify_request(rdata);
  3198. }
  3199. return PJ_FALSE;
  3200. }
  3201. static pj_bool_t pubsub_on_rx_request(pjsip_rx_data *rdata)
  3202. {
  3203. if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, pjsip_get_subscribe_method())) {
  3204. return pubsub_on_rx_subscribe_request(rdata);
  3205. } else if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_publish_method)) {
  3206. return pubsub_on_rx_publish_request(rdata);
  3207. } else if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_notify_method)) {
  3208. return pubsub_on_rx_notify_request(rdata);
  3209. }
  3210. return PJ_FALSE;
  3211. }
  3212. /*!
  3213. * \brief Callback sequence for subscription terminate:
  3214. *
  3215. * * Please note that the descriptions below represent pjproject behavior on versions
  3216. * >= 2.13.
  3217. * * Client initiated:
  3218. * pjproject receives SUBSCRIBE on the subscription's serializer thread
  3219. * calls pubsub_evsub_set_state with state = TERMINATED
  3220. * pubsub_on_evsub_state checks the event and finds it is due to a received
  3221. * SUBSCRIBE with an expires of 0 and so does nothing.
  3222. * calls pubsub_on_rx_refresh with dialog locked
  3223. * pubsub_on_rx_refresh sets TERMINATE_PENDING
  3224. * calls pubsub_on_refresh_timeout to push final NOTIFY to pjproject
  3225. * checks state == TERMINATE_PENDING
  3226. * sets TERMINATE_IN_PROGRESS
  3227. * calls send_notify (2)
  3228. * send_notify ultimately calls pjsip_evsub_send_request
  3229. * pjsip_evsub_send_request calls evsub's set_state
  3230. * set_state calls pubsub_evsub_set_state
  3231. * pubsub_on_evsub_state checks state == TERMINATE_IN_PROGRESS
  3232. * removes the subscriptions
  3233. * cleans up references to evsub
  3234. * sets state = TERMINATED
  3235. * pubsub_on_refresh_timeout unlocks dialog
  3236. * returns to pjproject
  3237. * pjproject unlocks dialog
  3238. *
  3239. * * Subscription timer expires:
  3240. * pjproject timer expires
  3241. * locks dialog
  3242. * calls pubsub_on_server_timeout
  3243. * pubsub_on_server_timeout checks state == NORMAL
  3244. * sets TERMINATE_PENDING
  3245. * pushes serialized_pubsub_on_refresh_timeout
  3246. * returns to pjproject
  3247. * pjproject unlocks dialog
  3248. * serialized_pubsub_on_refresh_timeout starts (1)
  3249. * locks dialog
  3250. * checks state == TERMINATE_PENDING
  3251. * sets TERMINATE_IN_PROGRESS
  3252. * calls send_notify (2)
  3253. * send_notify ultimately calls pjsip_evsub_send_request
  3254. * pjsip_evsub_send_request calls evsub's set_state
  3255. * set_state calls pubsub_evsub_set_state
  3256. * pubsub_on_evsub_state checks state == TERMINATE_IN_PROGRESS
  3257. * checks that the event is not due to un-SUBSCRIBE
  3258. * removes the subscriptions
  3259. * cleans up references to evsub
  3260. * sets state = TERMINATED
  3261. * serialized_pubsub_on_refresh_timeout unlocks dialog
  3262. *
  3263. * * Transmission failure sending NOTIFY or error response from client
  3264. * pjproject transaction timer expires or non OK response
  3265. * pjproject locks dialog
  3266. * calls pubsub_on_evsub_state with event TSX_STATE
  3267. * pubsub_on_evsub_state checks event == TSX_STATE
  3268. * removes the subscriptions
  3269. * cleans up references to evsub
  3270. * sets state = TERMINATED
  3271. * pjproject unlocks dialog
  3272. *
  3273. * * ast_sip_subscription_notify is called
  3274. * checks state == NORMAL
  3275. * if not batched...
  3276. * sets TERMINATE_IN_PROGRESS (if terminate is requested)
  3277. * calls send_notify
  3278. * See (2) Above
  3279. * if batched...
  3280. * sets TERMINATE_PENDING
  3281. * schedules task
  3282. * scheduler runs sched_task
  3283. * sched_task pushes serialized_send_notify
  3284. * serialized_send_notify starts
  3285. * checks state <= TERMINATE_PENDING
  3286. * if state == TERMINATE_PENDING set state = TERMINATE_IN_PROGRESS
  3287. * call send_notify
  3288. * See (2) Above
  3289. *
  3290. */
  3291. /* The code in this function was previously in pubsub_on_evsub_state. */
  3292. static void clean_sub_tree(pjsip_evsub *evsub)
  3293. {
  3294. struct sip_subscription_tree *sub_tree;
  3295. sub_tree = pjsip_evsub_get_mod_data(evsub, pubsub_module.id);
  3296. ast_debug(3, "Cleaning subscription %p\n", evsub);
  3297. if (sub_tree->expiration_task) {
  3298. char task_name[256];
  3299. ast_sip_sched_task_get_name(sub_tree->expiration_task, task_name, sizeof(task_name));
  3300. ast_debug(3, "Cancelling timer: %s\n", task_name);
  3301. ast_sip_sched_task_cancel(sub_tree->expiration_task);
  3302. ao2_cleanup(sub_tree->expiration_task);
  3303. sub_tree->expiration_task = NULL;
  3304. }
  3305. remove_subscription(sub_tree);
  3306. pjsip_evsub_set_mod_data(evsub, pubsub_module.id, NULL);
  3307. #ifdef HAVE_PJSIP_EVSUB_GRP_LOCK
  3308. pjsip_evsub_dec_ref(sub_tree->evsub);
  3309. #endif
  3310. sub_tree->evsub = NULL;
  3311. ast_sip_dialog_set_serializer(sub_tree->dlg, NULL);
  3312. ast_sip_dialog_set_endpoint(sub_tree->dlg, NULL);
  3313. subscription_persistence_remove(sub_tree);
  3314. shutdown_subscriptions(sub_tree->root);
  3315. sub_tree->state = SIP_SUB_TREE_TERMINATED;
  3316. /* Remove evsub's reference to the sub_tree */
  3317. ao2_ref(sub_tree, -1);
  3318. }
  3319. /* This functionality appeared in pjsip 2.13 */
  3320. #if PJ_VERSION_NUM >= 0x020D0000
  3321. # define HAVE_PJSIP_EVSUB_PENDING_NOTIFY 1
  3322. #endif
  3323. /*!
  3324. * \brief PJSIP callback when underlying SIP subscription changes state
  3325. *
  3326. * Although this function is called for every state change, we only care
  3327. * about the TERMINATED state, and only when we're actually processing the final
  3328. * notify (SIP_SUB_TREE_TERMINATE_IN_PROGRESS) OR when a transmission failure
  3329. * occurs (PJSIP_EVENT_TSX_STATE). In this case, we do all the subscription tree
  3330. * cleanup tasks and decrement the evsub reference.
  3331. */
  3332. static void pubsub_on_evsub_state(pjsip_evsub *evsub, pjsip_event *event)
  3333. {
  3334. struct sip_subscription_tree *sub_tree =
  3335. pjsip_evsub_get_mod_data(evsub, pubsub_module.id);
  3336. ast_debug(3, "evsub %p state %s event %s sub_tree %p sub_tree state %s\n", evsub,
  3337. pjsip_evsub_get_state_name(evsub), pjsip_event_str(event->type), sub_tree,
  3338. (sub_tree ? sub_tree_state_description[sub_tree->state] : "UNKNOWN"));
  3339. if (!sub_tree || pjsip_evsub_get_state(evsub) != PJSIP_EVSUB_STATE_TERMINATED) {
  3340. return;
  3341. }
  3342. /* It's easier to write this as what we WANT to process, then negate it. */
  3343. if (!(sub_tree->state == SIP_SUB_TREE_TERMINATE_IN_PROGRESS
  3344. || (event->type == PJSIP_EVENT_TSX_STATE && sub_tree->state == SIP_SUB_TREE_NORMAL)
  3345. )) {
  3346. ast_debug(3, "Do nothing.\n");
  3347. return;
  3348. }
  3349. #ifdef HAVE_PJSIP_EVSUB_PENDING_NOTIFY
  3350. /* This check looks for re-subscribes with an expires of 0. If we receive one of those,
  3351. we don't want to clean the evsub because we still need it to send the final NOTIFY.
  3352. This was previously handled by pubsub_on_rx_refresh setting:
  3353. 'sub_tree->state = SIP_SUB_TREE_TERMINATE_PENDING' */
  3354. if (event->body.tsx_state.type == PJSIP_EVENT_RX_MSG &&
  3355. !pjsip_method_cmp(&event->body.tsx_state.tsx->method, &pjsip_subscribe_method) &&
  3356. pjsip_evsub_get_expires(evsub) == 0) {
  3357. ast_debug(3, "Subscription ending, do nothing.\n");
  3358. return;
  3359. }
  3360. #endif
  3361. /* If we made it this far, we want to clean the sub tree. For pjproject <2.13, the sub_tree
  3362. state check makes sure the evsub is not cleaned at the wrong time */
  3363. clean_sub_tree(evsub);
  3364. }
  3365. static int pubsub_on_refresh_timeout(void *userdata)
  3366. {
  3367. struct sip_subscription_tree *sub_tree = userdata;
  3368. pjsip_dialog *dlg = sub_tree->dlg;
  3369. ast_debug(3, "sub_tree %p sub_tree state %s\n", sub_tree,
  3370. (sub_tree ? sub_tree_state_description[sub_tree->state] : "UNKNOWN"));
  3371. pjsip_dlg_inc_lock(dlg);
  3372. if (sub_tree->state >= SIP_SUB_TREE_TERMINATE_IN_PROGRESS) {
  3373. pjsip_dlg_dec_lock(dlg);
  3374. return 0;
  3375. }
  3376. if (sub_tree->state == SIP_SUB_TREE_TERMINATE_PENDING) {
  3377. sub_tree->state = SIP_SUB_TREE_TERMINATE_IN_PROGRESS;
  3378. set_state_terminated(sub_tree->root);
  3379. }
  3380. if (sub_tree->generate_initial_notify) {
  3381. sub_tree->generate_initial_notify = 0;
  3382. if (generate_initial_notify(sub_tree->root)) {
  3383. pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
  3384. pjsip_dlg_dec_lock(dlg);
  3385. return 0;
  3386. }
  3387. }
  3388. send_notify(sub_tree, 1);
  3389. ast_test_suite_event_notify(sub_tree->root->subscription_state == PJSIP_EVSUB_STATE_TERMINATED ?
  3390. "SUBSCRIPTION_TERMINATED" : "SUBSCRIPTION_REFRESHED",
  3391. "Resource: %s", sub_tree->root->resource);
  3392. pjsip_dlg_dec_lock(dlg);
  3393. return 0;
  3394. }
  3395. static int serialized_pubsub_on_refresh_timeout(void *userdata)
  3396. {
  3397. struct sip_subscription_tree *sub_tree = userdata;
  3398. ast_debug(3, "sub_tree %p sub_tree state %s\n", sub_tree,
  3399. (sub_tree ? sub_tree_state_description[sub_tree->state] : "UNKNOWN"));
  3400. pubsub_on_refresh_timeout(userdata);
  3401. ao2_cleanup(sub_tree);
  3402. return 0;
  3403. }
  3404. /*!
  3405. * \brief Compare strings for equality checking for NULL.
  3406. *
  3407. * This function considers NULL values as empty strings.
  3408. * This means NULL or empty strings are equal.
  3409. *
  3410. * \retval 0 The strings are equal
  3411. * \retval 1 The strings are not equal
  3412. */
  3413. static int cmp_strings(char *s1, char *s2)
  3414. {
  3415. if (!ast_strlen_zero(s1) && !ast_strlen_zero(s2)) {
  3416. return strcmp(s1, s2);
  3417. }
  3418. return ast_strlen_zero(s1) == ast_strlen_zero(s2) ? 0 : 1;
  3419. }
  3420. /*!
  3421. * \brief compares the childrens of two ast_sip_subscription s1 and s2
  3422. *
  3423. * \retval 0 The s1 childrens match the s2 childrens
  3424. * \retval 1 The s1 childrens do not match the s2 childrens
  3425. */
  3426. static int cmp_subscription_childrens(struct ast_sip_subscription *s1, struct ast_sip_subscription *s2)
  3427. {
  3428. int i;
  3429. if (AST_VECTOR_SIZE(&s1->children) != AST_VECTOR_SIZE(&s2->children)) {
  3430. return 1;
  3431. }
  3432. for (i = 0; i < AST_VECTOR_SIZE(&s1->children); ++i) {
  3433. struct ast_sip_subscription *c1 = AST_VECTOR_GET(&s1->children, i);
  3434. struct ast_sip_subscription *c2 = AST_VECTOR_GET(&s2->children, i);
  3435. if (cmp_strings(c1->resource, c2->resource)
  3436. || cmp_strings(c1->display_name, c2->display_name)) {
  3437. return 1;
  3438. }
  3439. }
  3440. return 0;
  3441. }
  3442. static int destroy_subscriptions_task(void *obj)
  3443. {
  3444. struct ast_sip_subscription *sub = (struct ast_sip_subscription *) obj;
  3445. destroy_subscriptions(sub);
  3446. return 0;
  3447. }
  3448. /*!
  3449. * \brief Called whenever an in-dialog SUBSCRIBE is received
  3450. *
  3451. * This includes both SUBSCRIBE requests that actually refresh the subscription
  3452. * as well as SUBSCRIBE requests that end the subscription.
  3453. *
  3454. * In either case we push an appropriate NOTIFY via pubsub_on_refresh_timeout.
  3455. */
  3456. static void pubsub_on_rx_refresh(pjsip_evsub *evsub, pjsip_rx_data *rdata,
  3457. int *p_st_code, pj_str_t **p_st_text, pjsip_hdr *res_hdr, pjsip_msg_body **p_body)
  3458. {
  3459. struct sip_subscription_tree *sub_tree;
  3460. RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
  3461. sub_tree = pjsip_evsub_get_mod_data(evsub, pubsub_module.id);
  3462. ast_debug(3, "evsub %p sub_tree %p sub_tree state %s\n", evsub, sub_tree,
  3463. (sub_tree ? sub_tree_state_description[sub_tree->state] : "UNKNOWN"));
  3464. if (!sub_tree || sub_tree->state != SIP_SUB_TREE_NORMAL) {
  3465. return;
  3466. }
  3467. if (sub_tree->expiration_task) {
  3468. char task_name[256];
  3469. ast_sip_sched_task_get_name(sub_tree->expiration_task, task_name, sizeof(task_name));
  3470. ast_debug(3, "Cancelling timer: %s\n", task_name);
  3471. ast_sip_sched_task_cancel(sub_tree->expiration_task);
  3472. ao2_cleanup(sub_tree->expiration_task);
  3473. sub_tree->expiration_task = NULL;
  3474. }
  3475. /* PJSIP will set the evsub's state to terminated before calling into this function
  3476. * if the Expires value of the incoming SUBSCRIBE is 0.
  3477. */
  3478. if (pjsip_evsub_get_state(sub_tree->evsub) == PJSIP_EVSUB_STATE_TERMINATED) {
  3479. sub_tree->state = SIP_SUB_TREE_TERMINATE_PENDING;
  3480. }
  3481. endpoint = ast_pjsip_rdata_get_endpoint(rdata);
  3482. /* If the handler wants a callback on refresh, then do it (some protocols require this). */
  3483. if (sub_tree->state == SIP_SUB_TREE_NORMAL && sub_tree->root->handler->notifier->refresh_subscribe) {
  3484. if (!sub_tree->root->handler->notifier->refresh_subscribe(sub_tree->root, rdata)) {
  3485. return; /* If the callback handled it, we're done. */
  3486. }
  3487. }
  3488. if (sub_tree->state == SIP_SUB_TREE_NORMAL && sub_tree->is_list) {
  3489. /* update RLS */
  3490. const char *resource = sub_tree->root->resource;
  3491. struct ast_sip_subscription *old_root = sub_tree->root;
  3492. struct ast_sip_subscription *new_root = NULL;
  3493. struct ast_sip_pubsub_body_generator *generator = NULL;
  3494. if (endpoint && (generator = subscription_get_generator_from_rdata(rdata, sub_tree->root->handler))) {
  3495. struct resource_tree tree;
  3496. int resp;
  3497. memset(&tree, 0, sizeof(tree));
  3498. resp = build_resource_tree(endpoint, sub_tree->root->handler, resource, &tree,
  3499. ast_sip_pubsub_has_eventlist_support(rdata), rdata);
  3500. if (PJSIP_IS_STATUS_IN_CLASS(resp, 200)) {
  3501. new_root = create_virtual_subscriptions(sub_tree->root->handler, resource, generator, sub_tree, tree.root);
  3502. if (new_root) {
  3503. if (cmp_subscription_childrens(old_root, new_root)) {
  3504. ast_debug(1, "RLS '%s->%s' was modified, regenerate it\n", ast_sorcery_object_get_id(endpoint), old_root->resource);
  3505. new_root->version = old_root->version;
  3506. sub_tree->root = new_root;
  3507. sub_tree->generate_initial_notify = 1;
  3508. /* If there is scheduled notification need to delete it to avoid use old subscriptions */
  3509. if (sub_tree->notify_sched_id > -1) {
  3510. AST_SCHED_DEL_UNREF(sched, sub_tree->notify_sched_id, ao2_ref(sub_tree, -1));
  3511. sub_tree->send_scheduled_notify = 0;
  3512. }
  3513. /* Terminate old subscriptions to stop sending NOTIFY messages on exten/device state changes */
  3514. set_state_terminated(old_root);
  3515. /* Shutdown old subscriptions to remove exten/device state change callbacks
  3516. that can queue tasks for old subscriptions */
  3517. shutdown_subscriptions(old_root);
  3518. /* Postpone destruction until all already queued tasks that may be using old subscriptions have completed */
  3519. if (ast_sip_push_task(sub_tree->serializer, destroy_subscriptions_task, old_root)) {
  3520. ast_log(LOG_ERROR, "Failed to push task to destroy old subscriptions for RLS '%s->%s'.\n",
  3521. ast_sorcery_object_get_id(endpoint), old_root->resource);
  3522. }
  3523. } else {
  3524. destroy_subscriptions(new_root);
  3525. }
  3526. }
  3527. } else {
  3528. sub_tree->state = SIP_SUB_TREE_TERMINATE_PENDING;
  3529. pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
  3530. }
  3531. resource_tree_destroy(&tree);
  3532. }
  3533. }
  3534. subscription_persistence_update(sub_tree, rdata, SUBSCRIPTION_PERSISTENCE_REFRESHED);
  3535. #ifdef HAVE_PJSIP_EVSUB_PENDING_NOTIFY
  3536. /* As of pjsip 2.13, the NOTIFY has to be sent within this function as pjproject now
  3537. requires it. Previously this would have caused an early NOTIFY to go out before the
  3538. SUBSCRIBE's 200 OK. The previous solution was to push the NOTIFY, but now pjproject
  3539. looks for the NOTIFY to be sent from this function and caches it to send after it
  3540. auto-replies to the SUBSCRIBE. */
  3541. pubsub_on_refresh_timeout(sub_tree);
  3542. #else
  3543. if (ast_sip_push_task(sub_tree->serializer, serialized_pubsub_on_refresh_timeout, ao2_bump(sub_tree))) {
  3544. /* If we can't push the NOTIFY refreshing task...we'll just go with it. */
  3545. ast_log(LOG_ERROR, "Failed to push task to send NOTIFY.\n");
  3546. sub_tree->state = SIP_SUB_TREE_NORMAL;
  3547. ao2_ref(sub_tree, -1);
  3548. }
  3549. #endif
  3550. if (sub_tree->is_list) {
  3551. pj_list_insert_before(res_hdr, create_require_eventlist(rdata->tp_info.pool));
  3552. }
  3553. }
  3554. static void pubsub_on_rx_notify(pjsip_evsub *evsub, pjsip_rx_data *rdata, int *p_st_code,
  3555. pj_str_t **p_st_text, pjsip_hdr *res_hdr, pjsip_msg_body **p_body)
  3556. {
  3557. struct ast_sip_subscription *sub;
  3558. if (!(sub = pjsip_evsub_get_mod_data(evsub, pubsub_module.id))) {
  3559. return;
  3560. }
  3561. sub->handler->subscriber->state_change(sub, rdata->msg_info.msg->body,
  3562. pjsip_evsub_get_state(evsub));
  3563. }
  3564. static int serialized_pubsub_on_client_refresh(void *userdata)
  3565. {
  3566. struct sip_subscription_tree *sub_tree = userdata;
  3567. pjsip_tx_data *tdata;
  3568. if (!sub_tree->evsub) {
  3569. ao2_cleanup(sub_tree);
  3570. return 0;
  3571. }
  3572. if (pjsip_evsub_initiate(sub_tree->evsub, NULL, -1, &tdata) == PJ_SUCCESS) {
  3573. pjsip_evsub_send_request(sub_tree->evsub, tdata);
  3574. } else {
  3575. pjsip_evsub_terminate(sub_tree->evsub, PJ_TRUE);
  3576. }
  3577. ao2_cleanup(sub_tree);
  3578. return 0;
  3579. }
  3580. static void pubsub_on_client_refresh(pjsip_evsub *evsub)
  3581. {
  3582. struct sip_subscription_tree *sub_tree;
  3583. if (!(sub_tree = pjsip_evsub_get_mod_data(evsub, pubsub_module.id))) {
  3584. return;
  3585. }
  3586. if (ast_sip_push_task(sub_tree->serializer, serialized_pubsub_on_client_refresh, ao2_bump(sub_tree))) {
  3587. ao2_cleanup(sub_tree);
  3588. }
  3589. }
  3590. static void pubsub_on_server_timeout(pjsip_evsub *evsub)
  3591. {
  3592. struct sip_subscription_tree *sub_tree;
  3593. /* PJSIP does not terminate the server timeout timer when a SUBSCRIBE
  3594. * with Expires: 0 arrives to end a subscription, nor does it terminate
  3595. * this timer when we send a NOTIFY request in response to receiving such
  3596. * a SUBSCRIBE. PJSIP does not stop the server timeout timer until the
  3597. * NOTIFY transaction has finished (either through receiving a response
  3598. * or through a transaction timeout).
  3599. *
  3600. * Therefore, it is possible that we can be told that a server timeout
  3601. * occurred after we already thought that the subscription had been
  3602. * terminated. In such a case, we will have already removed the sub_tree
  3603. * from the evsub's mod_data array.
  3604. */
  3605. sub_tree = pjsip_evsub_get_mod_data(evsub, pubsub_module.id);
  3606. if (!sub_tree || sub_tree->state != SIP_SUB_TREE_NORMAL) {
  3607. return;
  3608. }
  3609. sub_tree->state = SIP_SUB_TREE_TERMINATE_PENDING;
  3610. if (ast_sip_push_task(sub_tree->serializer, serialized_pubsub_on_refresh_timeout, ao2_bump(sub_tree))) {
  3611. sub_tree->state = SIP_SUB_TREE_NORMAL;
  3612. ao2_cleanup(sub_tree);
  3613. }
  3614. }
  3615. static int ami_subscription_detail(struct sip_subscription_tree *sub_tree,
  3616. struct ast_sip_ami *ami,
  3617. const char *event)
  3618. {
  3619. struct ast_str *buf;
  3620. buf = ast_sip_create_ami_event(event, ami);
  3621. if (!buf) {
  3622. return -1;
  3623. }
  3624. sip_subscription_to_ami(sub_tree, &buf);
  3625. astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
  3626. ast_free(buf);
  3627. ++ami->count;
  3628. return 0;
  3629. }
  3630. static int ami_subscription_detail_inbound(struct sip_subscription_tree *sub_tree, void *arg)
  3631. {
  3632. return sub_tree->role == AST_SIP_NOTIFIER ? ami_subscription_detail(
  3633. sub_tree, arg, "InboundSubscriptionDetail") : 0;
  3634. }
  3635. static int ami_subscription_detail_outbound(struct sip_subscription_tree *sub_tree, void *arg)
  3636. {
  3637. return sub_tree->role == AST_SIP_SUBSCRIBER ? ami_subscription_detail(
  3638. sub_tree, arg, "OutboundSubscriptionDetail") : 0;
  3639. }
  3640. static int ami_show_subscriptions_inbound(struct mansession *s, const struct message *m)
  3641. {
  3642. struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
  3643. astman_send_listack(s, m, "Following are Events for each inbound Subscription",
  3644. "start");
  3645. for_each_subscription(ami_subscription_detail_inbound, &ami);
  3646. astman_send_list_complete_start(s, m, "InboundSubscriptionDetailComplete", ami.count);
  3647. astman_send_list_complete_end(s);
  3648. return 0;
  3649. }
  3650. static int ami_show_subscriptions_outbound(struct mansession *s, const struct message *m)
  3651. {
  3652. struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
  3653. astman_send_listack(s, m, "Following are Events for each outbound Subscription",
  3654. "start");
  3655. for_each_subscription(ami_subscription_detail_outbound, &ami);
  3656. astman_send_list_complete_start(s, m, "OutboundSubscriptionDetailComplete", ami.count);
  3657. astman_send_list_complete_end(s);
  3658. return 0;
  3659. }
  3660. static int format_ami_resource_lists(void *obj, void *arg, int flags)
  3661. {
  3662. struct resource_list *list = obj;
  3663. struct ast_sip_ami *ami = arg;
  3664. struct ast_str *buf;
  3665. buf = ast_sip_create_ami_event("ResourceListDetail", ami);
  3666. if (!buf) {
  3667. return CMP_STOP;
  3668. }
  3669. if (ast_sip_sorcery_object_to_ami(list, &buf)) {
  3670. ast_free(buf);
  3671. return CMP_STOP;
  3672. }
  3673. astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
  3674. ast_free(buf);
  3675. ++ami->count;
  3676. return 0;
  3677. }
  3678. static int ami_show_resource_lists(struct mansession *s, const struct message *m)
  3679. {
  3680. struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
  3681. struct ao2_container *lists;
  3682. lists = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "resource_list",
  3683. AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  3684. if (!lists || !ao2_container_count(lists)) {
  3685. astman_send_error(s, m, "No resource lists found\n");
  3686. return 0;
  3687. }
  3688. astman_send_listack(s, m, "A listing of resource lists follows, presented as ResourceListDetail events",
  3689. "start");
  3690. ao2_callback(lists, OBJ_NODATA, format_ami_resource_lists, &ami);
  3691. astman_send_list_complete_start(s, m, "ResourceListDetailComplete", ami.count);
  3692. astman_send_list_complete_end(s);
  3693. return 0;
  3694. }
  3695. #define AMI_SHOW_SUBSCRIPTIONS_INBOUND "PJSIPShowSubscriptionsInbound"
  3696. #define AMI_SHOW_SUBSCRIPTIONS_OUTBOUND "PJSIPShowSubscriptionsOutbound"
  3697. #define MAX_REGEX_ERROR_LEN 128
  3698. struct cli_sub_parms {
  3699. /*! CLI handler entry e parameter */
  3700. struct ast_cli_entry *e;
  3701. /*! CLI handler entry a parameter */
  3702. struct ast_cli_args *a;
  3703. /*! CLI subscription entry output line(s) */
  3704. struct ast_str *buf;
  3705. /*! Compiled regular expression to select if buf is written to CLI when not NULL. */
  3706. regex_t *like;
  3707. int count;
  3708. };
  3709. struct cli_sub_complete_parms {
  3710. struct ast_cli_args *a;
  3711. /*! Found callid for search position */
  3712. char *callid;
  3713. int wordlen;
  3714. int which;
  3715. };
  3716. static int cli_complete_subscription_common(struct sip_subscription_tree *sub_tree, struct cli_sub_complete_parms *cli)
  3717. {
  3718. pj_str_t *callid;
  3719. if (!sub_tree->dlg) {
  3720. return 0;
  3721. }
  3722. callid = &sub_tree->dlg->call_id->id;
  3723. if (cli->wordlen <= pj_strlen(callid)
  3724. && !strncasecmp(cli->a->word, pj_strbuf(callid), cli->wordlen)
  3725. && (++cli->which > cli->a->n)) {
  3726. cli->callid = ast_malloc(pj_strlen(callid) + 1);
  3727. if (cli->callid) {
  3728. ast_copy_pj_str(cli->callid, callid, pj_strlen(callid) + 1);
  3729. }
  3730. return -1;
  3731. }
  3732. return 0;
  3733. }
  3734. static int cli_complete_subscription_inbound(struct sip_subscription_tree *sub_tree, void *arg)
  3735. {
  3736. return sub_tree->role == AST_SIP_NOTIFIER
  3737. ? cli_complete_subscription_common(sub_tree, arg) : 0;
  3738. }
  3739. static int cli_complete_subscription_outbound(struct sip_subscription_tree *sub_tree, void *arg)
  3740. {
  3741. return sub_tree->role == AST_SIP_SUBSCRIBER
  3742. ? cli_complete_subscription_common(sub_tree, arg) : 0;
  3743. }
  3744. static char *cli_complete_subscription_callid(struct ast_cli_args *a)
  3745. {
  3746. struct cli_sub_complete_parms cli;
  3747. on_subscription_t on_subscription;
  3748. if (a->pos != 4) {
  3749. return NULL;
  3750. }
  3751. if (!strcasecmp(a->argv[3], "inbound")) {
  3752. on_subscription = cli_complete_subscription_inbound;
  3753. } else if (!strcasecmp(a->argv[3], "outbound")) {
  3754. on_subscription = cli_complete_subscription_outbound;
  3755. } else {
  3756. /* Should never get here */
  3757. ast_assert(0);
  3758. return NULL;
  3759. }
  3760. cli.a = a;
  3761. cli.callid = NULL;
  3762. cli.wordlen = strlen(a->word);
  3763. cli.which = 0;
  3764. for_each_subscription(on_subscription, &cli);
  3765. return cli.callid;
  3766. }
  3767. static unsigned int cli_subscription_expiry(struct sip_subscription_tree *sub_tree)
  3768. {
  3769. int expiry;
  3770. expiry = sub_tree->persistence
  3771. ? ast_tvdiff_ms(sub_tree->persistence->expires, ast_tvnow()) / 1000
  3772. : 0;
  3773. if (expiry < 0) {
  3774. /* Subscription expired */
  3775. expiry = 0;
  3776. }
  3777. return expiry;
  3778. }
  3779. static int cli_show_subscription_common(struct sip_subscription_tree *sub_tree, struct cli_sub_parms *cli)
  3780. {
  3781. const char *callid = (const char *) cli->buf;/* Member repurposed to pass in callid */
  3782. pj_str_t *sub_callid;
  3783. struct ast_str *buf;
  3784. char *src;
  3785. char *dest;
  3786. char *key;
  3787. char *value;
  3788. char *value_end;
  3789. int key_len;
  3790. int key_filler_width;
  3791. int value_len;
  3792. if (!sub_tree->dlg) {
  3793. return 0;
  3794. }
  3795. sub_callid = &sub_tree->dlg->call_id->id;
  3796. if (pj_strcmp2(sub_callid, callid)) {
  3797. return 0;
  3798. }
  3799. buf = ast_str_create(512);
  3800. if (!buf) {
  3801. return -1;
  3802. }
  3803. ast_cli(cli->a->fd,
  3804. "%-20s: %s\n"
  3805. "===========================================================================\n",
  3806. "ParameterName", "ParameterValue");
  3807. ast_str_append(&buf, 0, "Resource: %s\n", sub_tree->root->resource);
  3808. ast_str_append(&buf, 0, "Event: %s\n", sub_tree->root->handler->event_name);
  3809. ast_str_append(&buf, 0, "Expiry: %u\n", cli_subscription_expiry(sub_tree));
  3810. sip_subscription_to_ami(sub_tree, &buf);
  3811. /* Convert AMI \r\n to \n line terminators. */
  3812. src = strchr(ast_str_buffer(buf), '\r');
  3813. if (src) {
  3814. dest = src;
  3815. ++src;
  3816. while (*src) {
  3817. if (*src == '\r') {
  3818. ++src;
  3819. continue;
  3820. }
  3821. *dest++ = *src++;
  3822. }
  3823. *dest = '\0';
  3824. ast_str_update(buf);
  3825. }
  3826. /* Reformat AMI key value pairs to pretty columns */
  3827. key = ast_str_buffer(buf);
  3828. do {
  3829. value = strchr(key, ':');
  3830. if (!value) {
  3831. break;
  3832. }
  3833. value_end = strchr(value, '\n');
  3834. if (!value_end) {
  3835. break;
  3836. }
  3837. /* Calculate field lengths */
  3838. key_len = value - key;
  3839. key_filler_width = 20 - key_len;
  3840. if (key_filler_width < 0) {
  3841. key_filler_width = 0;
  3842. }
  3843. value_len = value_end - value;
  3844. ast_cli(cli->a->fd, "%.*s%*s%.*s\n",
  3845. key_len, key, key_filler_width, "",
  3846. value_len, value);
  3847. key = value_end + 1;
  3848. } while (*key);
  3849. ast_cli(cli->a->fd, "\n");
  3850. ast_free(buf);
  3851. return -1;
  3852. }
  3853. static int cli_show_subscription_inbound(struct sip_subscription_tree *sub_tree, void *arg)
  3854. {
  3855. return sub_tree->role == AST_SIP_NOTIFIER
  3856. ? cli_show_subscription_common(sub_tree, arg) : 0;
  3857. }
  3858. static int cli_show_subscription_outbound(struct sip_subscription_tree *sub_tree, void *arg)
  3859. {
  3860. return sub_tree->role == AST_SIP_SUBSCRIBER
  3861. ? cli_show_subscription_common(sub_tree, arg) : 0;
  3862. }
  3863. static char *cli_show_subscription_inout(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3864. {
  3865. on_subscription_t on_subscription;
  3866. struct cli_sub_parms cli;
  3867. switch (cmd) {
  3868. case CLI_INIT:
  3869. e->command = "pjsip show subscription {inbound|outbound}";
  3870. e->usage = "Usage:\n"
  3871. " pjsip show subscription inbound <call-id>\n"
  3872. " pjsip show subscription outbound <call-id>\n"
  3873. " Show active subscription with the dialog call-id\n";
  3874. return NULL;
  3875. case CLI_GENERATE:
  3876. return cli_complete_subscription_callid(a);
  3877. }
  3878. if (a->argc != 5) {
  3879. return CLI_SHOWUSAGE;
  3880. }
  3881. if (!strcasecmp(a->argv[3], "inbound")) {
  3882. on_subscription = cli_show_subscription_inbound;
  3883. } else if (!strcasecmp(a->argv[3], "outbound")) {
  3884. on_subscription = cli_show_subscription_outbound;
  3885. } else {
  3886. /* Should never get here */
  3887. ast_assert(0);
  3888. return NULL;
  3889. }
  3890. /* Find the subscription with the specified call-id */
  3891. cli.a = a;
  3892. cli.e = e;
  3893. cli.buf = (void *) a->argv[4];/* Repurpose the buf member to pass in callid */
  3894. for_each_subscription(on_subscription, &cli);
  3895. return CLI_SUCCESS;
  3896. }
  3897. #define CLI_SHOW_SUB_FORMAT_HEADER \
  3898. "Endpoint: <Endpoint/Caller-ID.............................................>\n" \
  3899. "Resource: <Resource/Event.................................................>\n" \
  3900. " Expiry: <Expiry> <Call-id..............................................>\n" \
  3901. "===========================================================================\n\n"
  3902. #define CLI_SHOW_SUB_FORMAT_ENTRY \
  3903. "Endpoint: %s/%s\n" \
  3904. "Resource: %s/%s\n" \
  3905. " Expiry: %8d %s\n\n"
  3906. static int cli_show_subscriptions_detail(struct sip_subscription_tree *sub_tree, struct cli_sub_parms *cli)
  3907. {
  3908. char caller_id[256];
  3909. char callid[256];
  3910. ast_callerid_merge(caller_id, sizeof(caller_id),
  3911. S_COR(sub_tree->endpoint->id.self.name.valid,
  3912. sub_tree->endpoint->id.self.name.str, NULL),
  3913. S_COR(sub_tree->endpoint->id.self.number.valid,
  3914. sub_tree->endpoint->id.self.number.str, NULL),
  3915. "<none>");
  3916. /* Call-id */
  3917. if (sub_tree->dlg) {
  3918. ast_copy_pj_str(callid, &sub_tree->dlg->call_id->id, sizeof(callid));
  3919. } else {
  3920. ast_copy_string(callid, "<unknown>", sizeof(callid));
  3921. }
  3922. ast_str_set(&cli->buf, 0, CLI_SHOW_SUB_FORMAT_ENTRY,
  3923. ast_sorcery_object_get_id(sub_tree->endpoint), caller_id,
  3924. sub_tree->root->resource, sub_tree->root->handler->event_name,
  3925. cli_subscription_expiry(sub_tree), callid);
  3926. if (cli->like) {
  3927. if (regexec(cli->like, ast_str_buffer(cli->buf), 0, NULL, 0)) {
  3928. /* Output line did not match the regex */
  3929. return 0;
  3930. }
  3931. }
  3932. ast_cli(cli->a->fd, "%s", ast_str_buffer(cli->buf));
  3933. ++cli->count;
  3934. return 0;
  3935. }
  3936. static int cli_show_subscriptions_inbound(struct sip_subscription_tree *sub_tree, void *arg)
  3937. {
  3938. return sub_tree->role == AST_SIP_NOTIFIER
  3939. ? cli_show_subscriptions_detail(sub_tree, arg) : 0;
  3940. }
  3941. static int cli_show_subscriptions_outbound(struct sip_subscription_tree *sub_tree, void *arg)
  3942. {
  3943. return sub_tree->role == AST_SIP_SUBSCRIBER
  3944. ? cli_show_subscriptions_detail(sub_tree, arg) : 0;
  3945. }
  3946. static char *cli_show_subscriptions_inout(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3947. {
  3948. on_subscription_t on_subscription;
  3949. struct cli_sub_parms cli;
  3950. regex_t like;
  3951. const char *regex;
  3952. switch (cmd) {
  3953. case CLI_INIT:
  3954. e->command = "pjsip show subscriptions {inbound|outbound} [like]";
  3955. e->usage = "Usage:\n"
  3956. " pjsip show subscriptions inbound [like <regex>]\n"
  3957. " Show active inbound subscriptions\n"
  3958. " pjsip show subscriptions outbound [like <regex>]\n"
  3959. " Show active outbound subscriptions\n"
  3960. "\n"
  3961. " The regex selects a subscriptions output that matches.\n"
  3962. " i.e., All output lines for a subscription are checked\n"
  3963. " as a block by the regex.\n";
  3964. return NULL;
  3965. case CLI_GENERATE:
  3966. return NULL;
  3967. }
  3968. if (a->argc != 4 && a->argc != 6) {
  3969. return CLI_SHOWUSAGE;
  3970. }
  3971. if (!strcasecmp(a->argv[3], "inbound")) {
  3972. on_subscription = cli_show_subscriptions_inbound;
  3973. } else if (!strcasecmp(a->argv[3], "outbound")) {
  3974. on_subscription = cli_show_subscriptions_outbound;
  3975. } else {
  3976. /* Should never get here */
  3977. ast_assert(0);
  3978. return CLI_SHOWUSAGE;
  3979. }
  3980. if (a->argc == 6) {
  3981. int rc;
  3982. if (strcasecmp(a->argv[4], "like")) {
  3983. return CLI_SHOWUSAGE;
  3984. }
  3985. /* Setup regular expression */
  3986. memset(&like, 0, sizeof(like));
  3987. cli.like = &like;
  3988. regex = a->argv[5];
  3989. rc = regcomp(cli.like, regex, REG_EXTENDED | REG_NOSUB);
  3990. if (rc) {
  3991. char *regerr = ast_alloca(MAX_REGEX_ERROR_LEN);
  3992. regerror(rc, cli.like, regerr, MAX_REGEX_ERROR_LEN);
  3993. ast_cli(a->fd, "Regular expression '%s' failed to compile: %s\n",
  3994. regex, regerr);
  3995. return CLI_FAILURE;
  3996. }
  3997. } else {
  3998. cli.like = NULL;
  3999. regex = NULL;
  4000. }
  4001. cli.a = a;
  4002. cli.e = e;
  4003. cli.count = 0;
  4004. cli.buf = ast_str_create(256);
  4005. if (!cli.buf) {
  4006. if (cli.like) {
  4007. regfree(cli.like);
  4008. }
  4009. return CLI_FAILURE;
  4010. }
  4011. ast_cli(a->fd, CLI_SHOW_SUB_FORMAT_HEADER);
  4012. for_each_subscription(on_subscription, &cli);
  4013. ast_cli(a->fd, "%d active subscriptions%s%s%s\n",
  4014. cli.count,
  4015. regex ? " matched \"" : "",
  4016. regex ?: "",
  4017. regex ? "\"" : "");
  4018. ast_free(cli.buf);
  4019. if (cli.like) {
  4020. regfree(cli.like);
  4021. }
  4022. return CLI_SUCCESS;
  4023. }
  4024. #define CLI_LIST_SUB_FORMAT_HEADER "%-30.30s %-30.30s %6.6s %s\n"
  4025. #define CLI_LIST_SUB_FORMAT_ENTRY "%-30.30s %-30.30s %6d %s\n"
  4026. static int cli_list_subscriptions_detail(struct sip_subscription_tree *sub_tree, struct cli_sub_parms *cli)
  4027. {
  4028. char ep_cid_buf[50];
  4029. char res_evt_buf[50];
  4030. char callid[256];
  4031. /* Endpoint/CID column */
  4032. snprintf(ep_cid_buf, sizeof(ep_cid_buf), "%s/%s",
  4033. ast_sorcery_object_get_id(sub_tree->endpoint),
  4034. S_COR(sub_tree->endpoint->id.self.name.valid, sub_tree->endpoint->id.self.name.str,
  4035. S_COR(sub_tree->endpoint->id.self.number.valid,
  4036. sub_tree->endpoint->id.self.number.str, "<none>")));
  4037. /* Resource/Event column */
  4038. snprintf(res_evt_buf, sizeof(res_evt_buf), "%s/%s",
  4039. sub_tree->root->resource,
  4040. sub_tree->root->handler->event_name);
  4041. /* Call-id column */
  4042. if (sub_tree->dlg) {
  4043. ast_copy_pj_str(callid, &sub_tree->dlg->call_id->id, sizeof(callid));
  4044. } else {
  4045. ast_copy_string(callid, "<unknown>", sizeof(callid));
  4046. }
  4047. ast_str_set(&cli->buf, 0, CLI_LIST_SUB_FORMAT_ENTRY,
  4048. ep_cid_buf,
  4049. res_evt_buf,
  4050. cli_subscription_expiry(sub_tree),
  4051. callid);
  4052. if (cli->like) {
  4053. if (regexec(cli->like, ast_str_buffer(cli->buf), 0, NULL, 0)) {
  4054. /* Output line did not match the regex */
  4055. return 0;
  4056. }
  4057. }
  4058. ast_cli(cli->a->fd, "%s", ast_str_buffer(cli->buf));
  4059. ++cli->count;
  4060. return 0;
  4061. }
  4062. static int cli_list_subscriptions_inbound(struct sip_subscription_tree *sub_tree, void *arg)
  4063. {
  4064. return sub_tree->role == AST_SIP_NOTIFIER
  4065. ? cli_list_subscriptions_detail(sub_tree, arg) : 0;
  4066. }
  4067. static int cli_list_subscriptions_outbound(struct sip_subscription_tree *sub_tree, void *arg)
  4068. {
  4069. return sub_tree->role == AST_SIP_SUBSCRIBER
  4070. ? cli_list_subscriptions_detail(sub_tree, arg) : 0;
  4071. }
  4072. static char *cli_list_subscriptions_inout(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  4073. {
  4074. on_subscription_t on_subscription;
  4075. struct cli_sub_parms cli;
  4076. regex_t like;
  4077. const char *regex;
  4078. switch (cmd) {
  4079. case CLI_INIT:
  4080. e->command = "pjsip list subscriptions {inbound|outbound} [like]";
  4081. e->usage = "Usage:\n"
  4082. " pjsip list subscriptions inbound [like <regex>]\n"
  4083. " List active inbound subscriptions\n"
  4084. " pjsip list subscriptions outbound [like <regex>]\n"
  4085. " List active outbound subscriptions\n"
  4086. "\n"
  4087. " The regex selects output lines that match.\n";
  4088. return NULL;
  4089. case CLI_GENERATE:
  4090. return NULL;
  4091. }
  4092. if (a->argc != 4 && a->argc != 6) {
  4093. return CLI_SHOWUSAGE;
  4094. }
  4095. if (!strcasecmp(a->argv[3], "inbound")) {
  4096. on_subscription = cli_list_subscriptions_inbound;
  4097. } else if (!strcasecmp(a->argv[3], "outbound")) {
  4098. on_subscription = cli_list_subscriptions_outbound;
  4099. } else {
  4100. /* Should never get here */
  4101. ast_assert(0);
  4102. return CLI_SHOWUSAGE;
  4103. }
  4104. if (a->argc == 6) {
  4105. int rc;
  4106. if (strcasecmp(a->argv[4], "like")) {
  4107. return CLI_SHOWUSAGE;
  4108. }
  4109. /* Setup regular expression */
  4110. memset(&like, 0, sizeof(like));
  4111. cli.like = &like;
  4112. regex = a->argv[5];
  4113. rc = regcomp(cli.like, regex, REG_EXTENDED | REG_NOSUB);
  4114. if (rc) {
  4115. char *regerr = ast_alloca(MAX_REGEX_ERROR_LEN);
  4116. regerror(rc, cli.like, regerr, MAX_REGEX_ERROR_LEN);
  4117. ast_cli(a->fd, "Regular expression '%s' failed to compile: %s\n",
  4118. regex, regerr);
  4119. return CLI_FAILURE;
  4120. }
  4121. } else {
  4122. cli.like = NULL;
  4123. regex = NULL;
  4124. }
  4125. cli.a = a;
  4126. cli.e = e;
  4127. cli.count = 0;
  4128. cli.buf = ast_str_create(256);
  4129. if (!cli.buf) {
  4130. if (cli.like) {
  4131. regfree(cli.like);
  4132. }
  4133. return CLI_FAILURE;
  4134. }
  4135. ast_cli(a->fd, CLI_LIST_SUB_FORMAT_HEADER,
  4136. "Endpoint/CLI", "Resource/Event", "Expiry", "Call-id");
  4137. for_each_subscription(on_subscription, &cli);
  4138. ast_cli(a->fd, "\n%d active subscriptions%s%s%s\n",
  4139. cli.count,
  4140. regex ? " matched \"" : "",
  4141. regex ?: "",
  4142. regex ? "\"" : "");
  4143. ast_free(cli.buf);
  4144. if (cli.like) {
  4145. regfree(cli.like);
  4146. }
  4147. return CLI_SUCCESS;
  4148. }
  4149. static struct ast_cli_entry cli_commands[] = {
  4150. AST_CLI_DEFINE(cli_list_subscriptions_inout, "List active inbound/outbound subscriptions"),
  4151. AST_CLI_DEFINE(cli_show_subscription_inout, "Show active subscription details"),
  4152. AST_CLI_DEFINE(cli_show_subscriptions_inout, "Show active inbound/outbound subscriptions"),
  4153. };
  4154. static int persistence_endpoint_str2struct(const struct aco_option *opt, struct ast_variable *var, void *obj)
  4155. {
  4156. struct subscription_persistence *persistence = obj;
  4157. persistence->endpoint = ast_strdup(var->value);
  4158. return 0;
  4159. }
  4160. static int persistence_endpoint_struct2str(const void *obj, const intptr_t *args, char **buf)
  4161. {
  4162. const struct subscription_persistence *persistence = obj;
  4163. *buf = ast_strdup(persistence->endpoint);
  4164. return 0;
  4165. }
  4166. static int persistence_tag_str2struct(const struct aco_option *opt, struct ast_variable *var, void *obj)
  4167. {
  4168. struct subscription_persistence *persistence = obj;
  4169. persistence->tag = ast_strdup(var->value);
  4170. return 0;
  4171. }
  4172. static int persistence_tag_struct2str(const void *obj, const intptr_t *args, char **buf)
  4173. {
  4174. const struct subscription_persistence *persistence = obj;
  4175. *buf = ast_strdup(persistence->tag);
  4176. return 0;
  4177. }
  4178. static int persistence_generator_data_str2struct(const struct aco_option *opt, struct ast_variable *var, void *obj)
  4179. {
  4180. struct subscription_persistence *persistence = obj;
  4181. struct ast_json_error error;
  4182. /* We tolerate a failure of the JSON to load and instead start fresh, since this field
  4183. * originates from the persistence code and not a user.
  4184. */
  4185. persistence->generator_data = ast_json_load_string(var->value, &error);
  4186. return 0;
  4187. }
  4188. static int persistence_generator_data_struct2str(const void *obj, const intptr_t *args, char **buf)
  4189. {
  4190. const struct subscription_persistence *persistence = obj;
  4191. char *value;
  4192. if (!persistence->generator_data) {
  4193. return 0;
  4194. }
  4195. value = ast_json_dump_string(persistence->generator_data);
  4196. if (!value) {
  4197. return -1;
  4198. }
  4199. *buf = ast_strdup(value);
  4200. ast_json_free(value);
  4201. return 0;
  4202. }
  4203. static int persistence_expires_str2struct(const struct aco_option *opt, struct ast_variable *var, void *obj)
  4204. {
  4205. struct subscription_persistence *persistence = obj;
  4206. return ast_get_timeval(var->value, &persistence->expires, ast_tv(0, 0), NULL);
  4207. }
  4208. static int persistence_expires_struct2str(const void *obj, const intptr_t *args, char **buf)
  4209. {
  4210. const struct subscription_persistence *persistence = obj;
  4211. char secs[AST_TIME_T_LEN];
  4212. ast_time_t_to_string(persistence->expires.tv_sec, secs, sizeof(secs));
  4213. return (ast_asprintf(buf, "%s", secs) < 0) ? -1 : 0;
  4214. }
  4215. #define RESOURCE_LIST_INIT_SIZE 4
  4216. static void resource_list_destructor(void *obj)
  4217. {
  4218. struct resource_list *list = obj;
  4219. int i;
  4220. for (i = 0; i < AST_VECTOR_SIZE(&list->items); ++i) {
  4221. ast_free((char *) AST_VECTOR_GET(&list->items, i));
  4222. }
  4223. AST_VECTOR_FREE(&list->items);
  4224. }
  4225. static void *resource_list_alloc(const char *name)
  4226. {
  4227. struct resource_list *list;
  4228. list = ast_sorcery_generic_alloc(sizeof(*list), resource_list_destructor);
  4229. if (!list) {
  4230. return NULL;
  4231. }
  4232. if (AST_VECTOR_INIT(&list->items, RESOURCE_LIST_INIT_SIZE)) {
  4233. ao2_cleanup(list);
  4234. return NULL;
  4235. }
  4236. return list;
  4237. }
  4238. static int item_in_vector(const struct resource_list *list, const char *item)
  4239. {
  4240. int i;
  4241. for (i = 0; i < AST_VECTOR_SIZE(&list->items); ++i) {
  4242. if (!strcmp(item, AST_VECTOR_GET(&list->items, i))) {
  4243. return 1;
  4244. }
  4245. }
  4246. return 0;
  4247. }
  4248. static int list_item_handler(const struct aco_option *opt,
  4249. struct ast_variable *var, void *obj)
  4250. {
  4251. struct resource_list *list = obj;
  4252. char *items = ast_strdupa(var->value);
  4253. char *item;
  4254. while ((item = ast_strip(strsep(&items, ",")))) {
  4255. if (ast_strlen_zero(item)) {
  4256. continue;
  4257. }
  4258. if (item_in_vector(list, item)) {
  4259. ast_log(LOG_WARNING, "Ignoring duplicated list item '%s'\n", item);
  4260. continue;
  4261. }
  4262. item = ast_strdup(item);
  4263. if (!item || AST_VECTOR_APPEND(&list->items, item)) {
  4264. ast_free(item);
  4265. return -1;
  4266. }
  4267. }
  4268. return 0;
  4269. }
  4270. static int list_item_to_str(const void *obj, const intptr_t *args, char **buf)
  4271. {
  4272. const struct resource_list *list = obj;
  4273. int i;
  4274. struct ast_str *str = ast_str_create(32);
  4275. for (i = 0; i < AST_VECTOR_SIZE(&list->items); ++i) {
  4276. ast_str_append(&str, 0, "%s,", AST_VECTOR_GET(&list->items, i));
  4277. }
  4278. /* Chop off trailing comma */
  4279. ast_str_truncate(str, -1);
  4280. *buf = ast_strdup(ast_str_buffer(str));
  4281. ast_free(str);
  4282. return 0;
  4283. }
  4284. static int resource_list_apply_handler(const struct ast_sorcery *sorcery, void *obj)
  4285. {
  4286. struct resource_list *list = obj;
  4287. if (ast_strlen_zero(list->event)) {
  4288. ast_log(LOG_WARNING, "Resource list '%s' has no event set\n",
  4289. ast_sorcery_object_get_id(list));
  4290. return -1;
  4291. }
  4292. if (AST_VECTOR_SIZE(&list->items) == 0) {
  4293. ast_log(LOG_WARNING, "Resource list '%s' has no list items\n",
  4294. ast_sorcery_object_get_id(list));
  4295. return -1;
  4296. }
  4297. return 0;
  4298. }
  4299. static int apply_list_configuration(struct ast_sorcery *sorcery)
  4300. {
  4301. ast_sorcery_apply_default(sorcery, "resource_list", "config",
  4302. "pjsip.conf,criteria=type=resource_list");
  4303. if (ast_sorcery_object_register(sorcery, "resource_list", resource_list_alloc,
  4304. NULL, resource_list_apply_handler)) {
  4305. return -1;
  4306. }
  4307. ast_sorcery_object_field_register(sorcery, "resource_list", "type", "",
  4308. OPT_NOOP_T, 0, 0);
  4309. ast_sorcery_object_field_register(sorcery, "resource_list", "event", "",
  4310. OPT_CHAR_ARRAY_T, 1, CHARFLDSET(struct resource_list, event));
  4311. ast_sorcery_object_field_register(sorcery, "resource_list", "full_state", "no",
  4312. OPT_BOOL_T, 1, FLDSET(struct resource_list, full_state));
  4313. ast_sorcery_object_field_register(sorcery, "resource_list", "notification_batch_interval",
  4314. "0", OPT_UINT_T, 0, FLDSET(struct resource_list, notification_batch_interval));
  4315. ast_sorcery_object_field_register_custom(sorcery, "resource_list", "list_item",
  4316. "", list_item_handler, list_item_to_str, NULL, 0, 0);
  4317. ast_sorcery_object_field_register(sorcery, "resource_list", "resource_display_name", "no",
  4318. OPT_BOOL_T, 1, FLDSET(struct resource_list, resource_display_name));
  4319. ast_sorcery_reload_object(sorcery, "resource_list");
  4320. return 0;
  4321. }
  4322. #ifdef TEST_FRAMEWORK
  4323. /*!
  4324. * \brief "bad" resources
  4325. *
  4326. * These are resources that the test handler will reject subscriptions to.
  4327. */
  4328. const char *bad_resources[] = {
  4329. "coconut",
  4330. "cilantro",
  4331. "olive",
  4332. "cheese",
  4333. };
  4334. /*!
  4335. * \brief new_subscribe callback for unit tests
  4336. *
  4337. * Will give a 200 OK response to any resource except the "bad" ones.
  4338. */
  4339. static int test_new_subscribe(struct ast_sip_endpoint *endpoint, const char *resource)
  4340. {
  4341. int i;
  4342. for (i = 0; i < ARRAY_LEN(bad_resources); ++i) {
  4343. if (!strcmp(resource, bad_resources[i])) {
  4344. return 400;
  4345. }
  4346. }
  4347. return 200;
  4348. }
  4349. /*!
  4350. * \brief Subscription notifier for unit tests.
  4351. *
  4352. * Since unit tests are only concerned with building a resource tree,
  4353. * only the new_subscribe callback needs to be defined.
  4354. */
  4355. struct ast_sip_notifier test_notifier = {
  4356. .new_subscribe = test_new_subscribe,
  4357. };
  4358. /*!
  4359. * \brief Subscription handler for unit tests.
  4360. */
  4361. struct ast_sip_subscription_handler test_handler = {
  4362. .event_name = "test",
  4363. .body_type = "",
  4364. .notifier = &test_notifier,
  4365. };
  4366. /*!
  4367. * \brief Set properties on an allocated resource list
  4368. *
  4369. * \param list The list to set details on.
  4370. * \param event The list's event.
  4371. * \param resources Array of resources to add to the list.
  4372. * \param num_resources Number of resources in the array.
  4373. * \retval 0 Success
  4374. * \retval non-zero Failure
  4375. */
  4376. static int populate_list(struct resource_list *list, const char *event, const char **resources, size_t num_resources)
  4377. {
  4378. int i;
  4379. ast_copy_string(list->event, event, sizeof(list->event));
  4380. for (i = 0; i < num_resources; ++i) {
  4381. char *resource = ast_strdup(resources[i]);
  4382. if (!resource || AST_VECTOR_APPEND(&list->items, resource)) {
  4383. ast_free(resource);
  4384. return -1;
  4385. }
  4386. }
  4387. return 0;
  4388. }
  4389. /*!
  4390. * \brief RAII callback to destroy a resource list
  4391. */
  4392. static void cleanup_resource_list(struct resource_list *list)
  4393. {
  4394. if (!list) {
  4395. return;
  4396. }
  4397. ast_sorcery_delete(ast_sip_get_sorcery(), list);
  4398. ao2_cleanup(list);
  4399. }
  4400. /*!
  4401. * \brief allocate a resource list, store it in sorcery, and set its details
  4402. *
  4403. * \param test The unit test. Used for logging status messages.
  4404. * \param list_name The name of the list to create.
  4405. * \param event The event the list services
  4406. * \param resources Array of resources to apply to the list
  4407. * \param num_resources The number of resources in the array
  4408. * \retval NULL Failed to allocate or populate list
  4409. * \retval non-NULL The created list
  4410. */
  4411. static struct resource_list *create_resource_list(struct ast_test *test,
  4412. const char *list_name, const char *event, const char **resources, size_t num_resources)
  4413. {
  4414. struct resource_list *list;
  4415. list = ast_sorcery_alloc(ast_sip_get_sorcery(), "resource_list", list_name);
  4416. if (!list) {
  4417. ast_test_status_update(test, "Could not allocate resource list in sorcery\n");
  4418. return NULL;
  4419. }
  4420. if (ast_sorcery_create(ast_sip_get_sorcery(), list)) {
  4421. ast_test_status_update(test, "Could not store the resource list in sorcery\n");
  4422. ao2_cleanup(list);
  4423. return NULL;
  4424. }
  4425. if (populate_list(list, event, resources, num_resources)) {
  4426. ast_test_status_update(test, "Could not add resources to the resource list\n");
  4427. cleanup_resource_list(list);
  4428. return NULL;
  4429. }
  4430. return list;
  4431. }
  4432. /*!
  4433. * \brief Check the integrity of a tree node against a set of resources.
  4434. *
  4435. * The tree node's resources must be in the same order as the resources in
  4436. * the supplied resources array. Because of this constraint, tests can misrepresent
  4437. * the size of the resources array as being smaller than it really is if resources
  4438. * at the end of the array should not be present in the tree node.
  4439. *
  4440. * \param test The unit test. Used for printing status messages.
  4441. * \param node The constructed tree node whose integrity is under question.
  4442. * \param resources Array of expected resource values
  4443. * \param num_resources The number of resources to check in the array.
  4444. */
  4445. static int check_node(struct ast_test *test, struct tree_node *node,
  4446. const char **resources, size_t num_resources)
  4447. {
  4448. int i;
  4449. if (AST_VECTOR_SIZE(&node->children) != num_resources) {
  4450. ast_test_status_update(test, "Unexpected number of resources in tree. Expected %zu, got %zu\n",
  4451. num_resources, AST_VECTOR_SIZE(&node->children));
  4452. return -1;
  4453. }
  4454. for (i = 0; i < num_resources; ++i) {
  4455. if (strcmp(resources[i], AST_VECTOR_GET(&node->children, i)->resource)) {
  4456. ast_test_status_update(test, "Mismatched resources. Expected '%s' but got '%s'\n",
  4457. resources[i], AST_VECTOR_GET(&node->children, i)->resource);
  4458. return -1;
  4459. }
  4460. }
  4461. return 0;
  4462. }
  4463. /*!
  4464. * \brief RAII_VAR callback to destroy an allocated resource tree
  4465. */
  4466. static void test_resource_tree_destroy(struct resource_tree *tree)
  4467. {
  4468. resource_tree_destroy(tree);
  4469. ast_free(tree);
  4470. }
  4471. static int ineligible_configuration(void)
  4472. {
  4473. struct ast_config *config;
  4474. struct ast_flags flags = {0,};
  4475. const char *value;
  4476. config = ast_config_load("sorcery.conf", flags);
  4477. if (!config) {
  4478. return 1;
  4479. }
  4480. value = ast_variable_retrieve(config, "res_pjsip_pubsub", "resource_list");
  4481. if (ast_strlen_zero(value)) {
  4482. ast_config_destroy(config);
  4483. return 1;
  4484. }
  4485. if (strcasecmp(value, "memory") && strcasecmp(value, "astdb")) {
  4486. ast_config_destroy(config);
  4487. return 1;
  4488. }
  4489. return 0;
  4490. }
  4491. AST_TEST_DEFINE(resource_tree)
  4492. {
  4493. RAII_VAR(struct resource_list *, list, NULL, cleanup_resource_list);
  4494. RAII_VAR(struct resource_tree *, tree, NULL, test_resource_tree_destroy);
  4495. const char *resources[] = {
  4496. "huey",
  4497. "dewey",
  4498. "louie",
  4499. };
  4500. int resp;
  4501. switch (cmd) {
  4502. case TEST_INIT:
  4503. info->name = "resource_tree";
  4504. info->category = "/res/res_pjsip_pubsub/";
  4505. info->summary = "Basic resource tree integrity check";
  4506. info->description =
  4507. "Create a resource list and ensure that our attempt to build a tree works as expected.";
  4508. return AST_TEST_NOT_RUN;
  4509. case TEST_EXECUTE:
  4510. break;
  4511. }
  4512. if (ineligible_configuration()) {
  4513. ast_test_status_update(test, "Ineligible configuration for this test. Please add a "
  4514. "'res_pjsip_pubsub' section to sorcery.conf, and set 'resource_list=memory'\n");
  4515. return AST_TEST_NOT_RUN;
  4516. }
  4517. list = create_resource_list(test, "foo", "test", resources, ARRAY_LEN(resources));
  4518. if (!list) {
  4519. return AST_TEST_FAIL;
  4520. }
  4521. tree = ast_calloc(1, sizeof(*tree));
  4522. resp = build_resource_tree(NULL, &test_handler, "foo", tree, 1, NULL);
  4523. if (resp != 200) {
  4524. ast_test_status_update(test, "Unexpected response %d when building resource tree\n", resp);
  4525. return AST_TEST_FAIL;
  4526. }
  4527. if (!tree->root) {
  4528. ast_test_status_update(test, "Resource tree has no root\n");
  4529. return AST_TEST_FAIL;
  4530. }
  4531. if (check_node(test, tree->root, resources, ARRAY_LEN(resources))) {
  4532. return AST_TEST_FAIL;
  4533. }
  4534. return AST_TEST_PASS;
  4535. }
  4536. AST_TEST_DEFINE(complex_resource_tree)
  4537. {
  4538. RAII_VAR(struct resource_list *, list_1, NULL, cleanup_resource_list);
  4539. RAII_VAR(struct resource_list *, list_2, NULL, cleanup_resource_list);
  4540. RAII_VAR(struct resource_tree *, tree, NULL, test_resource_tree_destroy);
  4541. const char *resources_1[] = {
  4542. "huey",
  4543. "dewey",
  4544. "louie",
  4545. "dwarves",
  4546. };
  4547. const char *resources_2[] = {
  4548. "happy",
  4549. "grumpy",
  4550. "doc",
  4551. "bashful",
  4552. "dopey",
  4553. "sneezy",
  4554. "sleepy",
  4555. };
  4556. int resp;
  4557. struct tree_node *node;
  4558. switch (cmd) {
  4559. case TEST_INIT:
  4560. info->name = "complex_resource_tree";
  4561. info->category = "/res/res_pjsip_pubsub/";
  4562. info->summary = "Complex resource tree integrity check";
  4563. info->description =
  4564. "Create a complex resource list and ensure that our attempt to build a tree works as expected.";
  4565. return AST_TEST_NOT_RUN;
  4566. case TEST_EXECUTE:
  4567. break;
  4568. }
  4569. if (ineligible_configuration()) {
  4570. ast_test_status_update(test, "Ineligible configuration for this test. Please add a "
  4571. "'res_pjsip_pubsub' section to sorcery.conf, and set 'resource_list=memory'\n");
  4572. return AST_TEST_NOT_RUN;
  4573. }
  4574. list_1 = create_resource_list(test, "foo", "test", resources_1, ARRAY_LEN(resources_1));
  4575. if (!list_1) {
  4576. return AST_TEST_FAIL;
  4577. }
  4578. list_2 = create_resource_list(test, "dwarves", "test", resources_2, ARRAY_LEN(resources_2));
  4579. if (!list_2) {
  4580. return AST_TEST_FAIL;
  4581. }
  4582. tree = ast_calloc(1, sizeof(*tree));
  4583. resp = build_resource_tree(NULL, &test_handler, "foo", tree, 1, NULL);
  4584. if (resp != 200) {
  4585. ast_test_status_update(test, "Unexpected response %d when building resource tree\n", resp);
  4586. return AST_TEST_FAIL;
  4587. }
  4588. if (!tree->root) {
  4589. ast_test_status_update(test, "Resource tree has no root\n");
  4590. return AST_TEST_FAIL;
  4591. }
  4592. node = tree->root;
  4593. if (check_node(test, node, resources_1, ARRAY_LEN(resources_1))) {
  4594. return AST_TEST_FAIL;
  4595. }
  4596. /* The embedded list is at index 3 in the root node's children */
  4597. node = AST_VECTOR_GET(&node->children, 3);
  4598. if (check_node(test, node, resources_2, ARRAY_LEN(resources_2))) {
  4599. return AST_TEST_FAIL;
  4600. }
  4601. return AST_TEST_PASS;
  4602. }
  4603. AST_TEST_DEFINE(bad_resource)
  4604. {
  4605. RAII_VAR(struct resource_list *, list, NULL, cleanup_resource_list);
  4606. RAII_VAR(struct resource_tree *, tree, NULL, test_resource_tree_destroy);
  4607. const char *resources[] = {
  4608. "huey",
  4609. "dewey",
  4610. "louie",
  4611. "coconut", /* A "bad" resource */
  4612. };
  4613. int resp;
  4614. switch (cmd) {
  4615. case TEST_INIT:
  4616. info->name = "bad_resource";
  4617. info->category = "/res/res_pjsip_pubsub/";
  4618. info->summary = "Ensure bad resources do not end up in the tree";
  4619. info->description =
  4620. "Create a resource list with a single bad resource. Ensure the bad resource does not end up in the tree.";
  4621. return AST_TEST_NOT_RUN;
  4622. case TEST_EXECUTE:
  4623. break;
  4624. }
  4625. if (ineligible_configuration()) {
  4626. ast_test_status_update(test, "Ineligible configuration for this test. Please add a "
  4627. "'res_pjsip_pubsub' section to sorcery.conf, and set 'resource_list=memory'\n");
  4628. return AST_TEST_NOT_RUN;
  4629. }
  4630. list = create_resource_list(test, "foo", "test", resources, ARRAY_LEN(resources));
  4631. if (!list) {
  4632. return AST_TEST_FAIL;
  4633. }
  4634. tree = ast_calloc(1, sizeof(*tree));
  4635. resp = build_resource_tree(NULL, &test_handler, "foo", tree, 1, NULL);
  4636. if (resp != 200) {
  4637. ast_test_status_update(test, "Unexpected response %d when building resource tree\n", resp);
  4638. return AST_TEST_FAIL;
  4639. }
  4640. if (!tree->root) {
  4641. ast_test_status_update(test, "Resource tree has no root\n");
  4642. return AST_TEST_FAIL;
  4643. }
  4644. /* We check against all but the final resource since we expect it not to be in the tree */
  4645. if (check_node(test, tree->root, resources, ARRAY_LEN(resources) - 1)) {
  4646. return AST_TEST_FAIL;
  4647. }
  4648. return AST_TEST_PASS;
  4649. }
  4650. AST_TEST_DEFINE(bad_branch)
  4651. {
  4652. RAII_VAR(struct resource_list *, list_1, NULL, cleanup_resource_list);
  4653. RAII_VAR(struct resource_list *, list_2, NULL, cleanup_resource_list);
  4654. RAII_VAR(struct resource_tree *, tree, NULL, test_resource_tree_destroy);
  4655. const char *resources_1[] = {
  4656. "huey",
  4657. "dewey",
  4658. "louie",
  4659. "gross",
  4660. };
  4661. /* This list has nothing but bad resources */
  4662. const char *resources_2[] = {
  4663. "coconut",
  4664. "cilantro",
  4665. "olive",
  4666. "cheese",
  4667. };
  4668. int resp;
  4669. switch (cmd) {
  4670. case TEST_INIT:
  4671. info->name = "bad_branch";
  4672. info->category = "/res/res_pjsip_pubsub/";
  4673. info->summary = "Ensure bad branches are pruned from the tree";
  4674. info->description =
  4675. "Create a resource list that makes a tree with an entire branch of bad resources.\n"
  4676. "Ensure the bad branch is pruned from the tree.";
  4677. return AST_TEST_NOT_RUN;
  4678. case TEST_EXECUTE:
  4679. break;
  4680. }
  4681. if (ineligible_configuration()) {
  4682. ast_test_status_update(test, "Ineligible configuration for this test. Please add a "
  4683. "'res_pjsip_pubsub' section to sorcery.conf, and set 'resource_list=memory'\n");
  4684. return AST_TEST_NOT_RUN;
  4685. }
  4686. list_1 = create_resource_list(test, "foo", "test", resources_1, ARRAY_LEN(resources_1));
  4687. if (!list_1) {
  4688. return AST_TEST_FAIL;
  4689. }
  4690. list_2 = create_resource_list(test, "gross", "test", resources_2, ARRAY_LEN(resources_2));
  4691. if (!list_2) {
  4692. return AST_TEST_FAIL;
  4693. }
  4694. tree = ast_calloc(1, sizeof(*tree));
  4695. resp = build_resource_tree(NULL, &test_handler, "foo", tree, 1, NULL);
  4696. if (resp != 200) {
  4697. ast_test_status_update(test, "Unexpected response %d when building resource tree\n", resp);
  4698. return AST_TEST_FAIL;
  4699. }
  4700. if (!tree->root) {
  4701. ast_test_status_update(test, "Resource tree has no root\n");
  4702. return AST_TEST_FAIL;
  4703. }
  4704. /* We check against all but the final resource of the list since the entire branch should
  4705. * be pruned from the tree
  4706. */
  4707. if (check_node(test, tree->root, resources_1, ARRAY_LEN(resources_1) - 1)) {
  4708. return AST_TEST_FAIL;
  4709. }
  4710. return AST_TEST_PASS;
  4711. }
  4712. AST_TEST_DEFINE(duplicate_resource)
  4713. {
  4714. RAII_VAR(struct resource_list *, list_1, NULL, cleanup_resource_list);
  4715. RAII_VAR(struct resource_list *, list_2, NULL, cleanup_resource_list);
  4716. RAII_VAR(struct resource_tree *, tree, NULL, test_resource_tree_destroy);
  4717. const char *resources_1[] = {
  4718. "huey",
  4719. "ducks",
  4720. "dewey",
  4721. "louie",
  4722. };
  4723. const char *resources_2[] = {
  4724. "donald",
  4725. "daisy",
  4726. "scrooge",
  4727. "dewey",
  4728. "louie",
  4729. "huey",
  4730. };
  4731. int resp;
  4732. struct tree_node *node;
  4733. switch (cmd) {
  4734. case TEST_INIT:
  4735. info->name = "duplicate_resource";
  4736. info->category = "/res/res_pjsip_pubsub/";
  4737. info->summary = "Ensure duplicated resources do not end up in the tree";
  4738. info->description =
  4739. "Create a resource list with a single duplicated resource. Ensure the duplicated resource does not end up in the tree.";
  4740. return AST_TEST_NOT_RUN;
  4741. case TEST_EXECUTE:
  4742. break;
  4743. }
  4744. if (ineligible_configuration()) {
  4745. ast_test_status_update(test, "Ineligible configuration for this test. Please add a "
  4746. "'res_pjsip_pubsub' section to sorcery.conf, and set 'resource_list=memory'\n");
  4747. return AST_TEST_NOT_RUN;
  4748. }
  4749. list_1 = create_resource_list(test, "foo", "test", resources_1, ARRAY_LEN(resources_1));
  4750. if (!list_1) {
  4751. return AST_TEST_FAIL;
  4752. }
  4753. list_2 = create_resource_list(test, "ducks", "test", resources_2, ARRAY_LEN(resources_2));
  4754. if (!list_2) {
  4755. return AST_TEST_FAIL;
  4756. }
  4757. tree = ast_calloc(1, sizeof(*tree));
  4758. resp = build_resource_tree(NULL, &test_handler, "foo", tree, 1, NULL);
  4759. if (resp != 200) {
  4760. ast_test_status_update(test, "Unexpected response %d when building resource tree\n", resp);
  4761. return AST_TEST_FAIL;
  4762. }
  4763. if (!tree->root) {
  4764. ast_test_status_update(test, "Resource tree has no root\n");
  4765. return AST_TEST_FAIL;
  4766. }
  4767. node = tree->root;
  4768. /* This node should have "huey" and "ducks". "dewey" and "louie" should not
  4769. * be present since they were found in the "ducks" list.
  4770. */
  4771. if (check_node(test, node, resources_1, ARRAY_LEN(resources_1) - 2)) {
  4772. return AST_TEST_FAIL;
  4773. }
  4774. /* This node should have "donald", "daisy", "scrooge", "dewey", and "louie".
  4775. * "huey" is not here since that was already encountered in the parent list
  4776. */
  4777. node = AST_VECTOR_GET(&node->children, 1);
  4778. if (check_node(test, node, resources_2, ARRAY_LEN(resources_2) - 1)) {
  4779. return AST_TEST_FAIL;
  4780. }
  4781. return AST_TEST_PASS;
  4782. }
  4783. AST_TEST_DEFINE(loop)
  4784. {
  4785. RAII_VAR(struct resource_list *, list_1, NULL, cleanup_resource_list);
  4786. RAII_VAR(struct resource_list *, list_2, NULL, cleanup_resource_list);
  4787. RAII_VAR(struct resource_tree *, tree, NULL, test_resource_tree_destroy);
  4788. const char *resources_1[] = {
  4789. "derp",
  4790. };
  4791. const char *resources_2[] = {
  4792. "herp",
  4793. };
  4794. int resp;
  4795. switch (cmd) {
  4796. case TEST_INIT:
  4797. info->name = "loop";
  4798. info->category = "/res/res_pjsip_pubsub/";
  4799. info->summary = "Test that loops are properly detected.";
  4800. info->description =
  4801. "Create two resource lists that refer to each other. Ensure that attempting to build a tree\n"
  4802. "results in an empty tree.";
  4803. return AST_TEST_NOT_RUN;
  4804. case TEST_EXECUTE:
  4805. break;
  4806. }
  4807. if (ineligible_configuration()) {
  4808. ast_test_status_update(test, "Ineligible configuration for this test. Please add a "
  4809. "'res_pjsip_pubsub' section to sorcery.conf, and set 'resource_list=memory'\n");
  4810. return AST_TEST_NOT_RUN;
  4811. }
  4812. list_1 = create_resource_list(test, "herp", "test", resources_1, ARRAY_LEN(resources_1));
  4813. if (!list_1) {
  4814. return AST_TEST_FAIL;
  4815. }
  4816. list_2 = create_resource_list(test, "derp", "test", resources_2, ARRAY_LEN(resources_2));
  4817. if (!list_2) {
  4818. return AST_TEST_FAIL;
  4819. }
  4820. tree = ast_calloc(1, sizeof(*tree));
  4821. resp = build_resource_tree(NULL, &test_handler, "herp", tree, 1, NULL);
  4822. if (resp == 200) {
  4823. ast_test_status_update(test, "Unexpected response %d when building resource tree\n", resp);
  4824. return AST_TEST_FAIL;
  4825. }
  4826. return AST_TEST_PASS;
  4827. }
  4828. AST_TEST_DEFINE(bad_event)
  4829. {
  4830. RAII_VAR(struct resource_list *, list, NULL, cleanup_resource_list);
  4831. RAII_VAR(struct resource_tree *, tree, NULL, test_resource_tree_destroy);
  4832. const char *resources[] = {
  4833. "huey",
  4834. "dewey",
  4835. "louie",
  4836. };
  4837. int resp;
  4838. switch (cmd) {
  4839. case TEST_INIT:
  4840. info->name = "bad_event";
  4841. info->category = "/res/res_pjsip_pubsub/";
  4842. info->summary = "Ensure that list with wrong event specified is not retrieved";
  4843. info->description =
  4844. "Create a simple resource list for event 'tsetse'. Ensure that trying to retrieve the list for event 'test' fails.";
  4845. return AST_TEST_NOT_RUN;
  4846. case TEST_EXECUTE:
  4847. break;
  4848. }
  4849. if (ineligible_configuration()) {
  4850. ast_test_status_update(test, "Ineligible configuration for this test. Please add a "
  4851. "'res_pjsip_pubsub' section to sorcery.conf, and set 'resource_list=memory'\n");
  4852. return AST_TEST_NOT_RUN;
  4853. }
  4854. list = create_resource_list(test, "foo", "tsetse", resources, ARRAY_LEN(resources));
  4855. if (!list) {
  4856. return AST_TEST_FAIL;
  4857. }
  4858. tree = ast_calloc(1, sizeof(*tree));
  4859. /* Since the test_handler is for event "test", this should not build a list, but
  4860. * instead result in a single resource being created, called "foo"
  4861. */
  4862. resp = build_resource_tree(NULL, &test_handler, "foo", tree, 1, NULL);
  4863. if (resp != 200) {
  4864. ast_test_status_update(test, "Unexpected response %d when building resource tree\n", resp);
  4865. return AST_TEST_FAIL;
  4866. }
  4867. if (!tree->root) {
  4868. ast_test_status_update(test, "Resource tree has no root\n");
  4869. return AST_TEST_FAIL;
  4870. }
  4871. if (strcmp(tree->root->resource, "foo")) {
  4872. ast_test_status_update(test, "Unexpected resource %s found in tree\n", tree->root->resource);
  4873. return AST_TEST_FAIL;
  4874. }
  4875. return AST_TEST_PASS;
  4876. }
  4877. #endif
  4878. static int resource_endpoint_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
  4879. {
  4880. struct ast_sip_publication_resource *resource = obj;
  4881. ast_free(resource->endpoint);
  4882. resource->endpoint = ast_strdup(var->value);
  4883. return 0;
  4884. }
  4885. static int resource_event_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
  4886. {
  4887. struct ast_sip_publication_resource *resource = obj;
  4888. /* The event configuration name starts with 'event_' so skip past it to get the real name */
  4889. const char *event = var->name + 6;
  4890. struct ast_variable *item;
  4891. if (ast_strlen_zero(event) || ast_strlen_zero(var->value)) {
  4892. return -1;
  4893. }
  4894. item = ast_variable_new(event, var->value, "");
  4895. if (!item) {
  4896. return -1;
  4897. }
  4898. if (resource->events) {
  4899. item->next = resource->events;
  4900. }
  4901. resource->events = item;
  4902. return 0;
  4903. }
  4904. static int load_module(void)
  4905. {
  4906. static const pj_str_t str_PUBLISH = { "PUBLISH", 7 };
  4907. struct ast_sorcery *sorcery;
  4908. sorcery = ast_sip_get_sorcery();
  4909. if (!(sched = ast_sched_context_create())) {
  4910. ast_log(LOG_ERROR, "Could not create scheduler for publication expiration\n");
  4911. return AST_MODULE_LOAD_DECLINE;
  4912. }
  4913. if (ast_sched_start_thread(sched)) {
  4914. ast_log(LOG_ERROR, "Could not start scheduler thread for publication expiration\n");
  4915. ast_sched_context_destroy(sched);
  4916. return AST_MODULE_LOAD_DECLINE;
  4917. }
  4918. ast_sorcery_apply_config(sorcery, "res_pjsip_pubsub");
  4919. ast_sorcery_apply_default(sorcery, "subscription_persistence", "astdb", "subscription_persistence");
  4920. if (ast_sorcery_object_register(sorcery, "subscription_persistence", subscription_persistence_alloc,
  4921. NULL, NULL)) {
  4922. ast_log(LOG_ERROR, "Could not register subscription persistence object support\n");
  4923. ast_sched_context_destroy(sched);
  4924. return AST_MODULE_LOAD_DECLINE;
  4925. }
  4926. ast_sorcery_object_field_register(sorcery, "subscription_persistence", "packet", "", OPT_CHAR_ARRAY_T, 0,
  4927. CHARFLDSET(struct subscription_persistence, packet));
  4928. ast_sorcery_object_field_register(sorcery, "subscription_persistence", "src_name", "", OPT_CHAR_ARRAY_T, 0,
  4929. CHARFLDSET(struct subscription_persistence, src_name));
  4930. ast_sorcery_object_field_register(sorcery, "subscription_persistence", "src_port", "0", OPT_UINT_T, 0,
  4931. FLDSET(struct subscription_persistence, src_port));
  4932. ast_sorcery_object_field_register(sorcery, "subscription_persistence", "transport_key", "0", OPT_CHAR_ARRAY_T, 0,
  4933. CHARFLDSET(struct subscription_persistence, transport_type));
  4934. ast_sorcery_object_field_register(sorcery, "subscription_persistence", "local_name", "", OPT_CHAR_ARRAY_T, 0,
  4935. CHARFLDSET(struct subscription_persistence, local_name));
  4936. ast_sorcery_object_field_register(sorcery, "subscription_persistence", "local_port", "0", OPT_UINT_T, 0,
  4937. FLDSET(struct subscription_persistence, local_port));
  4938. ast_sorcery_object_field_register(sorcery, "subscription_persistence", "cseq", "0", OPT_UINT_T, 0,
  4939. FLDSET(struct subscription_persistence, cseq));
  4940. ast_sorcery_object_field_register_custom(sorcery, "subscription_persistence", "endpoint", "",
  4941. persistence_endpoint_str2struct, persistence_endpoint_struct2str, NULL, 0, 0);
  4942. ast_sorcery_object_field_register_custom(sorcery, "subscription_persistence", "tag", "",
  4943. persistence_tag_str2struct, persistence_tag_struct2str, NULL, 0, 0);
  4944. ast_sorcery_object_field_register_custom(sorcery, "subscription_persistence", "expires", "",
  4945. persistence_expires_str2struct, persistence_expires_struct2str, NULL, 0, 0);
  4946. ast_sorcery_object_field_register(sorcery, "subscription_persistence", "contact_uri", "", OPT_CHAR_ARRAY_T, 0,
  4947. CHARFLDSET(struct subscription_persistence, contact_uri));
  4948. ast_sorcery_object_field_register(sorcery, "subscription_persistence", "prune_on_boot", "no", OPT_YESNO_T, 1,
  4949. FLDSET(struct subscription_persistence, prune_on_boot));
  4950. ast_sorcery_object_field_register_custom(sorcery, "subscription_persistence", "generator_data", "",
  4951. persistence_generator_data_str2struct, persistence_generator_data_struct2str, NULL, 0, 0);
  4952. if (apply_list_configuration(sorcery)) {
  4953. ast_sched_context_destroy(sched);
  4954. return AST_MODULE_LOAD_DECLINE;
  4955. }
  4956. ast_sorcery_apply_default(sorcery, "inbound-publication", "config", "pjsip.conf,criteria=type=inbound-publication");
  4957. if (ast_sorcery_object_register(sorcery, "inbound-publication", publication_resource_alloc,
  4958. NULL, NULL)) {
  4959. ast_log(LOG_ERROR, "Could not register subscription persistence object support\n");
  4960. ast_sched_context_destroy(sched);
  4961. return AST_MODULE_LOAD_DECLINE;
  4962. }
  4963. ast_sorcery_object_field_register(sorcery, "inbound-publication", "type", "", OPT_NOOP_T, 0, 0);
  4964. ast_sorcery_object_field_register_custom(sorcery, "inbound-publication", "endpoint", "",
  4965. resource_endpoint_handler, NULL, NULL, 0, 0);
  4966. ast_sorcery_object_fields_register(sorcery, "inbound-publication", "^event_", resource_event_handler, NULL);
  4967. ast_sorcery_reload_object(sorcery, "inbound-publication");
  4968. if (ast_sip_register_service(&pubsub_module)) {
  4969. ast_log(LOG_ERROR, "Could not register pubsub service\n");
  4970. ast_sched_context_destroy(sched);
  4971. return AST_MODULE_LOAD_DECLINE;
  4972. }
  4973. if (pjsip_evsub_init_module(ast_sip_get_pjsip_endpoint()) != PJ_SUCCESS) {
  4974. ast_log(LOG_ERROR, "Could not initialize pjsip evsub module.\n");
  4975. ast_sip_unregister_service(&pubsub_module);
  4976. ast_sched_context_destroy(sched);
  4977. return AST_MODULE_LOAD_DECLINE;
  4978. }
  4979. /* Once pjsip_evsub_init_module succeeds we cannot unload.
  4980. * Keep all module_load errors above this point. */
  4981. ast_module_shutdown_ref(ast_module_info->self);
  4982. pjsip_media_type_init2(&rlmi_media_type, "application", "rlmi+xml");
  4983. pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_ALLOW, NULL, 1, &str_PUBLISH);
  4984. if (ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
  4985. ast_sip_push_task(NULL, subscription_persistence_load, NULL);
  4986. } else {
  4987. struct stasis_subscription *sub;
  4988. sub = stasis_subscribe_pool(ast_manager_get_topic(), subscription_persistence_event_cb, NULL);
  4989. stasis_subscription_accept_message_type(sub, ast_manager_get_generic_type());
  4990. stasis_subscription_set_filter(sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
  4991. }
  4992. ast_manager_register_xml(AMI_SHOW_SUBSCRIPTIONS_INBOUND, EVENT_FLAG_SYSTEM,
  4993. ami_show_subscriptions_inbound);
  4994. ast_manager_register_xml(AMI_SHOW_SUBSCRIPTIONS_OUTBOUND, EVENT_FLAG_SYSTEM,
  4995. ami_show_subscriptions_outbound);
  4996. ast_manager_register_xml("PJSIPShowResourceLists", EVENT_FLAG_SYSTEM,
  4997. ami_show_resource_lists);
  4998. ast_cli_register_multiple(cli_commands, ARRAY_LEN(cli_commands));
  4999. AST_TEST_REGISTER(resource_tree);
  5000. AST_TEST_REGISTER(complex_resource_tree);
  5001. AST_TEST_REGISTER(bad_resource);
  5002. AST_TEST_REGISTER(bad_branch);
  5003. AST_TEST_REGISTER(duplicate_resource);
  5004. AST_TEST_REGISTER(loop);
  5005. AST_TEST_REGISTER(bad_event);
  5006. return AST_MODULE_LOAD_SUCCESS;
  5007. }
  5008. static int unload_module(void)
  5009. {
  5010. AST_TEST_UNREGISTER(resource_tree);
  5011. AST_TEST_UNREGISTER(complex_resource_tree);
  5012. AST_TEST_UNREGISTER(bad_resource);
  5013. AST_TEST_UNREGISTER(bad_branch);
  5014. AST_TEST_UNREGISTER(duplicate_resource);
  5015. AST_TEST_UNREGISTER(loop);
  5016. AST_TEST_UNREGISTER(bad_event);
  5017. ast_sip_transport_monitor_unregister_all(sub_tree_transport_cb, NULL, NULL);
  5018. ast_cli_unregister_multiple(cli_commands, ARRAY_LEN(cli_commands));
  5019. ast_manager_unregister(AMI_SHOW_SUBSCRIPTIONS_OUTBOUND);
  5020. ast_manager_unregister(AMI_SHOW_SUBSCRIPTIONS_INBOUND);
  5021. ast_manager_unregister("PJSIPShowResourceLists");
  5022. ast_sip_unregister_service(&pubsub_module);
  5023. if (sched) {
  5024. ast_sched_context_destroy(sched);
  5025. }
  5026. return 0;
  5027. }
  5028. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP event resource",
  5029. .support_level = AST_MODULE_SUPPORT_CORE,
  5030. .load = load_module,
  5031. .unload = unload_module,
  5032. .load_pri = AST_MODPRI_CHANNEL_DEPEND,
  5033. .requires = "res_pjsip",
  5034. );