res_pjsip_pubsub.c 174 KB

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