manager.c 283 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief The Asterisk Management Interface - AMI
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. *
  24. * OpenSSL http://www.openssl.org - for AMI/SSL
  25. *
  26. * At the moment this file contains a number of functions, namely:
  27. *
  28. * - data structures storing AMI state
  29. * - AMI-related API functions, used by internal asterisk components
  30. * - handlers for AMI-related CLI functions
  31. * - handlers for AMI functions (available through the AMI socket)
  32. * - the code for the main AMI listener thread and individual session threads
  33. * - the http handlers invoked for AMI-over-HTTP by the threads in main/http.c
  34. *
  35. * \ref amiconf
  36. */
  37. /*! \li \ref manager.c uses the configuration file \ref manager.conf and \ref users.conf
  38. * \addtogroup configuration_file
  39. */
  40. /*! \page manager.conf manager.conf
  41. * \verbinclude manager.conf.sample
  42. */
  43. /*! \page users.conf users.conf
  44. * \verbinclude users.conf.sample
  45. */
  46. /*** MODULEINFO
  47. <support_level>core</support_level>
  48. ***/
  49. #include "asterisk.h"
  50. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  51. #include "asterisk/paths.h" /* use various ast_config_AST_* */
  52. #include <ctype.h>
  53. #include <sys/time.h>
  54. #include <signal.h>
  55. #include <sys/mman.h>
  56. #include <sys/types.h>
  57. #include <regex.h>
  58. #include "asterisk/channel.h"
  59. #include "asterisk/file.h"
  60. #include "asterisk/manager.h"
  61. #include "asterisk/module.h"
  62. #include "asterisk/config.h"
  63. #include "asterisk/callerid.h"
  64. #include "asterisk/lock.h"
  65. #include "asterisk/cli.h"
  66. #include "asterisk/app.h"
  67. #include "asterisk/pbx.h"
  68. #include "asterisk/md5.h"
  69. #include "asterisk/acl.h"
  70. #include "asterisk/utils.h"
  71. #include "asterisk/tcptls.h"
  72. #include "asterisk/http.h"
  73. #include "asterisk/ast_version.h"
  74. #include "asterisk/threadstorage.h"
  75. #include "asterisk/linkedlists.h"
  76. #include "asterisk/term.h"
  77. #include "asterisk/astobj2.h"
  78. #include "asterisk/features.h"
  79. #include "asterisk/security_events.h"
  80. #include "asterisk/aoc.h"
  81. #include "asterisk/strings.h"
  82. #include "asterisk/stringfields.h"
  83. #include "asterisk/presencestate.h"
  84. #include "asterisk/stasis_message_router.h"
  85. #include "asterisk/stasis_channels.h"
  86. #include "asterisk/stasis_bridges.h"
  87. #include "asterisk/test.h"
  88. #include "asterisk/json.h"
  89. #include "asterisk/bridge.h"
  90. #include "asterisk/features_config.h"
  91. #include "asterisk/rtp_engine.h"
  92. #include "asterisk/format_cache.h"
  93. #include "asterisk/translate.h"
  94. #include "asterisk/taskprocessor.h"
  95. /*** DOCUMENTATION
  96. <manager name="Ping" language="en_US">
  97. <synopsis>
  98. Keepalive command.
  99. </synopsis>
  100. <syntax>
  101. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  102. </syntax>
  103. <description>
  104. <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
  105. manager connection open.</para>
  106. </description>
  107. </manager>
  108. <manager name="Events" language="en_US">
  109. <synopsis>
  110. Control Event Flow.
  111. </synopsis>
  112. <syntax>
  113. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  114. <parameter name="EventMask" required="true">
  115. <enumlist>
  116. <enum name="on">
  117. <para>If all events should be sent.</para>
  118. </enum>
  119. <enum name="off">
  120. <para>If no events should be sent.</para>
  121. </enum>
  122. <enum name="system,call,log,...">
  123. <para>To select which flags events should have to be sent.</para>
  124. </enum>
  125. </enumlist>
  126. </parameter>
  127. </syntax>
  128. <description>
  129. <para>Enable/Disable sending of events to this manager client.</para>
  130. </description>
  131. </manager>
  132. <manager name="Logoff" language="en_US">
  133. <synopsis>
  134. Logoff Manager.
  135. </synopsis>
  136. <syntax>
  137. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  138. </syntax>
  139. <description>
  140. <para>Logoff the current manager session.</para>
  141. </description>
  142. <see-also>
  143. <ref type="manager">Login</ref>
  144. </see-also>
  145. </manager>
  146. <manager name="Login" language="en_US">
  147. <synopsis>
  148. Login Manager.
  149. </synopsis>
  150. <syntax>
  151. <parameter name="ActionID">
  152. <para>ActionID for this transaction. Will be returned.</para>
  153. </parameter>
  154. <parameter name="Username" required="true">
  155. <para>Username to login with as specified in manager.conf.</para>
  156. </parameter>
  157. <parameter name="Secret">
  158. <para>Secret to login with as specified in manager.conf.</para>
  159. </parameter>
  160. </syntax>
  161. <description>
  162. <para>Login Manager.</para>
  163. </description>
  164. <see-also>
  165. <ref type="manager">Logoff</ref>
  166. </see-also>
  167. </manager>
  168. <manager name="Challenge" language="en_US">
  169. <synopsis>
  170. Generate Challenge for MD5 Auth.
  171. </synopsis>
  172. <syntax>
  173. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  174. <parameter name="AuthType" required="true">
  175. <para>Digest algorithm to use in the challenge. Valid values are:</para>
  176. <enumlist>
  177. <enum name="MD5" />
  178. </enumlist>
  179. </parameter>
  180. </syntax>
  181. <description>
  182. <para>Generate a challenge for MD5 authentication.</para>
  183. </description>
  184. </manager>
  185. <manager name="Hangup" language="en_US">
  186. <synopsis>
  187. Hangup channel.
  188. </synopsis>
  189. <syntax>
  190. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  191. <parameter name="Channel" required="true">
  192. <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
  193. <para>Example exact channel: SIP/provider-0000012a</para>
  194. <para>Example regular expression: /^SIP/provider-.*$/</para>
  195. </parameter>
  196. <parameter name="Cause">
  197. <para>Numeric hangup cause.</para>
  198. </parameter>
  199. </syntax>
  200. <description>
  201. <para>Hangup a channel.</para>
  202. </description>
  203. </manager>
  204. <manager name="Status" language="en_US">
  205. <synopsis>
  206. List channel status.
  207. </synopsis>
  208. <syntax>
  209. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  210. <parameter name="Channel" required="false">
  211. <para>The name of the channel to query for status.</para>
  212. </parameter>
  213. <parameter name="Variables">
  214. <para>Comma <literal>,</literal> separated list of variable to include.</para>
  215. </parameter>
  216. </syntax>
  217. <description>
  218. <para>Will return the status information of each channel along with the
  219. value for the specified channel variables.</para>
  220. </description>
  221. <responses>
  222. <list-elements>
  223. <xi:include xpointer="xpointer(/docs/managerEvent[@name='Status'])" />
  224. </list-elements>
  225. <xi:include xpointer="xpointer(/docs/managerEvent[@name='StatusComplete'])" />
  226. </responses>
  227. </manager>
  228. <managerEvent language="en_US" name="Status">
  229. <managerEventInstance class="EVENT_FLAG_CALL">
  230. <synopsis>Raised in response to a Status command.</synopsis>
  231. <syntax>
  232. <parameter name="ActionID" required="false"/>
  233. <channel_snapshot/>
  234. <parameter name="Type">
  235. <para>Type of channel</para>
  236. </parameter>
  237. <parameter name="DNID">
  238. <para>Dialed number identifier</para>
  239. </parameter>
  240. <parameter name="EffectiveConnectedLineNum">
  241. </parameter>
  242. <parameter name="EffectiveConnectedLineName">
  243. </parameter>
  244. <parameter name="TimeToHangup">
  245. <para>Absolute lifetime of the channel</para>
  246. </parameter>
  247. <parameter name="BridgeID">
  248. <para>Identifier of the bridge the channel is in, may be empty if not in one</para>
  249. </parameter>
  250. <parameter name="Application">
  251. <para>Application currently executing on the channel</para>
  252. </parameter>
  253. <parameter name="Data">
  254. <para>Data given to the currently executing channel</para>
  255. </parameter>
  256. <parameter name="Nativeformats">
  257. <para>Media formats the connected party is willing to send or receive</para>
  258. </parameter>
  259. <parameter name="Readformat">
  260. <para>Media formats that frames from the channel are received in</para>
  261. </parameter>
  262. <parameter name="Readtrans">
  263. <para>Translation path for media received in native formats</para>
  264. </parameter>
  265. <parameter name="Writeformat">
  266. <para>Media formats that frames to the channel are accepted in</para>
  267. </parameter>
  268. <parameter name="Writetrans">
  269. <para>Translation path for media sent to the connected party</para>
  270. </parameter>
  271. <parameter name="Callgroup">
  272. <para>Configured call group on the channel</para>
  273. </parameter>
  274. <parameter name="Pickupgroup">
  275. <para>Configured pickup group on the channel</para>
  276. </parameter>
  277. <parameter name="Seconds">
  278. <para>Number of seconds the channel has been active</para>
  279. </parameter>
  280. </syntax>
  281. <see-also>
  282. <ref type="manager">Status</ref>
  283. </see-also>
  284. </managerEventInstance>
  285. </managerEvent>
  286. <managerEvent language="en_US" name="StatusComplete">
  287. <managerEventInstance class="EVENT_FLAG_CALL">
  288. <synopsis>Raised in response to a Status command.</synopsis>
  289. <syntax>
  290. <parameter name="Items">
  291. <para>Number of Status events returned</para>
  292. </parameter>
  293. </syntax>
  294. <see-also>
  295. <ref type="manager">Status</ref>
  296. </see-also>
  297. </managerEventInstance>
  298. </managerEvent>
  299. <manager name="Setvar" language="en_US">
  300. <synopsis>
  301. Sets a channel variable or function value.
  302. </synopsis>
  303. <syntax>
  304. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  305. <parameter name="Channel">
  306. <para>Channel to set variable for.</para>
  307. </parameter>
  308. <parameter name="Variable" required="true">
  309. <para>Variable name, function or expression.</para>
  310. </parameter>
  311. <parameter name="Value" required="true">
  312. <para>Variable or function value.</para>
  313. </parameter>
  314. </syntax>
  315. <description>
  316. <para>This command can be used to set the value of channel variables or dialplan
  317. functions.</para>
  318. <note>
  319. <para>If a channel name is not provided then the variable is considered global.</para>
  320. </note>
  321. </description>
  322. <see-also>
  323. <ref type="manager">Getvar</ref>
  324. </see-also>
  325. </manager>
  326. <manager name="Getvar" language="en_US">
  327. <synopsis>
  328. Gets a channel variable or function value.
  329. </synopsis>
  330. <syntax>
  331. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  332. <parameter name="Channel">
  333. <para>Channel to read variable from.</para>
  334. </parameter>
  335. <parameter name="Variable" required="true">
  336. <para>Variable name, function or expression.</para>
  337. </parameter>
  338. </syntax>
  339. <description>
  340. <para>Get the value of a channel variable or function return.</para>
  341. <note>
  342. <para>If a channel name is not provided then the variable is considered global.</para>
  343. </note>
  344. </description>
  345. <see-also>
  346. <ref type="manager">Setvar</ref>
  347. </see-also>
  348. </manager>
  349. <manager name="GetConfig" language="en_US">
  350. <synopsis>
  351. Retrieve configuration.
  352. </synopsis>
  353. <syntax>
  354. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  355. <parameter name="Filename" required="true">
  356. <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
  357. </parameter>
  358. <parameter name="Category">
  359. <para>Category in configuration file.</para>
  360. </parameter>
  361. <parameter name="Filter">
  362. <para>A comma separated list of
  363. <replaceable>name_regex</replaceable>=<replaceable>value_regex</replaceable>
  364. expressions which will cause only categories whose variables match all expressions
  365. to be considered. The special variable name <literal>TEMPLATES</literal>
  366. can be used to control whether templates are included. Passing
  367. <literal>include</literal> as the value will include templates
  368. along with normal categories. Passing
  369. <literal>restrict</literal> as the value will restrict the operation to
  370. ONLY templates. Not specifying a <literal>TEMPLATES</literal> expression
  371. results in the default behavior which is to not include templates.</para>
  372. </parameter>
  373. </syntax>
  374. <description>
  375. <para>This action will dump the contents of a configuration
  376. file by category and contents or optionally by specified category only.
  377. In the case where a category name is non-unique, a filter may be specified
  378. to match only categories with matching variable values.</para>
  379. </description>
  380. <see-also>
  381. <ref type="manager">GetConfigJSON</ref>
  382. <ref type="manager">UpdateConfig</ref>
  383. <ref type="manager">CreateConfig</ref>
  384. <ref type="manager">ListCategories</ref>
  385. </see-also>
  386. </manager>
  387. <manager name="GetConfigJSON" language="en_US">
  388. <synopsis>
  389. Retrieve configuration (JSON format).
  390. </synopsis>
  391. <syntax>
  392. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  393. <parameter name="Filename" required="true">
  394. <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
  395. </parameter>
  396. <parameter name="Category">
  397. <para>Category in configuration file.</para>
  398. </parameter>
  399. <parameter name="Filter">
  400. <xi:include xpointer="xpointer(/docs/manager[@name='GetConfig']/syntax/parameter[@name='Filter']/para[1])" />
  401. </parameter>
  402. </syntax>
  403. <description>
  404. <para>This action will dump the contents of a configuration file by category
  405. and contents in JSON format or optionally by specified category only.
  406. This only makes sense to be used using rawman over the HTTP interface.
  407. In the case where a category name is non-unique, a filter may be specified
  408. to match only categories with matching variable values.</para>
  409. </description>
  410. <see-also>
  411. <ref type="manager">GetConfig</ref>
  412. <ref type="manager">UpdateConfig</ref>
  413. <ref type="manager">CreateConfig</ref>
  414. <ref type="manager">ListCategories</ref>
  415. </see-also>
  416. </manager>
  417. <manager name="UpdateConfig" language="en_US">
  418. <synopsis>
  419. Update basic configuration.
  420. </synopsis>
  421. <syntax>
  422. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  423. <parameter name="SrcFilename" required="true">
  424. <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
  425. </parameter>
  426. <parameter name="DstFilename" required="true">
  427. <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
  428. </parameter>
  429. <parameter name="Reload">
  430. <para>Whether or not a reload should take place (or name of specific module).</para>
  431. </parameter>
  432. <parameter name="PreserveEffectiveContext">
  433. <para>Whether the effective category contents should be preserved on template change. Default is true (pre 13.2 behavior).</para>
  434. </parameter>
  435. <parameter name="Action-000000">
  436. <para>Action to take.</para>
  437. <para>0's represent 6 digit number beginning with 000000.</para>
  438. <enumlist>
  439. <enum name="NewCat" />
  440. <enum name="RenameCat" />
  441. <enum name="DelCat" />
  442. <enum name="EmptyCat" />
  443. <enum name="Update" />
  444. <enum name="Delete" />
  445. <enum name="Append" />
  446. <enum name="Insert" />
  447. </enumlist>
  448. </parameter>
  449. <parameter name="Cat-000000">
  450. <para>Category to operate on.</para>
  451. <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
  452. </parameter>
  453. <parameter name="Var-000000">
  454. <para>Variable to work on.</para>
  455. <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
  456. </parameter>
  457. <parameter name="Value-000000">
  458. <para>Value to work on.</para>
  459. <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
  460. </parameter>
  461. <parameter name="Match-000000">
  462. <para>Extra match required to match line.</para>
  463. <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
  464. </parameter>
  465. <parameter name="Line-000000">
  466. <para>Line in category to operate on (used with delete and insert actions).</para>
  467. <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
  468. </parameter>
  469. <parameter name="Options-000000">
  470. <para>A comma separated list of action-specific options.</para>
  471. <enumlist>
  472. <enum name="NewCat"><para>One or more of the following... </para>
  473. <enumlist>
  474. <enum name="allowdups"><para>Allow duplicate category names.</para></enum>
  475. <enum name="template"><para>This category is a template.</para></enum>
  476. <enum name="inherit=&quot;template[,...]&quot;"><para>Templates from which to inherit.</para></enum>
  477. </enumlist>
  478. </enum>
  479. </enumlist>
  480. <para> </para>
  481. <para>The following actions share the same options...</para>
  482. <enumlist>
  483. <enum name="RenameCat"/>
  484. <enum name="DelCat"/>
  485. <enum name="EmptyCat"/>
  486. <enum name="Update"/>
  487. <enum name="Delete"/>
  488. <enum name="Append"/>
  489. <enum name="Insert"><para> </para>
  490. <enumlist>
  491. <enum name="catfilter=&quot;&lt;expression&gt;[,...]&quot;"><para> </para>
  492. <xi:include xpointer="xpointer(/docs/manager[@name='GetConfig']/syntax/parameter[@name='Filter']/para[1])" />
  493. <para><literal>catfilter</literal> is most useful when a file
  494. contains multiple categories with the same name and you wish to
  495. operate on specific ones instead of all of them.</para>
  496. </enum>
  497. </enumlist>
  498. </enum>
  499. </enumlist>
  500. <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
  501. </parameter>
  502. </syntax>
  503. <description>
  504. <para>This action will modify, create, or delete configuration elements
  505. in Asterisk configuration files.</para>
  506. </description>
  507. <see-also>
  508. <ref type="manager">GetConfig</ref>
  509. <ref type="manager">GetConfigJSON</ref>
  510. <ref type="manager">CreateConfig</ref>
  511. <ref type="manager">ListCategories</ref>
  512. </see-also>
  513. </manager>
  514. <manager name="CreateConfig" language="en_US">
  515. <synopsis>
  516. Creates an empty file in the configuration directory.
  517. </synopsis>
  518. <syntax>
  519. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  520. <parameter name="Filename" required="true">
  521. <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
  522. </parameter>
  523. </syntax>
  524. <description>
  525. <para>This action will create an empty file in the configuration
  526. directory. This action is intended to be used before an UpdateConfig
  527. action.</para>
  528. </description>
  529. <see-also>
  530. <ref type="manager">GetConfig</ref>
  531. <ref type="manager">GetConfigJSON</ref>
  532. <ref type="manager">UpdateConfig</ref>
  533. <ref type="manager">ListCategories</ref>
  534. </see-also>
  535. </manager>
  536. <manager name="ListCategories" language="en_US">
  537. <synopsis>
  538. List categories in configuration file.
  539. </synopsis>
  540. <syntax>
  541. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  542. <parameter name="Filename" required="true">
  543. <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
  544. </parameter>
  545. </syntax>
  546. <description>
  547. <para>This action will dump the categories in a given file.</para>
  548. </description>
  549. <see-also>
  550. <ref type="manager">GetConfig</ref>
  551. <ref type="manager">GetConfigJSON</ref>
  552. <ref type="manager">UpdateConfig</ref>
  553. <ref type="manager">CreateConfig</ref>
  554. </see-also>
  555. </manager>
  556. <manager name="Redirect" language="en_US">
  557. <synopsis>
  558. Redirect (transfer) a call.
  559. </synopsis>
  560. <syntax>
  561. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  562. <parameter name="Channel" required="true">
  563. <para>Channel to redirect.</para>
  564. </parameter>
  565. <parameter name="ExtraChannel">
  566. <para>Second call leg to transfer (optional).</para>
  567. </parameter>
  568. <parameter name="Exten" required="true">
  569. <para>Extension to transfer to.</para>
  570. </parameter>
  571. <parameter name="ExtraExten">
  572. <para>Extension to transfer extrachannel to (optional).</para>
  573. </parameter>
  574. <parameter name="Context" required="true">
  575. <para>Context to transfer to.</para>
  576. </parameter>
  577. <parameter name="ExtraContext">
  578. <para>Context to transfer extrachannel to (optional).</para>
  579. </parameter>
  580. <parameter name="Priority" required="true">
  581. <para>Priority to transfer to.</para>
  582. </parameter>
  583. <parameter name="ExtraPriority">
  584. <para>Priority to transfer extrachannel to (optional).</para>
  585. </parameter>
  586. </syntax>
  587. <description>
  588. <para>Redirect (transfer) a call.</para>
  589. </description>
  590. <see-also>
  591. <ref type="manager">BlindTransfer</ref>
  592. </see-also>
  593. </manager>
  594. <manager name="Atxfer" language="en_US">
  595. <synopsis>
  596. Attended transfer.
  597. </synopsis>
  598. <syntax>
  599. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  600. <parameter name="Channel" required="true">
  601. <para>Transferer's channel.</para>
  602. </parameter>
  603. <parameter name="Exten" required="true">
  604. <para>Extension to transfer to.</para>
  605. </parameter>
  606. <parameter name="Context">
  607. <para>Context to transfer to.</para>
  608. </parameter>
  609. </syntax>
  610. <description>
  611. <para>Attended transfer.</para>
  612. </description>
  613. <see-also>
  614. <ref type="managerEvent">AttendedTransfer</ref>
  615. </see-also>
  616. </manager>
  617. <manager name="CancelAtxfer" language="en_US">
  618. <synopsis>
  619. Cancel an attended transfer.
  620. </synopsis>
  621. <syntax>
  622. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  623. <parameter name="Channel" required="true">
  624. <para>The transferer channel.</para>
  625. </parameter>
  626. </syntax>
  627. <description>
  628. <para>Cancel an attended transfer. Note, this uses the configured cancel attended transfer
  629. feature option (atxferabort) to cancel the transfer. If not available this action will fail.
  630. </para>
  631. </description>
  632. <see-also>
  633. <ref type="managerEvent">AttendedTransfer</ref>
  634. </see-also>
  635. </manager>
  636. <manager name="Originate" language="en_US">
  637. <synopsis>
  638. Originate a call.
  639. </synopsis>
  640. <syntax>
  641. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  642. <parameter name="Channel" required="true">
  643. <para>Channel name to call.</para>
  644. </parameter>
  645. <parameter name="Exten">
  646. <para>Extension to use (requires <literal>Context</literal> and
  647. <literal>Priority</literal>)</para>
  648. </parameter>
  649. <parameter name="Context">
  650. <para>Context to use (requires <literal>Exten</literal> and
  651. <literal>Priority</literal>)</para>
  652. </parameter>
  653. <parameter name="Priority">
  654. <para>Priority to use (requires <literal>Exten</literal> and
  655. <literal>Context</literal>)</para>
  656. </parameter>
  657. <parameter name="Application">
  658. <para>Application to execute.</para>
  659. </parameter>
  660. <parameter name="Data">
  661. <para>Data to use (requires <literal>Application</literal>).</para>
  662. </parameter>
  663. <parameter name="Timeout" default="30000">
  664. <para>How long to wait for call to be answered (in ms.).</para>
  665. </parameter>
  666. <parameter name="CallerID">
  667. <para>Caller ID to be set on the outgoing channel.</para>
  668. </parameter>
  669. <parameter name="Variable">
  670. <para>Channel variable to set, multiple Variable: headers are allowed.</para>
  671. </parameter>
  672. <parameter name="Account">
  673. <para>Account code.</para>
  674. </parameter>
  675. <parameter name="EarlyMedia">
  676. <para>Set to <literal>true</literal> to force call bridge on early media..</para>
  677. </parameter>
  678. <parameter name="Async">
  679. <para>Set to <literal>true</literal> for fast origination.</para>
  680. </parameter>
  681. <parameter name="Codecs">
  682. <para>Comma-separated list of codecs to use for this call.</para>
  683. </parameter>
  684. <parameter name="ChannelId">
  685. <para>Channel UniqueId to be set on the channel.</para>
  686. </parameter>
  687. <parameter name="OtherChannelId">
  688. <para>Channel UniqueId to be set on the second local channel.</para>
  689. </parameter>
  690. </syntax>
  691. <description>
  692. <para>Generates an outgoing call to a
  693. <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
  694. or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
  695. </description>
  696. <see-also>
  697. <ref type="managerEvent">OriginateResponse</ref>
  698. </see-also>
  699. </manager>
  700. <managerEvent language="en_US" name="OriginateResponse">
  701. <managerEventInstance class="EVENT_FLAG_CALL">
  702. <synopsis>Raised in response to an Originate command.</synopsis>
  703. <syntax>
  704. <parameter name="ActionID" required="false"/>
  705. <parameter name="Response">
  706. <enumlist>
  707. <enum name="Failure"/>
  708. <enum name="Success"/>
  709. </enumlist>
  710. </parameter>
  711. <parameter name="Channel"/>
  712. <parameter name="Context"/>
  713. <parameter name="Exten"/>
  714. <parameter name="Application"/>
  715. <parameter name="Data"/>
  716. <parameter name="Reason"/>
  717. <parameter name="Uniqueid"/>
  718. <parameter name="CallerIDNum"/>
  719. <parameter name="CallerIDName"/>
  720. </syntax>
  721. <see-also>
  722. <ref type="manager">Originate</ref>
  723. </see-also>
  724. </managerEventInstance>
  725. </managerEvent>
  726. <manager name="Command" language="en_US">
  727. <synopsis>
  728. Execute Asterisk CLI Command.
  729. </synopsis>
  730. <syntax>
  731. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  732. <parameter name="Command" required="true">
  733. <para>Asterisk CLI command to run.</para>
  734. </parameter>
  735. </syntax>
  736. <description>
  737. <para>Run a CLI command.</para>
  738. </description>
  739. </manager>
  740. <manager name="ExtensionState" language="en_US">
  741. <synopsis>
  742. Check Extension Status.
  743. </synopsis>
  744. <syntax>
  745. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  746. <parameter name="Exten" required="true">
  747. <para>Extension to check state on.</para>
  748. </parameter>
  749. <parameter name="Context" required="true">
  750. <para>Context for extension.</para>
  751. </parameter>
  752. </syntax>
  753. <description>
  754. <para>Report the extension state for given extension. If the extension has a hint,
  755. will use devicestate to check the status of the device connected to the extension.</para>
  756. <para>Will return an <literal>Extension Status</literal> message. The response will include
  757. the hint for the extension and the status.</para>
  758. </description>
  759. <see-also>
  760. <ref type="managerEvent">ExtensionStatus</ref>
  761. </see-also>
  762. </manager>
  763. <manager name="PresenceState" language="en_US">
  764. <synopsis>
  765. Check Presence State
  766. </synopsis>
  767. <syntax>
  768. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  769. <parameter name="Provider" required="true">
  770. <para>Presence Provider to check the state of</para>
  771. </parameter>
  772. </syntax>
  773. <description>
  774. <para>Report the presence state for the given presence provider.</para>
  775. <para>Will return a <literal>Presence State</literal> message. The response will include the
  776. presence state and, if set, a presence subtype and custom message.</para>
  777. </description>
  778. <see-also>
  779. <ref type="managerEvent">PresenceStatus</ref>
  780. </see-also>
  781. </manager>
  782. <manager name="AbsoluteTimeout" language="en_US">
  783. <synopsis>
  784. Set absolute timeout.
  785. </synopsis>
  786. <syntax>
  787. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  788. <parameter name="Channel" required="true">
  789. <para>Channel name to hangup.</para>
  790. </parameter>
  791. <parameter name="Timeout" required="true">
  792. <para>Maximum duration of the call (sec).</para>
  793. </parameter>
  794. </syntax>
  795. <description>
  796. <para>Hangup a channel after a certain time. Acknowledges set time with
  797. <literal>Timeout Set</literal> message.</para>
  798. </description>
  799. </manager>
  800. <manager name="MailboxStatus" language="en_US">
  801. <synopsis>
  802. Check mailbox.
  803. </synopsis>
  804. <syntax>
  805. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  806. <parameter name="Mailbox" required="true">
  807. <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
  808. </parameter>
  809. </syntax>
  810. <description>
  811. <para>Checks a voicemail account for status.</para>
  812. <para>Returns whether there are messages waiting.</para>
  813. <para>Message: Mailbox Status.</para>
  814. <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
  815. <para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
  816. if no messages waiting.</para>
  817. </description>
  818. <see-also>
  819. <ref type="manager">MailboxCount</ref>
  820. </see-also>
  821. </manager>
  822. <manager name="MailboxCount" language="en_US">
  823. <synopsis>
  824. Check Mailbox Message Count.
  825. </synopsis>
  826. <syntax>
  827. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  828. <parameter name="Mailbox" required="true">
  829. <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
  830. </parameter>
  831. </syntax>
  832. <description>
  833. <para>Checks a voicemail account for new messages.</para>
  834. <para>Returns number of urgent, new and old messages.</para>
  835. <para>Message: Mailbox Message Count</para>
  836. <para>Mailbox: <replaceable>mailboxid</replaceable></para>
  837. <para>UrgentMessages: <replaceable>count</replaceable></para>
  838. <para>NewMessages: <replaceable>count</replaceable></para>
  839. <para>OldMessages: <replaceable>count</replaceable></para>
  840. </description>
  841. <see-also>
  842. <ref type="manager">MailboxStatus</ref>
  843. </see-also>
  844. </manager>
  845. <manager name="ListCommands" language="en_US">
  846. <synopsis>
  847. List available manager commands.
  848. </synopsis>
  849. <syntax>
  850. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  851. </syntax>
  852. <description>
  853. <para>Returns the action name and synopsis for every action that
  854. is available to the user.</para>
  855. </description>
  856. </manager>
  857. <manager name="SendText" language="en_US">
  858. <synopsis>
  859. Send text message to channel.
  860. </synopsis>
  861. <syntax>
  862. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  863. <parameter name="Channel" required="true">
  864. <para>Channel to send message to.</para>
  865. </parameter>
  866. <parameter name="Message" required="true">
  867. <para>Message to send.</para>
  868. </parameter>
  869. </syntax>
  870. <description>
  871. <para>Sends A Text Message to a channel while in a call.</para>
  872. </description>
  873. </manager>
  874. <manager name="UserEvent" language="en_US">
  875. <synopsis>
  876. Send an arbitrary event.
  877. </synopsis>
  878. <syntax>
  879. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  880. <parameter name="UserEvent" required="true">
  881. <para>Event string to send.</para>
  882. </parameter>
  883. <parameter name="Header1">
  884. <para>Content1.</para>
  885. </parameter>
  886. <parameter name="HeaderN">
  887. <para>ContentN.</para>
  888. </parameter>
  889. </syntax>
  890. <description>
  891. <para>Send an event to manager sessions.</para>
  892. </description>
  893. <see-also>
  894. <ref type="managerEvent">UserEvent</ref>
  895. <ref type="application">UserEvent</ref>
  896. </see-also>
  897. </manager>
  898. <manager name="WaitEvent" language="en_US">
  899. <synopsis>
  900. Wait for an event to occur.
  901. </synopsis>
  902. <syntax>
  903. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  904. <parameter name="Timeout" required="true">
  905. <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
  906. </parameter>
  907. </syntax>
  908. <description>
  909. <para>This action will ellicit a <literal>Success</literal> response. Whenever
  910. a manager event is queued. Once WaitEvent has been called on an HTTP manager
  911. session, events will be generated and queued.</para>
  912. </description>
  913. </manager>
  914. <manager name="CoreSettings" language="en_US">
  915. <synopsis>
  916. Show PBX core settings (version etc).
  917. </synopsis>
  918. <syntax>
  919. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  920. </syntax>
  921. <description>
  922. <para>Query for Core PBX settings.</para>
  923. </description>
  924. </manager>
  925. <manager name="CoreStatus" language="en_US">
  926. <synopsis>
  927. Show PBX core status variables.
  928. </synopsis>
  929. <syntax>
  930. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  931. </syntax>
  932. <description>
  933. <para>Query for Core PBX status.</para>
  934. </description>
  935. </manager>
  936. <manager name="Reload" language="en_US">
  937. <synopsis>
  938. Send a reload event.
  939. </synopsis>
  940. <syntax>
  941. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  942. <parameter name="Module">
  943. <para>Name of the module to reload.</para>
  944. </parameter>
  945. </syntax>
  946. <description>
  947. <para>Send a reload event.</para>
  948. </description>
  949. <see-also>
  950. <ref type="manager">ModuleLoad</ref>
  951. </see-also>
  952. </manager>
  953. <managerEvent language="en_US" name="CoreShowChannel">
  954. <managerEventInstance class="EVENT_FLAG_CALL">
  955. <synopsis>Raised in response to a CoreShowChannels command.</synopsis>
  956. <syntax>
  957. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  958. <channel_snapshot/>
  959. <parameter name="BridgeId">
  960. <para>Identifier of the bridge the channel is in, may be empty if not in one</para>
  961. </parameter>
  962. <parameter name="Application">
  963. <para>Application currently executing on the channel</para>
  964. </parameter>
  965. <parameter name="ApplicationData">
  966. <para>Data given to the currently executing application</para>
  967. </parameter>
  968. <parameter name="Duration">
  969. <para>The amount of time the channel has existed</para>
  970. </parameter>
  971. </syntax>
  972. <see-also>
  973. <ref type="manager">CoreShowChannels</ref>
  974. <ref type="managerEvent">CoreShowChannelsComplete</ref>
  975. </see-also>
  976. </managerEventInstance>
  977. </managerEvent>
  978. <managerEvent language="en_US" name="CoreShowChannelsComplete">
  979. <managerEventInstance class="EVENT_FLAG_CALL">
  980. <synopsis>Raised at the end of the CoreShowChannel list produced by the CoreShowChannels command.</synopsis>
  981. <syntax>
  982. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  983. <parameter name="EventList">
  984. <para>Conveys the status of the command reponse list</para>
  985. </parameter>
  986. <parameter name="ListItems">
  987. <para>The total number of list items produced</para>
  988. </parameter>
  989. </syntax>
  990. <see-also>
  991. <ref type="manager">CoreShowChannels</ref>
  992. <ref type="managerEvent">CoreShowChannel</ref>
  993. </see-also>
  994. </managerEventInstance>
  995. </managerEvent>
  996. <manager name="CoreShowChannels" language="en_US">
  997. <synopsis>
  998. List currently active channels.
  999. </synopsis>
  1000. <syntax>
  1001. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  1002. </syntax>
  1003. <description>
  1004. <para>List currently defined channels and some information about them.</para>
  1005. </description>
  1006. <responses>
  1007. <list-elements>
  1008. <xi:include xpointer="xpointer(/docs/managerEvent[@name='CoreShowChannel'])" />
  1009. </list-elements>
  1010. <xi:include xpointer="xpointer(/docs/managerEvent[@name='CoreShowChannelsComplete'])" />
  1011. </responses>
  1012. </manager>
  1013. <manager name="LoggerRotate" language="en_US">
  1014. <synopsis>
  1015. Reload and rotate the Asterisk logger.
  1016. </synopsis>
  1017. <syntax>
  1018. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  1019. </syntax>
  1020. <description>
  1021. <para>Reload and rotate the logger. Analogous to the CLI command 'logger rotate'.</para>
  1022. </description>
  1023. </manager>
  1024. <manager name="ModuleLoad" language="en_US">
  1025. <synopsis>
  1026. Module management.
  1027. </synopsis>
  1028. <syntax>
  1029. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  1030. <parameter name="Module">
  1031. <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
  1032. <enumlist>
  1033. <enum name="cdr" />
  1034. <enum name="dnsmgr" />
  1035. <enum name="extconfig" />
  1036. <enum name="enum" />
  1037. <enum name="acl" />
  1038. <enum name="manager" />
  1039. <enum name="http" />
  1040. <enum name="logger" />
  1041. <enum name="features" />
  1042. <enum name="dsp" />
  1043. <enum name="udptl" />
  1044. <enum name="indications" />
  1045. <enum name="cel" />
  1046. <enum name="plc" />
  1047. </enumlist>
  1048. </parameter>
  1049. <parameter name="LoadType" required="true">
  1050. <para>The operation to be done on module. Subsystem identifiers may only
  1051. be reloaded.</para>
  1052. <enumlist>
  1053. <enum name="load" />
  1054. <enum name="unload" />
  1055. <enum name="reload" />
  1056. </enumlist>
  1057. <para>If no module is specified for a <literal>reload</literal> loadtype,
  1058. all modules are reloaded.</para>
  1059. </parameter>
  1060. </syntax>
  1061. <description>
  1062. <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
  1063. </description>
  1064. <see-also>
  1065. <ref type="manager">Reload</ref>
  1066. <ref type="manager">ModuleCheck</ref>
  1067. </see-also>
  1068. </manager>
  1069. <manager name="ModuleCheck" language="en_US">
  1070. <synopsis>
  1071. Check if module is loaded.
  1072. </synopsis>
  1073. <syntax>
  1074. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  1075. <parameter name="Module" required="true">
  1076. <para>Asterisk module name (not including extension).</para>
  1077. </parameter>
  1078. </syntax>
  1079. <description>
  1080. <para>Checks if Asterisk module is loaded. Will return Success/Failure.
  1081. For success returns, the module revision number is included.</para>
  1082. </description>
  1083. <see-also>
  1084. <ref type="manager">ModuleLoad</ref>
  1085. </see-also>
  1086. </manager>
  1087. <manager name="AOCMessage" language="en_US">
  1088. <synopsis>
  1089. Generate an Advice of Charge message on a channel.
  1090. </synopsis>
  1091. <syntax>
  1092. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  1093. <parameter name="Channel" required="true">
  1094. <para>Channel name to generate the AOC message on.</para>
  1095. </parameter>
  1096. <parameter name="ChannelPrefix">
  1097. <para>Partial channel prefix. By using this option one can match the beginning part
  1098. of a channel name without having to put the entire name in. For example
  1099. if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
  1100. that channel matches and the message will be sent. Note however that only
  1101. the first matched channel has the message sent on it. </para>
  1102. </parameter>
  1103. <parameter name="MsgType" required="true">
  1104. <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
  1105. <enumlist>
  1106. <enum name="D" />
  1107. <enum name="E" />
  1108. </enumlist>
  1109. </parameter>
  1110. <parameter name="ChargeType" required="true">
  1111. <para>Defines what kind of charge this message represents.</para>
  1112. <enumlist>
  1113. <enum name="NA" />
  1114. <enum name="FREE" />
  1115. <enum name="Currency" />
  1116. <enum name="Unit" />
  1117. </enumlist>
  1118. </parameter>
  1119. <parameter name="UnitAmount(0)">
  1120. <para>This represents the amount of units charged. The ETSI AOC standard specifies that
  1121. this value along with the optional UnitType value are entries in a list. To accommodate this
  1122. these values take an index value starting at 0 which can be used to generate this list of
  1123. unit entries. For Example, If two unit entires were required this could be achieved by setting the
  1124. paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
  1125. required when ChargeType=Unit, all other entries in the list are optional.
  1126. </para>
  1127. </parameter>
  1128. <parameter name="UnitType(0)">
  1129. <para>Defines the type of unit. ETSI AOC standard specifies this as an integer
  1130. value between 1 and 16, but this value is left open to accept any positive
  1131. integer. Like the UnitAmount parameter, this value represents a list entry
  1132. and has an index parameter that starts at 0.
  1133. </para>
  1134. </parameter>
  1135. <parameter name="CurrencyName">
  1136. <para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
  1137. </parameter>
  1138. <parameter name="CurrencyAmount">
  1139. <para>Specifies the charge unit amount as a positive integer. This value is required
  1140. when ChargeType==Currency.</para>
  1141. </parameter>
  1142. <parameter name="CurrencyMultiplier">
  1143. <para>Specifies the currency multiplier. This value is required when ChargeType==Currency.</para>
  1144. <enumlist>
  1145. <enum name="OneThousandth" />
  1146. <enum name="OneHundredth" />
  1147. <enum name="OneTenth" />
  1148. <enum name="One" />
  1149. <enum name="Ten" />
  1150. <enum name="Hundred" />
  1151. <enum name="Thousand" />
  1152. </enumlist>
  1153. </parameter>
  1154. <parameter name="TotalType" default="Total">
  1155. <para>Defines what kind of AOC-D total is represented.</para>
  1156. <enumlist>
  1157. <enum name="Total" />
  1158. <enum name="SubTotal" />
  1159. </enumlist>
  1160. </parameter>
  1161. <parameter name="AOCBillingId">
  1162. <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
  1163. that only the first 3 items of the enum are valid AOC-D billing IDs</para>
  1164. <enumlist>
  1165. <enum name="Normal" />
  1166. <enum name="ReverseCharge" />
  1167. <enum name="CreditCard" />
  1168. <enum name="CallFwdUnconditional" />
  1169. <enum name="CallFwdBusy" />
  1170. <enum name="CallFwdNoReply" />
  1171. <enum name="CallDeflection" />
  1172. <enum name="CallTransfer" />
  1173. </enumlist>
  1174. </parameter>
  1175. <parameter name="ChargingAssociationId">
  1176. <para>Charging association identifier. This is optional for AOC-E and can be
  1177. set to any value between -32768 and 32767</para>
  1178. </parameter>
  1179. <parameter name="ChargingAssociationNumber">
  1180. <para>Represents the charging association party number. This value is optional
  1181. for AOC-E.</para>
  1182. </parameter>
  1183. <parameter name="ChargingAssociationPlan">
  1184. <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
  1185. The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
  1186. numbering-plan-identification fields.</para>
  1187. </parameter>
  1188. </syntax>
  1189. <description>
  1190. <para>Generates an AOC-D or AOC-E message on a channel.</para>
  1191. </description>
  1192. <see-also>
  1193. <ref type="managerEvent">AOC-D</ref>
  1194. <ref type="managerEvent">AOC-E</ref>
  1195. </see-also>
  1196. </manager>
  1197. <function name="AMI_CLIENT" language="en_US">
  1198. <synopsis>
  1199. Checks attributes of manager accounts
  1200. </synopsis>
  1201. <syntax>
  1202. <parameter name="loginname" required="true">
  1203. <para>Login name, specified in manager.conf</para>
  1204. </parameter>
  1205. <parameter name="field" required="true">
  1206. <para>The manager account attribute to return</para>
  1207. <enumlist>
  1208. <enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
  1209. </enumlist>
  1210. </parameter>
  1211. </syntax>
  1212. <description>
  1213. <para>
  1214. Currently, the only supported parameter is "sessions" which will return the current number of
  1215. active sessions for this AMI account.
  1216. </para>
  1217. </description>
  1218. </function>
  1219. <manager name="Filter" language="en_US">
  1220. <synopsis>
  1221. Dynamically add filters for the current manager session.
  1222. </synopsis>
  1223. <syntax>
  1224. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  1225. <parameter name="Operation">
  1226. <enumlist>
  1227. <enum name="Add">
  1228. <para>Add a filter.</para>
  1229. </enum>
  1230. </enumlist>
  1231. </parameter>
  1232. <parameter name="Filter">
  1233. <para>Filters can be whitelist or blacklist</para>
  1234. <para>Example whitelist filter: "Event: Newchannel"</para>
  1235. <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
  1236. <para>This filter option is used to whitelist or blacklist events per user to be
  1237. reported with regular expressions and are allowed if both the regex matches
  1238. and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
  1239. unless preceeded by an exclamation point, which marks it as being black.
  1240. Evaluation of the filters is as follows:</para>
  1241. <para>- If no filters are configured all events are reported as normal.</para>
  1242. <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
  1243. <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
  1244. <para>- If there are both white and black filters: implied black all filter processed first, then white
  1245. filters, and lastly black filters.</para>
  1246. </parameter>
  1247. </syntax>
  1248. <description>
  1249. <para>The filters added are only used for the current session.
  1250. Once the connection is closed the filters are removed.</para>
  1251. <para>This comand requires the system permission because
  1252. this command can be used to create filters that may bypass
  1253. filters defined in manager.conf</para>
  1254. </description>
  1255. <see-also>
  1256. <ref type="manager">FilterList</ref>
  1257. </see-also>
  1258. </manager>
  1259. <manager name="FilterList" language="en_US">
  1260. <synopsis>
  1261. Show current event filters for this session
  1262. </synopsis>
  1263. <description>
  1264. <para>The filters displayed are for the current session. Only those filters defined in
  1265. manager.conf will be present upon starting a new session.</para>
  1266. </description>
  1267. <see-also>
  1268. <ref type="manager">Filter</ref>
  1269. </see-also>
  1270. </manager>
  1271. <manager name="BlindTransfer" language="en_US">
  1272. <synopsis>
  1273. Blind transfer channel(s) to the given destination
  1274. </synopsis>
  1275. <syntax>
  1276. <parameter name="Channel" required="true">
  1277. </parameter>
  1278. <parameter name="Context">
  1279. </parameter>
  1280. <parameter name="Exten">
  1281. </parameter>
  1282. </syntax>
  1283. <description>
  1284. <para>Redirect all channels currently bridged to the specified channel to the specified destination.</para>
  1285. </description>
  1286. <see-also>
  1287. <ref type="manager">Redirect</ref>
  1288. <ref type="managerEvent">BlindTransfer</ref>
  1289. </see-also>
  1290. </manager>
  1291. <managerEvent name="ExtensionStatus" language="en_US">
  1292. <managerEventInstance class="EVENT_FLAG_CALL">
  1293. <synopsis>Raised when a hint changes due to a device state change.</synopsis>
  1294. <syntax>
  1295. <parameter name="Exten">
  1296. <para>Name of the extension.</para>
  1297. </parameter>
  1298. <parameter name="Context">
  1299. <para>Context that owns the extension.</para>
  1300. </parameter>
  1301. <parameter name="Hint">
  1302. <para>Hint set for the extension</para>
  1303. </parameter>
  1304. <parameter name="Status">
  1305. <para>Numerical value of the extension status. Extension
  1306. status is determined by the combined device state of all items
  1307. contained in the hint.</para>
  1308. <enumlist>
  1309. <enum name="-2">
  1310. <para>The extension was removed from the dialplan.</para>
  1311. </enum>
  1312. <enum name="-1">
  1313. <para>The extension's hint was removed from the dialplan.</para>
  1314. </enum>
  1315. <enum name="0">
  1316. <para><literal>Idle</literal> - Related device(s) are in an idle
  1317. state.</para>
  1318. </enum>
  1319. <enum name="1">
  1320. <para><literal>InUse</literal> - Related device(s) are in active
  1321. calls but may take more calls.</para>
  1322. </enum>
  1323. <enum name="2">
  1324. <para><literal>Busy</literal> - Related device(s) are in active
  1325. calls and may not take any more calls.</para>
  1326. </enum>
  1327. <enum name="4">
  1328. <para><literal>Unavailable</literal> - Related device(s) are
  1329. not reachable.</para>
  1330. </enum>
  1331. <enum name="8">
  1332. <para><literal>Ringing</literal> - Related device(s) are
  1333. currently ringing.</para>
  1334. </enum>
  1335. <enum name="9">
  1336. <para><literal>InUse&amp;Ringing</literal> - Related device(s)
  1337. are currently ringing and in active calls.</para>
  1338. </enum>
  1339. <enum name="16">
  1340. <para><literal>Hold</literal> - Related device(s) are
  1341. currently on hold.</para>
  1342. </enum>
  1343. <enum name="17">
  1344. <para><literal>InUse&amp;Hold</literal> - Related device(s)
  1345. are currently on hold and in active calls.</para>
  1346. </enum>
  1347. </enumlist>
  1348. </parameter>
  1349. <parameter name="StatusText">
  1350. <para>Text representation of <literal>Status</literal>.</para>
  1351. <enumlist>
  1352. <enum name="Idle" />
  1353. <enum name="InUse" />
  1354. <enum name="Busy" />
  1355. <enum name="Unavailable" />
  1356. <enum name="Ringing" />
  1357. <enum name="InUse&amp;Ringing" />
  1358. <enum name="Hold" />
  1359. <enum name="InUse&amp;Hold" />
  1360. <enum name="Unknown">
  1361. <para>Status does not match any of the above values.</para>
  1362. </enum>
  1363. </enumlist>
  1364. </parameter>
  1365. </syntax>
  1366. <see-also>
  1367. <ref type="manager">ExtensionState</ref>
  1368. </see-also>
  1369. </managerEventInstance>
  1370. </managerEvent>
  1371. <managerEvent name="PresenceStatus" language="en_US">
  1372. <managerEventInstance class="EVENT_FLAG_CALL">
  1373. <synopsis>Raised when a hint changes due to a presence state change.</synopsis>
  1374. <syntax>
  1375. <parameter name="Exten" />
  1376. <parameter name="Context" />
  1377. <parameter name="Hint" />
  1378. <parameter name="Status" />
  1379. <parameter name="Subtype" />
  1380. <parameter name="Message" />
  1381. </syntax>
  1382. <see-also>
  1383. <ref type="manager">PresenceState</ref>
  1384. </see-also>
  1385. </managerEventInstance>
  1386. </managerEvent>
  1387. ***/
  1388. /*! \addtogroup Group_AMI AMI functions
  1389. */
  1390. /*! @{
  1391. Doxygen group */
  1392. enum error_type {
  1393. UNKNOWN_ACTION = 1,
  1394. UNKNOWN_CATEGORY,
  1395. UNSPECIFIED_CATEGORY,
  1396. UNSPECIFIED_ARGUMENT,
  1397. FAILURE_ALLOCATION,
  1398. FAILURE_NEWCAT,
  1399. FAILURE_DELCAT,
  1400. FAILURE_EMPTYCAT,
  1401. FAILURE_UPDATE,
  1402. FAILURE_DELETE,
  1403. FAILURE_APPEND,
  1404. FAILURE_TEMPLATE
  1405. };
  1406. enum add_filter_result {
  1407. FILTER_SUCCESS,
  1408. FILTER_ALLOC_FAILED,
  1409. FILTER_COMPILE_FAIL,
  1410. };
  1411. /*!
  1412. * Linked list of events.
  1413. * Global events are appended to the list by append_event().
  1414. * The usecount is the number of stored pointers to the element,
  1415. * excluding the list pointers. So an element that is only in
  1416. * the list has a usecount of 0, not 1.
  1417. *
  1418. * Clients have a pointer to the last event processed, and for each
  1419. * of these clients we track the usecount of the elements.
  1420. * If we have a pointer to an entry in the list, it is safe to navigate
  1421. * it forward because elements will not be deleted, but only appended.
  1422. * The worst that can happen is seeing the pointer still NULL.
  1423. *
  1424. * When the usecount of an element drops to 0, and the element is the
  1425. * first in the list, we can remove it. Removal is done within the
  1426. * main thread, which is woken up for the purpose.
  1427. *
  1428. * For simplicity of implementation, we make sure the list is never empty.
  1429. */
  1430. struct eventqent {
  1431. int usecount; /*!< # of clients who still need the event */
  1432. int category;
  1433. unsigned int seq; /*!< sequence number */
  1434. struct timeval tv; /*!< When event was allocated */
  1435. AST_RWLIST_ENTRY(eventqent) eq_next;
  1436. char eventdata[1]; /*!< really variable size, allocated by append_event() */
  1437. };
  1438. static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
  1439. static int displayconnects = 1;
  1440. static int allowmultiplelogin = 1;
  1441. static int timestampevents;
  1442. static int httptimeout = 60;
  1443. static int broken_events_action = 0;
  1444. static int manager_enabled = 0;
  1445. static int subscribed = 0;
  1446. static int webmanager_enabled = 0;
  1447. static int manager_debug = 0; /*!< enable some debugging code in the manager */
  1448. static int authtimeout;
  1449. static int authlimit;
  1450. static char *manager_channelvars;
  1451. #define DEFAULT_REALM "asterisk"
  1452. static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
  1453. static int unauth_sessions = 0;
  1454. static struct stasis_subscription *acl_change_sub;
  1455. /*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
  1456. static struct stasis_topic *manager_topic;
  1457. /*! \brief The \ref stasis_message_router for all \ref stasis messages */
  1458. static struct stasis_message_router *stasis_router;
  1459. /*! \brief The \ref stasis_subscription for forwarding the RTP topic to the AMI topic */
  1460. static struct stasis_forward *rtp_topic_forwarder;
  1461. /*! \brief The \ref stasis_subscription for forwarding the Security topic to the AMI topic */
  1462. static struct stasis_forward *security_topic_forwarder;
  1463. #ifdef TEST_FRAMEWORK
  1464. /*! \brief The \ref stasis_subscription for forwarding the Test topic to the AMI topic */
  1465. static struct stasis_forward *test_suite_forwarder;
  1466. #endif
  1467. #define MGR_SHOW_TERMINAL_WIDTH 80
  1468. #define MAX_VARS 128
  1469. /*! \brief Fake event class used to end sessions at shutdown */
  1470. #define EVENT_FLAG_SHUTDOWN -1
  1471. /*! \brief
  1472. * Descriptor for a manager session, either on the AMI socket or over HTTP.
  1473. *
  1474. * \note
  1475. * AMI session have managerid == 0; the entry is created upon a connect,
  1476. * and destroyed with the socket.
  1477. * HTTP sessions have managerid != 0, the value is used as a search key
  1478. * to lookup sessions (using the mansession_id cookie, or nonce key from
  1479. * Digest Authentication http header).
  1480. */
  1481. #define MAX_BLACKLIST_CMD_LEN 2
  1482. static const struct {
  1483. const char *words[AST_MAX_CMD_LEN];
  1484. } command_blacklist[] = {
  1485. {{ "module", "load", NULL }},
  1486. {{ "module", "unload", NULL }},
  1487. {{ "restart", "gracefully", NULL }},
  1488. };
  1489. static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
  1490. static void acl_change_stasis_subscribe(void)
  1491. {
  1492. if (!acl_change_sub) {
  1493. acl_change_sub = stasis_subscribe(ast_security_topic(),
  1494. acl_change_stasis_cb, NULL);
  1495. stasis_subscription_accept_message_type(acl_change_sub, ast_named_acl_change_type());
  1496. stasis_subscription_set_filter(acl_change_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
  1497. }
  1498. }
  1499. static void acl_change_stasis_unsubscribe(void)
  1500. {
  1501. acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
  1502. }
  1503. /* In order to understand what the heck is going on with the
  1504. * mansession_session and mansession structs, we need to have a bit of a history
  1505. * lesson.
  1506. *
  1507. * In the beginning, there was the mansession. The mansession contained data that was
  1508. * intrinsic to a manager session, such as the time that it started, the name of the logged-in
  1509. * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
  1510. * sessions, these were used to represent the TCP socket over which the AMI session was taking
  1511. * place. It makes perfect sense for these fields to be a part of the session-specific data since
  1512. * the session actually defines this information.
  1513. *
  1514. * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
  1515. * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
  1516. * but rather to the action that is being executed. Because a single session may execute many commands
  1517. * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
  1518. * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
  1519. * has had a chance to properly close its handles.
  1520. *
  1521. * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
  1522. * from being run at the same time in a single session. Some manager actions may block for a long time, thus
  1523. * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
  1524. * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
  1525. * part of the action instead.
  1526. *
  1527. * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
  1528. * contain the action-specific information, such as which file to write to. In order to maintain expectations
  1529. * of action handlers and not have to change the public API of the manager code, we would need to name this
  1530. * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
  1531. * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
  1532. * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
  1533. * data.
  1534. */
  1535. struct mansession_session {
  1536. /*! \todo XXX need to document which fields it is protecting */
  1537. struct ast_sockaddr addr; /*!< address we are connecting from */
  1538. FILE *f; /*!< fdopen() on the underlying fd */
  1539. int fd; /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
  1540. int inuse; /*!< number of HTTP sessions using this entry */
  1541. int needdestroy; /*!< Whether an HTTP session should be destroyed */
  1542. pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
  1543. uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
  1544. time_t sessionstart; /*!< Session start time */
  1545. struct timeval sessionstart_tv; /*!< Session start time */
  1546. time_t sessiontimeout; /*!< Session timeout if HTTP */
  1547. char username[80]; /*!< Logged in username */
  1548. char challenge[10]; /*!< Authentication challenge */
  1549. int authenticated; /*!< Authentication status */
  1550. int readperm; /*!< Authorization for reading */
  1551. int writeperm; /*!< Authorization for writing */
  1552. char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
  1553. int inlen; /*!< number of buffered bytes */
  1554. struct ao2_container *whitefilters; /*!< Manager event filters - white list */
  1555. struct ao2_container *blackfilters; /*!< Manager event filters - black list */
  1556. struct ast_variable *chanvars; /*!< Channel variables to set for originate */
  1557. int send_events; /*!< XXX what ? */
  1558. struct eventqent *last_ev; /*!< last event processed. */
  1559. int writetimeout; /*!< Timeout for ast_carefulwrite() */
  1560. time_t authstart;
  1561. int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
  1562. time_t noncetime; /*!< Timer for nonce value expiration */
  1563. unsigned long oldnonce; /*!< Stale nonce value */
  1564. unsigned long nc; /*!< incremental nonce counter */
  1565. AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
  1566. AST_LIST_ENTRY(mansession_session) list;
  1567. };
  1568. enum mansession_message_parsing {
  1569. MESSAGE_OKAY,
  1570. MESSAGE_LINE_TOO_LONG
  1571. };
  1572. /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
  1573. * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
  1574. * represents data that is different from Manager action to Manager action. The mansession_session pointer
  1575. * contained within points to session-specific data.
  1576. */
  1577. struct mansession {
  1578. struct mansession_session *session;
  1579. struct ast_tcptls_session_instance *tcptls_session;
  1580. FILE *f;
  1581. int fd;
  1582. enum mansession_message_parsing parsing;
  1583. int write_error:1;
  1584. struct manager_custom_hook *hook;
  1585. ast_mutex_t lock;
  1586. };
  1587. /*! Active manager connection sessions container. */
  1588. static AO2_GLOBAL_OBJ_STATIC(mgr_sessions);
  1589. /*! \brief user descriptor, as read from the config file.
  1590. *
  1591. * \note It is still missing some fields -- e.g. we can have multiple permit and deny
  1592. * lines which are not supported here, and readperm/writeperm/writetimeout
  1593. * are not stored.
  1594. */
  1595. struct ast_manager_user {
  1596. char username[80];
  1597. char *secret; /*!< Secret for logging in */
  1598. int readperm; /*!< Authorization for reading */
  1599. int writeperm; /*!< Authorization for writing */
  1600. int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
  1601. int displayconnects; /*!< XXX unused */
  1602. int allowmultiplelogin; /*!< Per user option*/
  1603. int keep; /*!< mark entries created on a reload */
  1604. struct ao2_container *whitefilters; /*!< Manager event filters - white list */
  1605. struct ao2_container *blackfilters; /*!< Manager event filters - black list */
  1606. struct ast_acl_list *acl; /*!< ACL setting */
  1607. char *a1_hash; /*!< precalculated A1 for Digest auth */
  1608. struct ast_variable *chanvars; /*!< Channel variables to set for originate */
  1609. AST_RWLIST_ENTRY(ast_manager_user) list;
  1610. };
  1611. /*! \brief list of users found in the config file */
  1612. static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
  1613. /*! \brief list of actions registered */
  1614. static AST_RWLIST_HEAD_STATIC(actions, manager_action);
  1615. /*! \brief list of hooks registered */
  1616. static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
  1617. #ifdef AST_XML_DOCS
  1618. /*! \brief A container of event documentation nodes */
  1619. static AO2_GLOBAL_OBJ_STATIC(event_docs);
  1620. #endif
  1621. static int __attribute__((format(printf, 9, 0))) __manager_event_sessions(
  1622. struct ao2_container *sessions,
  1623. int category,
  1624. const char *event,
  1625. int chancount,
  1626. struct ast_channel **chans,
  1627. const char *file,
  1628. int line,
  1629. const char *func,
  1630. const char *fmt,
  1631. ...);
  1632. static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
  1633. static int match_filter(struct mansession *s, char *eventdata);
  1634. /*!
  1635. * @{ \brief Define AMI message types.
  1636. */
  1637. STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
  1638. /*! @} */
  1639. /*!
  1640. * \internal
  1641. * \brief Find a registered action object.
  1642. *
  1643. * \param name Name of AMI action to find.
  1644. *
  1645. * \return Reffed action found or NULL
  1646. */
  1647. static struct manager_action *action_find(const char *name)
  1648. {
  1649. struct manager_action *act;
  1650. AST_RWLIST_RDLOCK(&actions);
  1651. AST_RWLIST_TRAVERSE(&actions, act, list) {
  1652. if (!strcasecmp(name, act->action)) {
  1653. ao2_t_ref(act, +1, "found action object");
  1654. break;
  1655. }
  1656. }
  1657. AST_RWLIST_UNLOCK(&actions);
  1658. return act;
  1659. }
  1660. struct stasis_topic *ast_manager_get_topic(void)
  1661. {
  1662. return manager_topic;
  1663. }
  1664. struct stasis_message_router *ast_manager_get_message_router(void)
  1665. {
  1666. return stasis_router;
  1667. }
  1668. static void manager_json_value_str_append(struct ast_json *value, const char *key,
  1669. struct ast_str **res)
  1670. {
  1671. switch (ast_json_typeof(value)) {
  1672. case AST_JSON_STRING:
  1673. ast_str_append(res, 0, "%s: %s\r\n", key, ast_json_string_get(value));
  1674. break;
  1675. case AST_JSON_INTEGER:
  1676. ast_str_append(res, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
  1677. break;
  1678. case AST_JSON_TRUE:
  1679. ast_str_append(res, 0, "%s: True\r\n", key);
  1680. break;
  1681. case AST_JSON_FALSE:
  1682. ast_str_append(res, 0, "%s: False\r\n", key);
  1683. break;
  1684. default:
  1685. ast_str_append(res, 0, "%s: \r\n", key);
  1686. break;
  1687. }
  1688. }
  1689. static void manager_json_to_ast_str(struct ast_json *obj, const char *key,
  1690. struct ast_str **res, key_exclusion_cb exclusion_cb);
  1691. static void manager_json_array_with_key(struct ast_json *obj, const char* key,
  1692. size_t index, struct ast_str **res,
  1693. key_exclusion_cb exclusion_cb)
  1694. {
  1695. struct ast_str *key_str = ast_str_alloca(64);
  1696. ast_str_set(&key_str, 0, "%s(%zu)", key, index);
  1697. manager_json_to_ast_str(obj, ast_str_buffer(key_str),
  1698. res, exclusion_cb);
  1699. }
  1700. static void manager_json_obj_with_key(struct ast_json *obj, const char* key,
  1701. const char *parent_key, struct ast_str **res,
  1702. key_exclusion_cb exclusion_cb)
  1703. {
  1704. if (parent_key) {
  1705. struct ast_str *key_str = ast_str_alloca(64);
  1706. ast_str_set(&key_str, 0, "%s/%s", parent_key, key);
  1707. manager_json_to_ast_str(obj, ast_str_buffer(key_str),
  1708. res, exclusion_cb);
  1709. return;
  1710. }
  1711. manager_json_to_ast_str(obj, key, res, exclusion_cb);
  1712. }
  1713. void manager_json_to_ast_str(struct ast_json *obj, const char *key,
  1714. struct ast_str **res, key_exclusion_cb exclusion_cb)
  1715. {
  1716. struct ast_json_iter *i;
  1717. /* If obj or res is not given, just return */
  1718. if (!obj || !res) {
  1719. return;
  1720. }
  1721. if (!*res && !(*res = ast_str_create(1024))) {
  1722. return;
  1723. }
  1724. if (exclusion_cb && key && exclusion_cb(key)) {
  1725. return;
  1726. }
  1727. if (ast_json_typeof(obj) != AST_JSON_OBJECT &&
  1728. ast_json_typeof(obj) != AST_JSON_ARRAY) {
  1729. manager_json_value_str_append(obj, key, res);
  1730. return;
  1731. }
  1732. if (ast_json_typeof(obj) == AST_JSON_ARRAY) {
  1733. size_t j;
  1734. for (j = 0; j < ast_json_array_size(obj); ++j) {
  1735. manager_json_array_with_key(ast_json_array_get(obj, j),
  1736. key, j, res, exclusion_cb);
  1737. }
  1738. return;
  1739. }
  1740. for (i = ast_json_object_iter(obj); i;
  1741. i = ast_json_object_iter_next(obj, i)) {
  1742. manager_json_obj_with_key(ast_json_object_iter_value(i),
  1743. ast_json_object_iter_key(i),
  1744. key, res, exclusion_cb);
  1745. }
  1746. }
  1747. struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
  1748. {
  1749. struct ast_str *res = ast_str_create(1024);
  1750. if (!ast_json_is_null(blob)) {
  1751. manager_json_to_ast_str(blob, NULL, &res, exclusion_cb);
  1752. }
  1753. return res;
  1754. }
  1755. #define manager_event_sessions(sessions, category, event, contents , ...) \
  1756. __manager_event_sessions(sessions, category, event, 0, NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, contents , ## __VA_ARGS__)
  1757. #define any_manager_listeners(sessions) \
  1758. ((sessions && ao2_container_count(sessions)) || !AST_RWLIST_EMPTY(&manager_hooks))
  1759. static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
  1760. struct stasis_message *message)
  1761. {
  1762. struct ao2_container *sessions;
  1763. struct ast_manager_event_blob *ev;
  1764. if (!stasis_message_can_be_ami(message)) {
  1765. /* Not an AMI message; disregard */
  1766. return;
  1767. }
  1768. sessions = ao2_global_obj_ref(mgr_sessions);
  1769. if (!any_manager_listeners(sessions)) {
  1770. /* Nobody is listening */
  1771. ao2_cleanup(sessions);
  1772. return;
  1773. }
  1774. ev = stasis_message_to_ami(message);
  1775. if (!ev) {
  1776. /* Conversion failure */
  1777. ao2_cleanup(sessions);
  1778. return;
  1779. }
  1780. manager_event_sessions(sessions, ev->event_flags, ev->manager_event,
  1781. "%s", ev->extra_fields);
  1782. ao2_ref(ev, -1);
  1783. ao2_cleanup(sessions);
  1784. }
  1785. static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
  1786. struct stasis_message *message)
  1787. {
  1788. struct ast_json_payload *payload;
  1789. int class_type;
  1790. const char *type;
  1791. struct ast_json *event;
  1792. struct ast_str *event_buffer;
  1793. struct ao2_container *sessions;
  1794. sessions = ao2_global_obj_ref(mgr_sessions);
  1795. if (!any_manager_listeners(sessions)) {
  1796. /* Nobody is listening */
  1797. ao2_cleanup(sessions);
  1798. return;
  1799. }
  1800. payload = stasis_message_data(message);
  1801. class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
  1802. type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
  1803. event = ast_json_object_get(payload->json, "event");
  1804. event_buffer = ast_manager_str_from_json_object(event, NULL);
  1805. if (!event_buffer) {
  1806. ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
  1807. ao2_cleanup(sessions);
  1808. return;
  1809. }
  1810. manager_event_sessions(sessions, class_type, type,
  1811. "%s", ast_str_buffer(event_buffer));
  1812. ast_free(event_buffer);
  1813. ao2_cleanup(sessions);
  1814. }
  1815. void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
  1816. {
  1817. RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
  1818. RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
  1819. RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
  1820. if (!obj || !ast_manager_get_generic_type()) {
  1821. return;
  1822. }
  1823. ast_json_ref(obj);
  1824. event_info = ast_json_pack("{s: s, s: i, s: o}",
  1825. "type", type,
  1826. "class_type", class_type,
  1827. "event", obj);
  1828. if (!event_info) {
  1829. return;
  1830. }
  1831. payload = ast_json_payload_create(event_info);
  1832. if (!payload) {
  1833. return;
  1834. }
  1835. message = stasis_message_create(ast_manager_get_generic_type(), payload);
  1836. if (!message) {
  1837. return;
  1838. }
  1839. stasis_publish(ast_manager_get_topic(), message);
  1840. }
  1841. /*! \brief Add a custom hook to be called when an event is fired */
  1842. void ast_manager_register_hook(struct manager_custom_hook *hook)
  1843. {
  1844. AST_RWLIST_WRLOCK(&manager_hooks);
  1845. AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
  1846. AST_RWLIST_UNLOCK(&manager_hooks);
  1847. }
  1848. /*! \brief Delete a custom hook to be called when an event is fired */
  1849. void ast_manager_unregister_hook(struct manager_custom_hook *hook)
  1850. {
  1851. AST_RWLIST_WRLOCK(&manager_hooks);
  1852. AST_RWLIST_REMOVE(&manager_hooks, hook, list);
  1853. AST_RWLIST_UNLOCK(&manager_hooks);
  1854. }
  1855. int check_manager_enabled(void)
  1856. {
  1857. return manager_enabled;
  1858. }
  1859. int check_webmanager_enabled(void)
  1860. {
  1861. return (webmanager_enabled && manager_enabled);
  1862. }
  1863. /*!
  1864. * Grab a reference to the last event, update usecount as needed.
  1865. * Can handle a NULL pointer.
  1866. */
  1867. static struct eventqent *grab_last(void)
  1868. {
  1869. struct eventqent *ret;
  1870. AST_RWLIST_WRLOCK(&all_events);
  1871. ret = AST_RWLIST_LAST(&all_events);
  1872. /* the list is never empty now, but may become so when
  1873. * we optimize it in the future, so be prepared.
  1874. */
  1875. if (ret) {
  1876. ast_atomic_fetchadd_int(&ret->usecount, 1);
  1877. }
  1878. AST_RWLIST_UNLOCK(&all_events);
  1879. return ret;
  1880. }
  1881. /*!
  1882. * Purge unused events. Remove elements from the head
  1883. * as long as their usecount is 0 and there is a next element.
  1884. */
  1885. static void purge_events(void)
  1886. {
  1887. struct eventqent *ev;
  1888. struct timeval now = ast_tvnow();
  1889. AST_RWLIST_WRLOCK(&all_events);
  1890. while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
  1891. ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
  1892. AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
  1893. ast_free(ev);
  1894. }
  1895. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
  1896. /* Never release the last event */
  1897. if (!AST_RWLIST_NEXT(ev, eq_next)) {
  1898. break;
  1899. }
  1900. /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
  1901. if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
  1902. AST_RWLIST_REMOVE_CURRENT(eq_next);
  1903. ast_free(ev);
  1904. }
  1905. }
  1906. AST_RWLIST_TRAVERSE_SAFE_END;
  1907. AST_RWLIST_UNLOCK(&all_events);
  1908. }
  1909. /*!
  1910. * helper functions to convert back and forth between
  1911. * string and numeric representation of set of flags
  1912. */
  1913. static const struct permalias {
  1914. int num;
  1915. const char *label;
  1916. } perms[] = {
  1917. { EVENT_FLAG_SYSTEM, "system" },
  1918. { EVENT_FLAG_CALL, "call" },
  1919. { EVENT_FLAG_LOG, "log" },
  1920. { EVENT_FLAG_VERBOSE, "verbose" },
  1921. { EVENT_FLAG_COMMAND, "command" },
  1922. { EVENT_FLAG_AGENT, "agent" },
  1923. { EVENT_FLAG_USER, "user" },
  1924. { EVENT_FLAG_CONFIG, "config" },
  1925. { EVENT_FLAG_DTMF, "dtmf" },
  1926. { EVENT_FLAG_REPORTING, "reporting" },
  1927. { EVENT_FLAG_CDR, "cdr" },
  1928. { EVENT_FLAG_DIALPLAN, "dialplan" },
  1929. { EVENT_FLAG_ORIGINATE, "originate" },
  1930. { EVENT_FLAG_AGI, "agi" },
  1931. { EVENT_FLAG_CC, "cc" },
  1932. { EVENT_FLAG_AOC, "aoc" },
  1933. { EVENT_FLAG_TEST, "test" },
  1934. { EVENT_FLAG_SECURITY, "security" },
  1935. { EVENT_FLAG_MESSAGE, "message" },
  1936. { INT_MAX, "all" },
  1937. { 0, "none" },
  1938. };
  1939. /*! Maximum string length of the AMI authority permission string buildable from perms[]. */
  1940. #define MAX_AUTH_PERM_STRING 150
  1941. /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
  1942. static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
  1943. {
  1944. if (!(writepermlist & EVENT_FLAG_SYSTEM)
  1945. && (
  1946. strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
  1947. strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
  1948. )) {
  1949. return 0;
  1950. }
  1951. return 1;
  1952. }
  1953. /*! \brief Convert authority code to a list of options for a user. This will only
  1954. * display those authority codes that have an explicit match on authority */
  1955. static const char *user_authority_to_str(int authority, struct ast_str **res)
  1956. {
  1957. int i;
  1958. char *sep = "";
  1959. ast_str_reset(*res);
  1960. for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
  1961. if ((authority & perms[i].num) == perms[i].num) {
  1962. ast_str_append(res, 0, "%s%s", sep, perms[i].label);
  1963. sep = ",";
  1964. }
  1965. }
  1966. if (ast_str_strlen(*res) == 0) {
  1967. /* replace empty string with something sensible */
  1968. ast_str_append(res, 0, "<none>");
  1969. }
  1970. return ast_str_buffer(*res);
  1971. }
  1972. /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
  1973. * authority will always be returned. */
  1974. static const char *authority_to_str(int authority, struct ast_str **res)
  1975. {
  1976. int i;
  1977. char *sep = "";
  1978. ast_str_reset(*res);
  1979. if (authority != EVENT_FLAG_SHUTDOWN) {
  1980. for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
  1981. if (authority & perms[i].num) {
  1982. ast_str_append(res, 0, "%s%s", sep, perms[i].label);
  1983. sep = ",";
  1984. }
  1985. }
  1986. }
  1987. if (ast_str_strlen(*res) == 0) {
  1988. /* replace empty string with something sensible */
  1989. ast_str_append(res, 0, "<none>");
  1990. }
  1991. return ast_str_buffer(*res);
  1992. }
  1993. /*! Tells you if smallstr exists inside bigstr
  1994. which is delim by delim and uses no buf or stringsep
  1995. ast_instring("this|that|more","this",'|') == 1;
  1996. feel free to move this to app.c -anthm */
  1997. static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
  1998. {
  1999. const char *val = bigstr, *next;
  2000. do {
  2001. if ((next = strchr(val, delim))) {
  2002. if (!strncmp(val, smallstr, (next - val))) {
  2003. return 1;
  2004. } else {
  2005. continue;
  2006. }
  2007. } else {
  2008. return !strcmp(smallstr, val);
  2009. }
  2010. } while (*(val = (next + 1)));
  2011. return 0;
  2012. }
  2013. static int get_perm(const char *instr)
  2014. {
  2015. int x = 0, ret = 0;
  2016. if (!instr) {
  2017. return 0;
  2018. }
  2019. for (x = 0; x < ARRAY_LEN(perms); x++) {
  2020. if (ast_instring(instr, perms[x].label, ',')) {
  2021. ret |= perms[x].num;
  2022. }
  2023. }
  2024. return ret;
  2025. }
  2026. /*!
  2027. * A number returns itself, false returns 0, true returns all flags,
  2028. * other strings return the flags that are set.
  2029. */
  2030. static int strings_to_mask(const char *string)
  2031. {
  2032. const char *p;
  2033. if (ast_strlen_zero(string)) {
  2034. return -1;
  2035. }
  2036. for (p = string; *p; p++) {
  2037. if (*p < '0' || *p > '9') {
  2038. break;
  2039. }
  2040. }
  2041. if (!*p) { /* all digits */
  2042. return atoi(string);
  2043. }
  2044. if (ast_false(string)) {
  2045. return 0;
  2046. }
  2047. if (ast_true(string)) { /* all permissions */
  2048. int x, ret = 0;
  2049. for (x = 0; x < ARRAY_LEN(perms); x++) {
  2050. ret |= perms[x].num;
  2051. }
  2052. return ret;
  2053. }
  2054. return get_perm(string);
  2055. }
  2056. /*! \brief Unreference manager session object.
  2057. If no more references, then go ahead and delete it */
  2058. static struct mansession_session *unref_mansession(struct mansession_session *s)
  2059. {
  2060. int refcount = ao2_ref(s, -1);
  2061. if (manager_debug) {
  2062. ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
  2063. }
  2064. return NULL;
  2065. }
  2066. static void event_filter_destructor(void *obj)
  2067. {
  2068. regex_t *regex_filter = obj;
  2069. regfree(regex_filter);
  2070. }
  2071. static void session_destructor(void *obj)
  2072. {
  2073. struct mansession_session *session = obj;
  2074. struct eventqent *eqe = session->last_ev;
  2075. struct ast_datastore *datastore;
  2076. /* Get rid of each of the data stores on the session */
  2077. while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
  2078. /* Free the data store */
  2079. ast_datastore_free(datastore);
  2080. }
  2081. if (session->f != NULL) {
  2082. fflush(session->f);
  2083. fclose(session->f);
  2084. }
  2085. if (eqe) {
  2086. ast_atomic_fetchadd_int(&eqe->usecount, -1);
  2087. }
  2088. if (session->chanvars) {
  2089. ast_variables_destroy(session->chanvars);
  2090. }
  2091. if (session->whitefilters) {
  2092. ao2_t_ref(session->whitefilters, -1, "decrement ref for white container, should be last one");
  2093. }
  2094. if (session->blackfilters) {
  2095. ao2_t_ref(session->blackfilters, -1, "decrement ref for black container, should be last one");
  2096. }
  2097. }
  2098. /*! \brief Allocate manager session structure and add it to the list of sessions */
  2099. static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
  2100. {
  2101. struct ao2_container *sessions;
  2102. struct mansession_session *newsession;
  2103. newsession = ao2_alloc(sizeof(*newsession), session_destructor);
  2104. if (!newsession) {
  2105. return NULL;
  2106. }
  2107. newsession->whitefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
  2108. newsession->blackfilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
  2109. if (!newsession->whitefilters || !newsession->blackfilters) {
  2110. ao2_ref(newsession, -1);
  2111. return NULL;
  2112. }
  2113. newsession->fd = -1;
  2114. newsession->waiting_thread = AST_PTHREADT_NULL;
  2115. newsession->writetimeout = 100;
  2116. newsession->send_events = -1;
  2117. ast_sockaddr_copy(&newsession->addr, addr);
  2118. sessions = ao2_global_obj_ref(mgr_sessions);
  2119. if (sessions) {
  2120. ao2_link(sessions, newsession);
  2121. ao2_ref(sessions, -1);
  2122. }
  2123. return newsession;
  2124. }
  2125. static int mansession_cmp_fn(void *obj, void *arg, int flags)
  2126. {
  2127. struct mansession_session *s = obj;
  2128. char *str = arg;
  2129. return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
  2130. }
  2131. static void session_destroy(struct mansession_session *s)
  2132. {
  2133. struct ao2_container *sessions;
  2134. sessions = ao2_global_obj_ref(mgr_sessions);
  2135. if (sessions) {
  2136. ao2_unlink(sessions, s);
  2137. ao2_ref(sessions, -1);
  2138. }
  2139. unref_mansession(s);
  2140. }
  2141. static int check_manager_session_inuse(const char *name)
  2142. {
  2143. struct ao2_container *sessions;
  2144. struct mansession_session *session;
  2145. int inuse = 0;
  2146. sessions = ao2_global_obj_ref(mgr_sessions);
  2147. if (sessions) {
  2148. session = ao2_find(sessions, (char *) name, 0);
  2149. ao2_ref(sessions, -1);
  2150. if (session) {
  2151. unref_mansession(session);
  2152. inuse = 1;
  2153. }
  2154. }
  2155. return inuse;
  2156. }
  2157. /*!
  2158. * lookup an entry in the list of registered users.
  2159. * must be called with the list lock held.
  2160. */
  2161. static struct ast_manager_user *get_manager_by_name_locked(const char *name)
  2162. {
  2163. struct ast_manager_user *user = NULL;
  2164. AST_RWLIST_TRAVERSE(&users, user, list) {
  2165. if (!strcasecmp(user->username, name)) {
  2166. break;
  2167. }
  2168. }
  2169. return user;
  2170. }
  2171. /*! \brief Get displayconnects config option.
  2172. * \param session manager session to get parameter from.
  2173. * \return displayconnects config option value.
  2174. */
  2175. static int manager_displayconnects(struct mansession_session *session)
  2176. {
  2177. struct ast_manager_user *user = NULL;
  2178. int ret = 0;
  2179. AST_RWLIST_RDLOCK(&users);
  2180. if ((user = get_manager_by_name_locked(session->username))) {
  2181. ret = user->displayconnects;
  2182. }
  2183. AST_RWLIST_UNLOCK(&users);
  2184. return ret;
  2185. }
  2186. #ifdef AST_XML_DOCS
  2187. static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance);
  2188. #endif
  2189. static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2190. {
  2191. struct manager_action *cur;
  2192. struct ast_str *authority;
  2193. int num;
  2194. int l;
  2195. const char *auth_str;
  2196. #ifdef AST_XML_DOCS
  2197. char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64];
  2198. char arguments_title[64], privilege_title[64], final_response_title[64], list_responses_title[64];
  2199. #endif
  2200. switch (cmd) {
  2201. case CLI_INIT:
  2202. e->command = "manager show command";
  2203. e->usage =
  2204. "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
  2205. " Shows the detailed description for a specific Asterisk manager interface command.\n";
  2206. return NULL;
  2207. case CLI_GENERATE:
  2208. l = strlen(a->word);
  2209. AST_RWLIST_RDLOCK(&actions);
  2210. AST_RWLIST_TRAVERSE(&actions, cur, list) {
  2211. if (!strncasecmp(a->word, cur->action, l)) {
  2212. if (ast_cli_completion_add(ast_strdup(cur->action))) {
  2213. break;
  2214. }
  2215. }
  2216. }
  2217. AST_RWLIST_UNLOCK(&actions);
  2218. return NULL;
  2219. }
  2220. if (a->argc < 4) {
  2221. return CLI_SHOWUSAGE;
  2222. }
  2223. authority = ast_str_alloca(MAX_AUTH_PERM_STRING);
  2224. #ifdef AST_XML_DOCS
  2225. /* setup the titles */
  2226. term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
  2227. term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
  2228. term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
  2229. term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
  2230. term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
  2231. term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
  2232. term_color(final_response_title, "[Final Response]\n", COLOR_MAGENTA, 0, 40);
  2233. term_color(list_responses_title, "[List Responses]\n", COLOR_MAGENTA, 0, 40);
  2234. #endif
  2235. AST_RWLIST_RDLOCK(&actions);
  2236. AST_RWLIST_TRAVERSE(&actions, cur, list) {
  2237. for (num = 3; num < a->argc; num++) {
  2238. if (!strcasecmp(cur->action, a->argv[num])) {
  2239. auth_str = authority_to_str(cur->authority, &authority);
  2240. #ifdef AST_XML_DOCS
  2241. if (cur->docsrc == AST_XML_DOC) {
  2242. char *syntax = ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1);
  2243. char *synopsis = ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1);
  2244. char *description = ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1);
  2245. char *arguments = ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1);
  2246. char *seealso = ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1);
  2247. char *privilege = ast_xmldoc_printable(S_OR(auth_str, "Not available"), 1);
  2248. char *responses = ast_xmldoc_printable("None", 1);
  2249. if (!syntax || !synopsis || !description || !arguments
  2250. || !seealso || !privilege || !responses) {
  2251. ast_free(syntax);
  2252. ast_free(synopsis);
  2253. ast_free(description);
  2254. ast_free(arguments);
  2255. ast_free(seealso);
  2256. ast_free(privilege);
  2257. ast_free(responses);
  2258. ast_cli(a->fd, "Allocation failure.\n");
  2259. AST_RWLIST_UNLOCK(&actions);
  2260. return CLI_FAILURE;
  2261. }
  2262. ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s",
  2263. syntax_title, syntax,
  2264. synopsis_title, synopsis,
  2265. description_title, description,
  2266. arguments_title, arguments,
  2267. seealso_title, seealso,
  2268. privilege_title, privilege,
  2269. list_responses_title);
  2270. if (!cur->list_responses) {
  2271. ast_cli(a->fd, "%s\n\n", responses);
  2272. } else {
  2273. struct ast_xml_doc_item *temp;
  2274. for (temp = cur->list_responses; temp; temp = AST_LIST_NEXT(temp, next)) {
  2275. ast_cli(a->fd, "Event: %s\n", temp->name);
  2276. print_event_instance(a, temp);
  2277. }
  2278. }
  2279. ast_cli(a->fd, "%s", final_response_title);
  2280. if (!cur->final_response) {
  2281. ast_cli(a->fd, "%s\n\n", responses);
  2282. } else {
  2283. ast_cli(a->fd, "Event: %s\n", cur->final_response->name);
  2284. print_event_instance(a, cur->final_response);
  2285. }
  2286. ast_free(syntax);
  2287. ast_free(synopsis);
  2288. ast_free(description);
  2289. ast_free(arguments);
  2290. ast_free(seealso);
  2291. ast_free(privilege);
  2292. ast_free(responses);
  2293. } else
  2294. #endif
  2295. {
  2296. ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
  2297. cur->action, cur->synopsis,
  2298. auth_str,
  2299. S_OR(cur->description, ""));
  2300. }
  2301. }
  2302. }
  2303. }
  2304. AST_RWLIST_UNLOCK(&actions);
  2305. return CLI_SUCCESS;
  2306. }
  2307. static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2308. {
  2309. switch (cmd) {
  2310. case CLI_INIT:
  2311. e->command = "manager set debug [on|off]";
  2312. e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
  2313. return NULL;
  2314. case CLI_GENERATE:
  2315. return NULL;
  2316. }
  2317. if (a->argc == 3) {
  2318. ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
  2319. } else if (a->argc == 4) {
  2320. if (!strcasecmp(a->argv[3], "on")) {
  2321. manager_debug = 1;
  2322. } else if (!strcasecmp(a->argv[3], "off")) {
  2323. manager_debug = 0;
  2324. } else {
  2325. return CLI_SHOWUSAGE;
  2326. }
  2327. }
  2328. return CLI_SUCCESS;
  2329. }
  2330. static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2331. {
  2332. struct ast_manager_user *user = NULL;
  2333. int l;
  2334. struct ast_str *rauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
  2335. struct ast_str *wauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
  2336. struct ast_variable *v;
  2337. switch (cmd) {
  2338. case CLI_INIT:
  2339. e->command = "manager show user";
  2340. e->usage =
  2341. " Usage: manager show user <user>\n"
  2342. " Display all information related to the manager user specified.\n";
  2343. return NULL;
  2344. case CLI_GENERATE:
  2345. l = strlen(a->word);
  2346. if (a->pos != 3) {
  2347. return NULL;
  2348. }
  2349. AST_RWLIST_RDLOCK(&users);
  2350. AST_RWLIST_TRAVERSE(&users, user, list) {
  2351. if (!strncasecmp(a->word, user->username, l)) {
  2352. if (ast_cli_completion_add(ast_strdup(user->username))) {
  2353. break;
  2354. }
  2355. }
  2356. }
  2357. AST_RWLIST_UNLOCK(&users);
  2358. return NULL;
  2359. }
  2360. if (a->argc != 4) {
  2361. return CLI_SHOWUSAGE;
  2362. }
  2363. AST_RWLIST_RDLOCK(&users);
  2364. if (!(user = get_manager_by_name_locked(a->argv[3]))) {
  2365. ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
  2366. AST_RWLIST_UNLOCK(&users);
  2367. return CLI_SUCCESS;
  2368. }
  2369. ast_cli(a->fd, "\n");
  2370. ast_cli(a->fd,
  2371. " username: %s\n"
  2372. " secret: %s\n"
  2373. " ACL: %s\n"
  2374. " read perm: %s\n"
  2375. " write perm: %s\n"
  2376. " displayconnects: %s\n"
  2377. "allowmultiplelogin: %s\n",
  2378. S_OR(user->username, "(N/A)"),
  2379. (user->secret ? "<Set>" : "(N/A)"),
  2380. ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
  2381. user_authority_to_str(user->readperm, &rauthority),
  2382. user_authority_to_str(user->writeperm, &wauthority),
  2383. (user->displayconnects ? "yes" : "no"),
  2384. (user->allowmultiplelogin ? "yes" : "no"));
  2385. ast_cli(a->fd, " Variables: \n");
  2386. for (v = user->chanvars ; v ; v = v->next) {
  2387. ast_cli(a->fd, " %s = %s\n", v->name, v->value);
  2388. }
  2389. AST_RWLIST_UNLOCK(&users);
  2390. return CLI_SUCCESS;
  2391. }
  2392. static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2393. {
  2394. struct ast_manager_user *user = NULL;
  2395. int count_amu = 0;
  2396. switch (cmd) {
  2397. case CLI_INIT:
  2398. e->command = "manager show users";
  2399. e->usage =
  2400. "Usage: manager show users\n"
  2401. " Prints a listing of all managers that are currently configured on that\n"
  2402. " system.\n";
  2403. return NULL;
  2404. case CLI_GENERATE:
  2405. return NULL;
  2406. }
  2407. if (a->argc != 3) {
  2408. return CLI_SHOWUSAGE;
  2409. }
  2410. AST_RWLIST_RDLOCK(&users);
  2411. /* If there are no users, print out something along those lines */
  2412. if (AST_RWLIST_EMPTY(&users)) {
  2413. ast_cli(a->fd, "There are no manager users.\n");
  2414. AST_RWLIST_UNLOCK(&users);
  2415. return CLI_SUCCESS;
  2416. }
  2417. ast_cli(a->fd, "\nusername\n--------\n");
  2418. AST_RWLIST_TRAVERSE(&users, user, list) {
  2419. ast_cli(a->fd, "%s\n", user->username);
  2420. count_amu++;
  2421. }
  2422. AST_RWLIST_UNLOCK(&users);
  2423. ast_cli(a->fd,"-------------------\n"
  2424. "%d manager users configured.\n", count_amu);
  2425. return CLI_SUCCESS;
  2426. }
  2427. /*! \brief CLI command manager list commands */
  2428. static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2429. {
  2430. struct manager_action *cur;
  2431. int name_len = 1;
  2432. int space_remaining;
  2433. #define HSMC_FORMAT " %-*.*s %-.*s\n"
  2434. switch (cmd) {
  2435. case CLI_INIT:
  2436. e->command = "manager show commands";
  2437. e->usage =
  2438. "Usage: manager show commands\n"
  2439. " Prints a listing of all the available Asterisk manager interface commands.\n";
  2440. return NULL;
  2441. case CLI_GENERATE:
  2442. return NULL;
  2443. }
  2444. AST_RWLIST_RDLOCK(&actions);
  2445. AST_RWLIST_TRAVERSE(&actions, cur, list) {
  2446. int incoming_len = strlen(cur->action);
  2447. if (incoming_len > name_len) {
  2448. name_len = incoming_len;
  2449. }
  2450. }
  2451. space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
  2452. if (space_remaining < 0) {
  2453. space_remaining = 0;
  2454. }
  2455. ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
  2456. ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
  2457. AST_RWLIST_TRAVERSE(&actions, cur, list) {
  2458. ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
  2459. }
  2460. AST_RWLIST_UNLOCK(&actions);
  2461. return CLI_SUCCESS;
  2462. }
  2463. /*! \brief CLI command manager list connected */
  2464. static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2465. {
  2466. struct ao2_container *sessions;
  2467. struct mansession_session *session;
  2468. time_t now = time(NULL);
  2469. #define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
  2470. #define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
  2471. int count = 0;
  2472. struct ao2_iterator i;
  2473. switch (cmd) {
  2474. case CLI_INIT:
  2475. e->command = "manager show connected";
  2476. e->usage =
  2477. "Usage: manager show connected\n"
  2478. " Prints a listing of the users that are currently connected to the\n"
  2479. "Asterisk manager interface.\n";
  2480. return NULL;
  2481. case CLI_GENERATE:
  2482. return NULL;
  2483. }
  2484. ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
  2485. sessions = ao2_global_obj_ref(mgr_sessions);
  2486. if (sessions) {
  2487. i = ao2_iterator_init(sessions, 0);
  2488. ao2_ref(sessions, -1);
  2489. while ((session = ao2_iterator_next(&i))) {
  2490. ao2_lock(session);
  2491. ast_cli(a->fd, HSMCONN_FORMAT2, session->username,
  2492. ast_sockaddr_stringify_addr(&session->addr),
  2493. (int) (session->sessionstart),
  2494. (int) (now - session->sessionstart),
  2495. session->fd,
  2496. session->inuse,
  2497. session->readperm,
  2498. session->writeperm);
  2499. count++;
  2500. ao2_unlock(session);
  2501. unref_mansession(session);
  2502. }
  2503. ao2_iterator_destroy(&i);
  2504. }
  2505. ast_cli(a->fd, "%d users connected.\n", count);
  2506. return CLI_SUCCESS;
  2507. }
  2508. /*! \brief CLI command manager list eventq */
  2509. /* Should change to "manager show connected" */
  2510. static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2511. {
  2512. struct eventqent *s;
  2513. switch (cmd) {
  2514. case CLI_INIT:
  2515. e->command = "manager show eventq";
  2516. e->usage =
  2517. "Usage: manager show eventq\n"
  2518. " Prints a listing of all events pending in the Asterisk manger\n"
  2519. "event queue.\n";
  2520. return NULL;
  2521. case CLI_GENERATE:
  2522. return NULL;
  2523. }
  2524. AST_RWLIST_RDLOCK(&all_events);
  2525. AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
  2526. ast_cli(a->fd, "Usecount: %d\n", s->usecount);
  2527. ast_cli(a->fd, "Category: %d\n", s->category);
  2528. ast_cli(a->fd, "Event:\n%s", s->eventdata);
  2529. }
  2530. AST_RWLIST_UNLOCK(&all_events);
  2531. return CLI_SUCCESS;
  2532. }
  2533. /*! \brief CLI command manager reload */
  2534. static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2535. {
  2536. switch (cmd) {
  2537. case CLI_INIT:
  2538. e->command = "manager reload";
  2539. e->usage =
  2540. "Usage: manager reload\n"
  2541. " Reloads the manager configuration.\n";
  2542. return NULL;
  2543. case CLI_GENERATE:
  2544. return NULL;
  2545. }
  2546. if (a->argc > 2) {
  2547. return CLI_SHOWUSAGE;
  2548. }
  2549. reload_manager();
  2550. return CLI_SUCCESS;
  2551. }
  2552. static struct eventqent *advance_event(struct eventqent *e)
  2553. {
  2554. struct eventqent *next;
  2555. AST_RWLIST_RDLOCK(&all_events);
  2556. if ((next = AST_RWLIST_NEXT(e, eq_next))) {
  2557. ast_atomic_fetchadd_int(&next->usecount, 1);
  2558. ast_atomic_fetchadd_int(&e->usecount, -1);
  2559. }
  2560. AST_RWLIST_UNLOCK(&all_events);
  2561. return next;
  2562. }
  2563. #define GET_HEADER_FIRST_MATCH 0
  2564. #define GET_HEADER_LAST_MATCH 1
  2565. #define GET_HEADER_SKIP_EMPTY 2
  2566. /*!
  2567. * \brief Return a matching header value.
  2568. *
  2569. * \details
  2570. * Generic function to return either the first or the last
  2571. * matching header from a list of variables, possibly skipping
  2572. * empty strings.
  2573. *
  2574. * \note At the moment there is only one use of this function in
  2575. * this file, so we make it static.
  2576. *
  2577. * \note Never returns NULL.
  2578. */
  2579. static const char *__astman_get_header(const struct message *m, char *var, int mode)
  2580. {
  2581. int x, l = strlen(var);
  2582. const char *result = "";
  2583. if (!m) {
  2584. return result;
  2585. }
  2586. for (x = 0; x < m->hdrcount; x++) {
  2587. const char *h = m->headers[x];
  2588. if (!strncasecmp(var, h, l) && h[l] == ':') {
  2589. const char *value = h + l + 1;
  2590. value = ast_skip_blanks(value); /* ignore leading spaces in the value */
  2591. /* found a potential candidate */
  2592. if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
  2593. continue; /* not interesting */
  2594. }
  2595. if (mode & GET_HEADER_LAST_MATCH) {
  2596. result = value; /* record the last match so far */
  2597. } else {
  2598. return value;
  2599. }
  2600. }
  2601. }
  2602. return result;
  2603. }
  2604. /*!
  2605. * \brief Return the first matching variable from an array.
  2606. *
  2607. * \note This is the legacy function and is implemented in
  2608. * therms of __astman_get_header().
  2609. *
  2610. * \note Never returns NULL.
  2611. */
  2612. const char *astman_get_header(const struct message *m, char *var)
  2613. {
  2614. return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
  2615. }
  2616. /*!
  2617. * \brief Append additional headers into the message structure from params.
  2618. *
  2619. * \note You likely want to initialize m->hdrcount to 0 before calling this.
  2620. */
  2621. static void astman_append_headers(struct message *m, const struct ast_variable *params)
  2622. {
  2623. const struct ast_variable *v;
  2624. for (v = params; v && m->hdrcount < ARRAY_LEN(m->headers); v = v->next) {
  2625. if (ast_asprintf((char**)&m->headers[m->hdrcount], "%s: %s", v->name, v->value) > -1) {
  2626. ++m->hdrcount;
  2627. }
  2628. }
  2629. }
  2630. /*!
  2631. * \brief Free headers inside message structure, but not the message structure itself.
  2632. */
  2633. static void astman_free_headers(struct message *m)
  2634. {
  2635. while (m->hdrcount) {
  2636. --m->hdrcount;
  2637. ast_free((void *) m->headers[m->hdrcount]);
  2638. m->headers[m->hdrcount] = NULL;
  2639. }
  2640. }
  2641. /*!
  2642. * \internal
  2643. * \brief Process one "Variable:" header value string.
  2644. *
  2645. * \param head Current list of AMI variables to get new values added.
  2646. * \param hdr_val Header value string to process.
  2647. *
  2648. * \return New variable list head.
  2649. */
  2650. static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
  2651. {
  2652. char *parse;
  2653. AST_DECLARE_APP_ARGS(args,
  2654. AST_APP_ARG(vars)[64];
  2655. );
  2656. hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
  2657. parse = ast_strdupa(hdr_val);
  2658. /* Break the header value string into name=val pair items. */
  2659. AST_STANDARD_APP_ARGS(args, parse);
  2660. if (args.argc) {
  2661. int y;
  2662. /* Process each name=val pair item. */
  2663. for (y = 0; y < args.argc; y++) {
  2664. struct ast_variable *cur;
  2665. char *var;
  2666. char *val;
  2667. if (!args.vars[y]) {
  2668. continue;
  2669. }
  2670. var = val = args.vars[y];
  2671. strsep(&val, "=");
  2672. /* XXX We may wish to trim whitespace from the strings. */
  2673. if (!val || ast_strlen_zero(var)) {
  2674. continue;
  2675. }
  2676. /* Create new variable list node and prepend it to the list. */
  2677. cur = ast_variable_new(var, val, "");
  2678. if (cur) {
  2679. cur->next = head;
  2680. head = cur;
  2681. }
  2682. }
  2683. }
  2684. return head;
  2685. }
  2686. struct ast_variable *astman_get_variables(const struct message *m)
  2687. {
  2688. return astman_get_variables_order(m, ORDER_REVERSE);
  2689. }
  2690. struct ast_variable *astman_get_variables_order(const struct message *m,
  2691. enum variable_orders order)
  2692. {
  2693. int varlen;
  2694. int x;
  2695. struct ast_variable *head = NULL;
  2696. static const char var_hdr[] = "Variable:";
  2697. /* Process all "Variable:" headers. */
  2698. varlen = strlen(var_hdr);
  2699. for (x = 0; x < m->hdrcount; x++) {
  2700. if (strncasecmp(var_hdr, m->headers[x], varlen)) {
  2701. continue;
  2702. }
  2703. head = man_do_variable_value(head, m->headers[x] + varlen);
  2704. }
  2705. if (order == ORDER_NATURAL) {
  2706. head = ast_variables_reverse(head);
  2707. }
  2708. return head;
  2709. }
  2710. /*! \brief access for hooks to send action messages to ami */
  2711. int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
  2712. {
  2713. const char *action;
  2714. int ret = 0;
  2715. struct manager_action *act_found;
  2716. struct mansession s = {.session = NULL, };
  2717. struct message m = { 0 };
  2718. char *dup_str;
  2719. char *src;
  2720. int x = 0;
  2721. int curlen;
  2722. if (hook == NULL) {
  2723. return -1;
  2724. }
  2725. /* Create our own copy of the AMI action msg string. */
  2726. src = dup_str = ast_strdup(msg);
  2727. if (!dup_str) {
  2728. return -1;
  2729. }
  2730. /* convert msg string to message struct */
  2731. curlen = strlen(src);
  2732. for (x = 0; x < curlen; x++) {
  2733. int cr; /* set if we have \r */
  2734. if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
  2735. cr = 2; /* Found. Update length to include \r\n */
  2736. else if (src[x] == '\n')
  2737. cr = 1; /* also accept \n only */
  2738. else
  2739. continue;
  2740. /* don't keep empty lines */
  2741. if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
  2742. /* ... but trim \r\n and terminate the header string */
  2743. src[x] = '\0';
  2744. m.headers[m.hdrcount++] = src;
  2745. }
  2746. x += cr;
  2747. curlen -= x; /* remaining size */
  2748. src += x; /* update pointer */
  2749. x = -1; /* reset loop */
  2750. }
  2751. action = astman_get_header(&m, "Action");
  2752. if (strcasecmp(action, "login")) {
  2753. act_found = action_find(action);
  2754. if (act_found) {
  2755. /*
  2756. * we have to simulate a session for this action request
  2757. * to be able to pass it down for processing
  2758. * This is necessary to meet the previous design of manager.c
  2759. */
  2760. s.hook = hook;
  2761. s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
  2762. ao2_lock(act_found);
  2763. if (act_found->registered && act_found->func) {
  2764. if (act_found->module) {
  2765. ast_module_ref(act_found->module);
  2766. }
  2767. ao2_unlock(act_found);
  2768. ret = act_found->func(&s, &m);
  2769. ao2_lock(act_found);
  2770. if (act_found->module) {
  2771. ast_module_unref(act_found->module);
  2772. }
  2773. } else {
  2774. ret = -1;
  2775. }
  2776. ao2_unlock(act_found);
  2777. ao2_t_ref(act_found, -1, "done with found action object");
  2778. }
  2779. }
  2780. ast_free(dup_str);
  2781. return ret;
  2782. }
  2783. /*!
  2784. * helper function to send a string to the socket.
  2785. * Return -1 on error (e.g. buffer full).
  2786. */
  2787. static int send_string(struct mansession *s, char *string)
  2788. {
  2789. int res;
  2790. FILE *f = s->f ? s->f : s->session->f;
  2791. int fd = s->f ? s->fd : s->session->fd;
  2792. /* It's a result from one of the hook's action invocation */
  2793. if (s->hook) {
  2794. /*
  2795. * to send responses, we're using the same function
  2796. * as for receiving events. We call the event "HookResponse"
  2797. */
  2798. s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
  2799. return 0;
  2800. }
  2801. if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
  2802. s->write_error = 1;
  2803. }
  2804. return res;
  2805. }
  2806. /*!
  2807. * \brief thread local buffer for astman_append
  2808. *
  2809. * \note This can not be defined within the astman_append() function
  2810. * because it declares a couple of functions that get used to
  2811. * initialize the thread local storage key.
  2812. */
  2813. AST_THREADSTORAGE(astman_append_buf);
  2814. AST_THREADSTORAGE(userevent_buf);
  2815. /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
  2816. #define ASTMAN_APPEND_BUF_INITSIZE 256
  2817. /*!
  2818. * utility functions for creating AMI replies
  2819. */
  2820. void astman_append(struct mansession *s, const char *fmt, ...)
  2821. {
  2822. int res;
  2823. va_list ap;
  2824. struct ast_str *buf;
  2825. if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
  2826. return;
  2827. }
  2828. va_start(ap, fmt);
  2829. res = ast_str_set_va(&buf, 0, fmt, ap);
  2830. va_end(ap);
  2831. if (res == AST_DYNSTR_BUILD_FAILED) {
  2832. return;
  2833. }
  2834. if (s->f != NULL || s->session->f != NULL) {
  2835. send_string(s, ast_str_buffer(buf));
  2836. } else {
  2837. ast_verbose("fd == -1 in astman_append, should not happen\n");
  2838. }
  2839. }
  2840. /*! \note NOTE: XXX this comment is unclear and possibly wrong.
  2841. Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
  2842. hold the session lock _or_ be running in an action callback (in which case s->session->busy will
  2843. be non-zero). In either of these cases, there is no need to lock-protect the session's
  2844. fd, since no other output will be sent (events will be queued), and no input will
  2845. be read until either the current action finishes or get_input() obtains the session
  2846. lock.
  2847. */
  2848. /*! \todo XXX MSG_MOREDATA should go to a header file. */
  2849. #define MSG_MOREDATA ((char *)astman_send_response)
  2850. /*! \brief send a response with an optional message,
  2851. * and terminate it with an empty line.
  2852. * m is used only to grab the 'ActionID' field.
  2853. *
  2854. * Use the explicit constant MSG_MOREDATA to remove the empty line.
  2855. * XXX MSG_MOREDATA should go to a header file.
  2856. */
  2857. static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
  2858. {
  2859. const char *id = astman_get_header(m, "ActionID");
  2860. astman_append(s, "Response: %s\r\n", resp);
  2861. if (!ast_strlen_zero(id)) {
  2862. astman_append(s, "ActionID: %s\r\n", id);
  2863. }
  2864. if (listflag) {
  2865. astman_append(s, "EventList: %s\r\n", listflag); /* Start, complete, cancelled */
  2866. }
  2867. if (msg == MSG_MOREDATA) {
  2868. return;
  2869. } else if (msg) {
  2870. astman_append(s, "Message: %s\r\n\r\n", msg);
  2871. } else {
  2872. astman_append(s, "\r\n");
  2873. }
  2874. }
  2875. void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
  2876. {
  2877. astman_send_response_full(s, m, resp, msg, NULL);
  2878. }
  2879. void astman_send_error(struct mansession *s, const struct message *m, char *error)
  2880. {
  2881. astman_send_response_full(s, m, "Error", error, NULL);
  2882. }
  2883. void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
  2884. {
  2885. int res;
  2886. va_list ap;
  2887. struct ast_str *buf;
  2888. char *msg;
  2889. if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
  2890. return;
  2891. }
  2892. va_start(ap, fmt);
  2893. res = ast_str_set_va(&buf, 0, fmt, ap);
  2894. va_end(ap);
  2895. if (res == AST_DYNSTR_BUILD_FAILED) {
  2896. return;
  2897. }
  2898. /* astman_append will use the same underlying buffer, so copy the message out
  2899. * before sending the response */
  2900. msg = ast_str_buffer(buf);
  2901. if (msg) {
  2902. msg = ast_strdupa(msg);
  2903. }
  2904. astman_send_response_full(s, m, "Error", msg, NULL);
  2905. }
  2906. void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
  2907. {
  2908. astman_send_response_full(s, m, "Success", msg, NULL);
  2909. }
  2910. static void astman_start_ack(struct mansession *s, const struct message *m)
  2911. {
  2912. astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
  2913. }
  2914. void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
  2915. {
  2916. astman_send_response_full(s, m, "Success", msg, listflag);
  2917. }
  2918. void astman_send_list_complete_start(struct mansession *s, const struct message *m, const char *event_name, int count)
  2919. {
  2920. const char *id = astman_get_header(m, "ActionID");
  2921. astman_append(s, "Event: %s\r\n", event_name);
  2922. if (!ast_strlen_zero(id)) {
  2923. astman_append(s, "ActionID: %s\r\n", id);
  2924. }
  2925. astman_append(s,
  2926. "EventList: Complete\r\n"
  2927. "ListItems: %d\r\n",
  2928. count);
  2929. }
  2930. void astman_send_list_complete_end(struct mansession *s)
  2931. {
  2932. astman_append(s, "\r\n");
  2933. }
  2934. /*! \brief Lock the 'mansession' structure. */
  2935. static void mansession_lock(struct mansession *s)
  2936. {
  2937. ast_mutex_lock(&s->lock);
  2938. }
  2939. /*! \brief Unlock the 'mansession' structure. */
  2940. static void mansession_unlock(struct mansession *s)
  2941. {
  2942. ast_mutex_unlock(&s->lock);
  2943. }
  2944. /*! \brief
  2945. Rather than braindead on,off this now can also accept a specific int mask value
  2946. or a ',' delim list of mask strings (the same as manager.conf) -anthm
  2947. */
  2948. static int set_eventmask(struct mansession *s, const char *eventmask)
  2949. {
  2950. int maskint = strings_to_mask(eventmask);
  2951. ao2_lock(s->session);
  2952. if (maskint >= 0) {
  2953. s->session->send_events = maskint;
  2954. }
  2955. ao2_unlock(s->session);
  2956. return maskint;
  2957. }
  2958. static enum ast_transport mansession_get_transport(const struct mansession *s)
  2959. {
  2960. return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
  2961. AST_TRANSPORT_TCP;
  2962. }
  2963. static void report_invalid_user(const struct mansession *s, const char *username)
  2964. {
  2965. char session_id[32];
  2966. struct ast_security_event_inval_acct_id inval_acct_id = {
  2967. .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
  2968. .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
  2969. .common.service = "AMI",
  2970. .common.account_id = username,
  2971. .common.session_tv = &s->session->sessionstart_tv,
  2972. .common.local_addr = {
  2973. .addr = &s->tcptls_session->parent->local_address,
  2974. .transport = mansession_get_transport(s),
  2975. },
  2976. .common.remote_addr = {
  2977. .addr = &s->session->addr,
  2978. .transport = mansession_get_transport(s),
  2979. },
  2980. .common.session_id = session_id,
  2981. };
  2982. snprintf(session_id, sizeof(session_id), "%p", s);
  2983. ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
  2984. }
  2985. static void report_failed_acl(const struct mansession *s, const char *username)
  2986. {
  2987. char session_id[32];
  2988. struct ast_security_event_failed_acl failed_acl_event = {
  2989. .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
  2990. .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
  2991. .common.service = "AMI",
  2992. .common.account_id = username,
  2993. .common.session_tv = &s->session->sessionstart_tv,
  2994. .common.local_addr = {
  2995. .addr = &s->tcptls_session->parent->local_address,
  2996. .transport = mansession_get_transport(s),
  2997. },
  2998. .common.remote_addr = {
  2999. .addr = &s->session->addr,
  3000. .transport = mansession_get_transport(s),
  3001. },
  3002. .common.session_id = session_id,
  3003. };
  3004. snprintf(session_id, sizeof(session_id), "%p", s->session);
  3005. ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
  3006. }
  3007. static void report_inval_password(const struct mansession *s, const char *username)
  3008. {
  3009. char session_id[32];
  3010. struct ast_security_event_inval_password inval_password = {
  3011. .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
  3012. .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
  3013. .common.service = "AMI",
  3014. .common.account_id = username,
  3015. .common.session_tv = &s->session->sessionstart_tv,
  3016. .common.local_addr = {
  3017. .addr = &s->tcptls_session->parent->local_address,
  3018. .transport = mansession_get_transport(s),
  3019. },
  3020. .common.remote_addr = {
  3021. .addr = &s->session->addr,
  3022. .transport = mansession_get_transport(s),
  3023. },
  3024. .common.session_id = session_id,
  3025. };
  3026. snprintf(session_id, sizeof(session_id), "%p", s->session);
  3027. ast_security_event_report(AST_SEC_EVT(&inval_password));
  3028. }
  3029. static void report_auth_success(const struct mansession *s)
  3030. {
  3031. char session_id[32];
  3032. struct ast_security_event_successful_auth successful_auth = {
  3033. .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
  3034. .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
  3035. .common.service = "AMI",
  3036. .common.account_id = s->session->username,
  3037. .common.session_tv = &s->session->sessionstart_tv,
  3038. .common.local_addr = {
  3039. .addr = &s->tcptls_session->parent->local_address,
  3040. .transport = mansession_get_transport(s),
  3041. },
  3042. .common.remote_addr = {
  3043. .addr = &s->session->addr,
  3044. .transport = mansession_get_transport(s),
  3045. },
  3046. .common.session_id = session_id,
  3047. };
  3048. snprintf(session_id, sizeof(session_id), "%p", s->session);
  3049. ast_security_event_report(AST_SEC_EVT(&successful_auth));
  3050. }
  3051. static void report_req_not_allowed(const struct mansession *s, const char *action)
  3052. {
  3053. char session_id[32];
  3054. char request_type[64];
  3055. struct ast_security_event_req_not_allowed req_not_allowed = {
  3056. .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
  3057. .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
  3058. .common.service = "AMI",
  3059. .common.account_id = s->session->username,
  3060. .common.session_tv = &s->session->sessionstart_tv,
  3061. .common.local_addr = {
  3062. .addr = &s->tcptls_session->parent->local_address,
  3063. .transport = mansession_get_transport(s),
  3064. },
  3065. .common.remote_addr = {
  3066. .addr = &s->session->addr,
  3067. .transport = mansession_get_transport(s),
  3068. },
  3069. .common.session_id = session_id,
  3070. .request_type = request_type,
  3071. };
  3072. snprintf(session_id, sizeof(session_id), "%p", s->session);
  3073. snprintf(request_type, sizeof(request_type), "Action: %s", action);
  3074. ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
  3075. }
  3076. static void report_req_bad_format(const struct mansession *s, const char *action)
  3077. {
  3078. char session_id[32];
  3079. char request_type[64];
  3080. struct ast_security_event_req_bad_format req_bad_format = {
  3081. .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
  3082. .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
  3083. .common.service = "AMI",
  3084. .common.account_id = s->session->username,
  3085. .common.session_tv = &s->session->sessionstart_tv,
  3086. .common.local_addr = {
  3087. .addr = &s->tcptls_session->parent->local_address,
  3088. .transport = mansession_get_transport(s),
  3089. },
  3090. .common.remote_addr = {
  3091. .addr = &s->session->addr,
  3092. .transport = mansession_get_transport(s),
  3093. },
  3094. .common.session_id = session_id,
  3095. .request_type = request_type,
  3096. };
  3097. snprintf(session_id, sizeof(session_id), "%p", s->session);
  3098. snprintf(request_type, sizeof(request_type), "Action: %s", action);
  3099. ast_security_event_report(AST_SEC_EVT(&req_bad_format));
  3100. }
  3101. static void report_failed_challenge_response(const struct mansession *s,
  3102. const char *response, const char *expected_response)
  3103. {
  3104. char session_id[32];
  3105. struct ast_security_event_chal_resp_failed chal_resp_failed = {
  3106. .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
  3107. .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
  3108. .common.service = "AMI",
  3109. .common.account_id = s->session->username,
  3110. .common.session_tv = &s->session->sessionstart_tv,
  3111. .common.local_addr = {
  3112. .addr = &s->tcptls_session->parent->local_address,
  3113. .transport = mansession_get_transport(s),
  3114. },
  3115. .common.remote_addr = {
  3116. .addr = &s->session->addr,
  3117. .transport = mansession_get_transport(s),
  3118. },
  3119. .common.session_id = session_id,
  3120. .challenge = s->session->challenge,
  3121. .response = response,
  3122. .expected_response = expected_response,
  3123. };
  3124. snprintf(session_id, sizeof(session_id), "%p", s->session);
  3125. ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
  3126. }
  3127. static void report_session_limit(const struct mansession *s)
  3128. {
  3129. char session_id[32];
  3130. struct ast_security_event_session_limit session_limit = {
  3131. .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
  3132. .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
  3133. .common.service = "AMI",
  3134. .common.account_id = s->session->username,
  3135. .common.session_tv = &s->session->sessionstart_tv,
  3136. .common.local_addr = {
  3137. .addr = &s->tcptls_session->parent->local_address,
  3138. .transport = mansession_get_transport(s),
  3139. },
  3140. .common.remote_addr = {
  3141. .addr = &s->session->addr,
  3142. .transport = mansession_get_transport(s),
  3143. },
  3144. .common.session_id = session_id,
  3145. };
  3146. snprintf(session_id, sizeof(session_id), "%p", s->session);
  3147. ast_security_event_report(AST_SEC_EVT(&session_limit));
  3148. }
  3149. /*
  3150. * Here we start with action_ handlers for AMI actions,
  3151. * and the internal functions used by them.
  3152. * Generally, the handlers are called action_foo()
  3153. */
  3154. /* helper function for action_login() */
  3155. static int authenticate(struct mansession *s, const struct message *m)
  3156. {
  3157. const char *username = astman_get_header(m, "Username");
  3158. const char *password = astman_get_header(m, "Secret");
  3159. int error = -1;
  3160. struct ast_manager_user *user = NULL;
  3161. regex_t *regex_filter;
  3162. struct ao2_iterator filter_iter;
  3163. if (ast_strlen_zero(username)) { /* missing username */
  3164. return -1;
  3165. }
  3166. /* locate user in locked state */
  3167. AST_RWLIST_WRLOCK(&users);
  3168. if (!(user = get_manager_by_name_locked(username))) {
  3169. report_invalid_user(s, username);
  3170. ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
  3171. } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
  3172. report_failed_acl(s, username);
  3173. ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
  3174. } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
  3175. const char *key = astman_get_header(m, "Key");
  3176. if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
  3177. int x;
  3178. int len = 0;
  3179. char md5key[256] = "";
  3180. struct MD5Context md5;
  3181. unsigned char digest[16];
  3182. MD5Init(&md5);
  3183. MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
  3184. MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
  3185. MD5Final(digest, &md5);
  3186. for (x = 0; x < 16; x++)
  3187. len += sprintf(md5key + len, "%02hhx", digest[x]);
  3188. if (!strcmp(md5key, key)) {
  3189. error = 0;
  3190. } else {
  3191. report_failed_challenge_response(s, key, md5key);
  3192. }
  3193. } else {
  3194. ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
  3195. S_OR(s->session->challenge, ""));
  3196. }
  3197. } else if (user->secret) {
  3198. if (!strcmp(password, user->secret)) {
  3199. error = 0;
  3200. } else {
  3201. report_inval_password(s, username);
  3202. }
  3203. }
  3204. if (error) {
  3205. ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
  3206. AST_RWLIST_UNLOCK(&users);
  3207. return -1;
  3208. }
  3209. /* auth complete */
  3210. /* All of the user parameters are copied to the session so that in the event
  3211. * of a reload and a configuration change, the session parameters are not
  3212. * changed. */
  3213. ast_copy_string(s->session->username, username, sizeof(s->session->username));
  3214. s->session->readperm = user->readperm;
  3215. s->session->writeperm = user->writeperm;
  3216. s->session->writetimeout = user->writetimeout;
  3217. if (user->chanvars) {
  3218. s->session->chanvars = ast_variables_dup(user->chanvars);
  3219. }
  3220. filter_iter = ao2_iterator_init(user->whitefilters, 0);
  3221. while ((regex_filter = ao2_iterator_next(&filter_iter))) {
  3222. ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
  3223. ao2_t_ref(regex_filter, -1, "remove iterator ref");
  3224. }
  3225. ao2_iterator_destroy(&filter_iter);
  3226. filter_iter = ao2_iterator_init(user->blackfilters, 0);
  3227. while ((regex_filter = ao2_iterator_next(&filter_iter))) {
  3228. ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
  3229. ao2_t_ref(regex_filter, -1, "remove iterator ref");
  3230. }
  3231. ao2_iterator_destroy(&filter_iter);
  3232. s->session->sessionstart = time(NULL);
  3233. s->session->sessionstart_tv = ast_tvnow();
  3234. set_eventmask(s, astman_get_header(m, "Events"));
  3235. report_auth_success(s);
  3236. AST_RWLIST_UNLOCK(&users);
  3237. return 0;
  3238. }
  3239. static int action_ping(struct mansession *s, const struct message *m)
  3240. {
  3241. const char *actionid = astman_get_header(m, "ActionID");
  3242. struct timeval now = ast_tvnow();
  3243. astman_append(s, "Response: Success\r\n");
  3244. if (!ast_strlen_zero(actionid)){
  3245. astman_append(s, "ActionID: %s\r\n", actionid);
  3246. }
  3247. astman_append(
  3248. s,
  3249. "Ping: Pong\r\n"
  3250. "Timestamp: %ld.%06lu\r\n"
  3251. "\r\n",
  3252. (long) now.tv_sec, (unsigned long) now.tv_usec);
  3253. return 0;
  3254. }
  3255. static int action_getconfig(struct mansession *s, const struct message *m)
  3256. {
  3257. struct ast_config *cfg;
  3258. const char *fn = astman_get_header(m, "Filename");
  3259. const char *category = astman_get_header(m, "Category");
  3260. const char *filter = astman_get_header(m, "Filter");
  3261. const char *category_name;
  3262. int catcount = 0;
  3263. int lineno = 0;
  3264. struct ast_category *cur_category = NULL;
  3265. struct ast_variable *v;
  3266. struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
  3267. if (ast_strlen_zero(fn)) {
  3268. astman_send_error(s, m, "Filename not specified");
  3269. return 0;
  3270. }
  3271. cfg = ast_config_load2(fn, "manager", config_flags);
  3272. if (cfg == CONFIG_STATUS_FILEMISSING) {
  3273. astman_send_error(s, m, "Config file not found");
  3274. return 0;
  3275. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  3276. astman_send_error(s, m, "Config file has invalid format");
  3277. return 0;
  3278. }
  3279. astman_start_ack(s, m);
  3280. while ((cur_category = ast_category_browse_filtered(cfg, category, cur_category, filter))) {
  3281. struct ast_str *templates;
  3282. category_name = ast_category_get_name(cur_category);
  3283. lineno = 0;
  3284. astman_append(s, "Category-%06d: %s\r\n", catcount, category_name);
  3285. if (ast_category_is_template(cur_category)) {
  3286. astman_append(s, "IsTemplate-%06d: %d\r\n", catcount, 1);
  3287. }
  3288. if ((templates = ast_category_get_templates(cur_category))
  3289. && ast_str_strlen(templates) > 0) {
  3290. astman_append(s, "Templates-%06d: %s\r\n", catcount, ast_str_buffer(templates));
  3291. ast_free(templates);
  3292. }
  3293. for (v = ast_category_first(cur_category); v; v = v->next) {
  3294. astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
  3295. }
  3296. catcount++;
  3297. }
  3298. if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
  3299. astman_append(s, "No categories found\r\n");
  3300. }
  3301. ast_config_destroy(cfg);
  3302. astman_append(s, "\r\n");
  3303. return 0;
  3304. }
  3305. static int action_listcategories(struct mansession *s, const struct message *m)
  3306. {
  3307. struct ast_config *cfg;
  3308. const char *fn = astman_get_header(m, "Filename");
  3309. const char *match = astman_get_header(m, "Match");
  3310. struct ast_category *category = NULL;
  3311. struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
  3312. int catcount = 0;
  3313. if (ast_strlen_zero(fn)) {
  3314. astman_send_error(s, m, "Filename not specified");
  3315. return 0;
  3316. }
  3317. if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
  3318. astman_send_error(s, m, "Config file not found");
  3319. return 0;
  3320. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  3321. astman_send_error(s, m, "Config file has invalid format");
  3322. return 0;
  3323. }
  3324. astman_start_ack(s, m);
  3325. while ((category = ast_category_browse_filtered(cfg, NULL, category, match))) {
  3326. astman_append(s, "Category-%06d: %s\r\n", catcount, ast_category_get_name(category));
  3327. catcount++;
  3328. }
  3329. if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
  3330. astman_append(s, "Error: no categories found\r\n");
  3331. }
  3332. ast_config_destroy(cfg);
  3333. astman_append(s, "\r\n");
  3334. return 0;
  3335. }
  3336. /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
  3337. static void json_escape(char *out, const char *in)
  3338. {
  3339. for (; *in; in++) {
  3340. if (*in == '\\' || *in == '\"') {
  3341. *out++ = '\\';
  3342. }
  3343. *out++ = *in;
  3344. }
  3345. *out = '\0';
  3346. }
  3347. /*!
  3348. * \internal
  3349. * \brief Append a JSON escaped string to the manager stream.
  3350. *
  3351. * \param s AMI stream to append a string.
  3352. * \param str String to append to the stream after JSON escaping it.
  3353. *
  3354. * \return Nothing
  3355. */
  3356. static void astman_append_json(struct mansession *s, const char *str)
  3357. {
  3358. char *buf;
  3359. buf = ast_alloca(2 * strlen(str) + 1);
  3360. json_escape(buf, str);
  3361. astman_append(s, "%s", buf);
  3362. }
  3363. static int action_getconfigjson(struct mansession *s, const struct message *m)
  3364. {
  3365. struct ast_config *cfg;
  3366. const char *fn = astman_get_header(m, "Filename");
  3367. const char *filter = astman_get_header(m, "Filter");
  3368. const char *category = astman_get_header(m, "Category");
  3369. struct ast_category *cur_category = NULL;
  3370. const char *category_name;
  3371. struct ast_variable *v;
  3372. int comma1 = 0;
  3373. struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
  3374. if (ast_strlen_zero(fn)) {
  3375. astman_send_error(s, m, "Filename not specified");
  3376. return 0;
  3377. }
  3378. if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
  3379. astman_send_error(s, m, "Config file not found");
  3380. return 0;
  3381. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  3382. astman_send_error(s, m, "Config file has invalid format");
  3383. return 0;
  3384. }
  3385. astman_start_ack(s, m);
  3386. astman_append(s, "JSON: {");
  3387. while ((cur_category = ast_category_browse_filtered(cfg, category, cur_category, filter))) {
  3388. int comma2 = 0;
  3389. struct ast_str *templates;
  3390. category_name = ast_category_get_name(cur_category);
  3391. astman_append(s, "%s\"", comma1 ? "," : "");
  3392. astman_append_json(s, category_name);
  3393. astman_append(s, "\":{");
  3394. comma1 = 1;
  3395. if (ast_category_is_template(cur_category)) {
  3396. astman_append(s, "\"istemplate\":1");
  3397. comma2 = 1;
  3398. }
  3399. if ((templates = ast_category_get_templates(cur_category))
  3400. && ast_str_strlen(templates) > 0) {
  3401. astman_append(s, "%s", comma2 ? "," : "");
  3402. astman_append(s, "\"templates\":\"%s\"", ast_str_buffer(templates));
  3403. ast_free(templates);
  3404. comma2 = 1;
  3405. }
  3406. for (v = ast_category_first(cur_category); v; v = v->next) {
  3407. astman_append(s, "%s\"", comma2 ? "," : "");
  3408. astman_append_json(s, v->name);
  3409. astman_append(s, "\":\"");
  3410. astman_append_json(s, v->value);
  3411. astman_append(s, "\"");
  3412. comma2 = 1;
  3413. }
  3414. astman_append(s, "}");
  3415. }
  3416. astman_append(s, "}\r\n\r\n");
  3417. ast_config_destroy(cfg);
  3418. return 0;
  3419. }
  3420. /*! \brief helper function for action_updateconfig */
  3421. static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
  3422. {
  3423. int x;
  3424. char hdr[40];
  3425. const char *action, *cat, *var, *value, *match, *line, *options;
  3426. struct ast_variable *v;
  3427. struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
  3428. enum error_type result = 0;
  3429. for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
  3430. unsigned int object = 0;
  3431. char *dupoptions;
  3432. int allowdups = 0;
  3433. int istemplate = 0;
  3434. int ignoreerror = 0;
  3435. char *inherit = NULL;
  3436. char *catfilter = NULL;
  3437. char *token;
  3438. int foundvar = 0;
  3439. int foundcat = 0;
  3440. struct ast_category *category = NULL;
  3441. snprintf(hdr, sizeof(hdr), "Action-%06d", x);
  3442. action = astman_get_header(m, hdr);
  3443. if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
  3444. break; /* this could cause problems if actions come in misnumbered */
  3445. snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
  3446. cat = astman_get_header(m, hdr);
  3447. if (ast_strlen_zero(cat)) { /* every action needs a category */
  3448. result = UNSPECIFIED_CATEGORY;
  3449. break;
  3450. }
  3451. snprintf(hdr, sizeof(hdr), "Var-%06d", x);
  3452. var = astman_get_header(m, hdr);
  3453. snprintf(hdr, sizeof(hdr), "Value-%06d", x);
  3454. value = astman_get_header(m, hdr);
  3455. if (!ast_strlen_zero(value) && *value == '>') {
  3456. object = 1;
  3457. value++;
  3458. }
  3459. snprintf(hdr, sizeof(hdr), "Match-%06d", x);
  3460. match = astman_get_header(m, hdr);
  3461. snprintf(hdr, sizeof(hdr), "Line-%06d", x);
  3462. line = astman_get_header(m, hdr);
  3463. snprintf(hdr, sizeof(hdr), "Options-%06d", x);
  3464. options = astman_get_header(m, hdr);
  3465. if (!ast_strlen_zero(options)) {
  3466. dupoptions = ast_strdupa(options);
  3467. while ((token = ast_strsep(&dupoptions, ',', AST_STRSEP_STRIP))) {
  3468. if (!strcasecmp("allowdups", token)) {
  3469. allowdups = 1;
  3470. continue;
  3471. }
  3472. if (!strcasecmp("template", token)) {
  3473. istemplate = 1;
  3474. continue;
  3475. }
  3476. if (!strcasecmp("ignoreerror", token)) {
  3477. ignoreerror = 1;
  3478. continue;
  3479. }
  3480. if (ast_begins_with(token, "inherit")) {
  3481. char *c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
  3482. c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
  3483. if (c) {
  3484. inherit = ast_strdupa(c);
  3485. }
  3486. continue;
  3487. }
  3488. if (ast_begins_with(token, "catfilter")) {
  3489. char *c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
  3490. c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
  3491. if (c) {
  3492. catfilter = ast_strdupa(c);
  3493. }
  3494. continue;
  3495. }
  3496. }
  3497. }
  3498. if (!strcasecmp(action, "newcat")) {
  3499. struct ast_category *template;
  3500. char *tmpl_name = NULL;
  3501. if (!allowdups) {
  3502. if (ast_category_get(cfg, cat, "TEMPLATES=include")) {
  3503. if (ignoreerror) {
  3504. continue;
  3505. } else {
  3506. result = FAILURE_NEWCAT; /* already exist */
  3507. break;
  3508. }
  3509. }
  3510. }
  3511. if (istemplate) {
  3512. category = ast_category_new_template(cat, dfn, -1);
  3513. } else {
  3514. category = ast_category_new(cat, dfn, -1);
  3515. }
  3516. if (!category) {
  3517. result = FAILURE_ALLOCATION;
  3518. break;
  3519. }
  3520. if (inherit) {
  3521. while ((tmpl_name = ast_strsep(&inherit, ',', AST_STRSEP_STRIP))) {
  3522. if ((template = ast_category_get(cfg, tmpl_name, "TEMPLATES=restrict"))) {
  3523. if (ast_category_inherit(category, template)) {
  3524. result = FAILURE_ALLOCATION;
  3525. break;
  3526. }
  3527. } else {
  3528. ast_category_destroy(category);
  3529. category = NULL;
  3530. result = FAILURE_TEMPLATE; /* template not found */
  3531. break;
  3532. }
  3533. }
  3534. }
  3535. if (category != NULL) {
  3536. if (ast_strlen_zero(match)) {
  3537. ast_category_append(cfg, category);
  3538. } else {
  3539. if (ast_category_insert(cfg, category, match)) {
  3540. ast_category_destroy(category);
  3541. result = FAILURE_NEWCAT;
  3542. break;
  3543. }
  3544. }
  3545. }
  3546. } else if (!strcasecmp(action, "renamecat")) {
  3547. if (ast_strlen_zero(value)) {
  3548. result = UNSPECIFIED_ARGUMENT;
  3549. break;
  3550. }
  3551. foundcat = 0;
  3552. while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
  3553. ast_category_rename(category, value);
  3554. foundcat = 1;
  3555. }
  3556. if (!foundcat) {
  3557. result = UNKNOWN_CATEGORY;
  3558. break;
  3559. }
  3560. } else if (!strcasecmp(action, "delcat")) {
  3561. foundcat = 0;
  3562. while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
  3563. category = ast_category_delete(cfg, category);
  3564. foundcat = 1;
  3565. }
  3566. if (!foundcat && !ignoreerror) {
  3567. result = UNKNOWN_CATEGORY;
  3568. break;
  3569. }
  3570. } else if (!strcasecmp(action, "emptycat")) {
  3571. foundcat = 0;
  3572. while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
  3573. ast_category_empty(category);
  3574. foundcat = 1;
  3575. }
  3576. if (!foundcat) {
  3577. result = UNKNOWN_CATEGORY;
  3578. break;
  3579. }
  3580. } else if (!strcasecmp(action, "update")) {
  3581. if (ast_strlen_zero(var)) {
  3582. result = UNSPECIFIED_ARGUMENT;
  3583. break;
  3584. }
  3585. foundcat = 0;
  3586. foundvar = 0;
  3587. while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
  3588. if (!ast_variable_update(category, var, value, match, object)) {
  3589. foundvar = 1;
  3590. }
  3591. foundcat = 1;
  3592. }
  3593. if (!foundcat) {
  3594. result = UNKNOWN_CATEGORY;
  3595. break;
  3596. }
  3597. if (!foundvar) {
  3598. result = FAILURE_UPDATE;
  3599. break;
  3600. }
  3601. } else if (!strcasecmp(action, "delete")) {
  3602. if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
  3603. result = UNSPECIFIED_ARGUMENT;
  3604. break;
  3605. }
  3606. foundcat = 0;
  3607. foundvar = 0;
  3608. while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
  3609. if (!ast_variable_delete(category, var, match, line)) {
  3610. foundvar = 1;
  3611. }
  3612. foundcat = 1;
  3613. }
  3614. if (!foundcat) {
  3615. result = UNKNOWN_CATEGORY;
  3616. break;
  3617. }
  3618. if (!foundvar && !ignoreerror) {
  3619. result = FAILURE_UPDATE;
  3620. break;
  3621. }
  3622. } else if (!strcasecmp(action, "append")) {
  3623. if (ast_strlen_zero(var)) {
  3624. result = UNSPECIFIED_ARGUMENT;
  3625. break;
  3626. }
  3627. foundcat = 0;
  3628. while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
  3629. if (!(v = ast_variable_new(var, value, dfn))) {
  3630. result = FAILURE_ALLOCATION;
  3631. break;
  3632. }
  3633. if (object || (match && !strcasecmp(match, "object"))) {
  3634. v->object = 1;
  3635. }
  3636. ast_variable_append(category, v);
  3637. foundcat = 1;
  3638. }
  3639. if (!foundcat) {
  3640. result = UNKNOWN_CATEGORY;
  3641. break;
  3642. }
  3643. } else if (!strcasecmp(action, "insert")) {
  3644. if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
  3645. result = UNSPECIFIED_ARGUMENT;
  3646. break;
  3647. }
  3648. foundcat = 0;
  3649. while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
  3650. if (!(v = ast_variable_new(var, value, dfn))) {
  3651. result = FAILURE_ALLOCATION;
  3652. break;
  3653. }
  3654. ast_variable_insert(category, v, line);
  3655. foundcat = 1;
  3656. }
  3657. if (!foundcat) {
  3658. result = UNKNOWN_CATEGORY;
  3659. break;
  3660. }
  3661. }
  3662. else {
  3663. ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
  3664. result = UNKNOWN_ACTION;
  3665. break;
  3666. }
  3667. }
  3668. ast_free(str1);
  3669. ast_free(str2);
  3670. return result;
  3671. }
  3672. static int action_updateconfig(struct mansession *s, const struct message *m)
  3673. {
  3674. struct ast_config *cfg;
  3675. const char *sfn = astman_get_header(m, "SrcFilename");
  3676. const char *dfn = astman_get_header(m, "DstFilename");
  3677. int res;
  3678. const char *rld = astman_get_header(m, "Reload");
  3679. int preserve_effective_context = CONFIG_SAVE_FLAG_PRESERVE_EFFECTIVE_CONTEXT;
  3680. const char *preserve_effective_context_string = astman_get_header(m, "PreserveEffectiveContext");
  3681. struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
  3682. enum error_type result;
  3683. if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
  3684. astman_send_error(s, m, "Filename not specified");
  3685. return 0;
  3686. }
  3687. if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
  3688. astman_send_error(s, m, "Config file not found");
  3689. return 0;
  3690. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  3691. astman_send_error(s, m, "Config file has invalid format");
  3692. return 0;
  3693. }
  3694. result = handle_updates(s, m, cfg, dfn);
  3695. if (!result) {
  3696. ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
  3697. if (!ast_strlen_zero(preserve_effective_context_string) && !ast_true(preserve_effective_context_string)) {
  3698. preserve_effective_context = CONFIG_SAVE_FLAG_NONE;
  3699. }
  3700. res = ast_config_text_file_save2(dfn, cfg, "Manager", preserve_effective_context);
  3701. ast_config_destroy(cfg);
  3702. if (res) {
  3703. astman_send_error(s, m, "Save of config failed");
  3704. return 0;
  3705. }
  3706. astman_send_ack(s, m, NULL);
  3707. if (!ast_strlen_zero(rld)) {
  3708. if (ast_true(rld)) {
  3709. rld = NULL;
  3710. }
  3711. ast_module_reload(rld);
  3712. }
  3713. } else {
  3714. ast_config_destroy(cfg);
  3715. switch(result) {
  3716. case UNKNOWN_ACTION:
  3717. astman_send_error(s, m, "Unknown action command");
  3718. break;
  3719. case UNKNOWN_CATEGORY:
  3720. astman_send_error(s, m, "Given category does not exist");
  3721. break;
  3722. case UNSPECIFIED_CATEGORY:
  3723. astman_send_error(s, m, "Category not specified");
  3724. break;
  3725. case UNSPECIFIED_ARGUMENT:
  3726. astman_send_error(s, m, "Problem with category, value, or line (if required)");
  3727. break;
  3728. case FAILURE_ALLOCATION:
  3729. astman_send_error(s, m, "Memory allocation failure, this should not happen");
  3730. break;
  3731. case FAILURE_NEWCAT:
  3732. astman_send_error(s, m, "Create category did not complete successfully");
  3733. break;
  3734. case FAILURE_DELCAT:
  3735. astman_send_error(s, m, "Delete category did not complete successfully");
  3736. break;
  3737. case FAILURE_EMPTYCAT:
  3738. astman_send_error(s, m, "Empty category did not complete successfully");
  3739. break;
  3740. case FAILURE_UPDATE:
  3741. astman_send_error(s, m, "Update did not complete successfully");
  3742. break;
  3743. case FAILURE_DELETE:
  3744. astman_send_error(s, m, "Delete did not complete successfully");
  3745. break;
  3746. case FAILURE_APPEND:
  3747. astman_send_error(s, m, "Append did not complete successfully");
  3748. break;
  3749. case FAILURE_TEMPLATE:
  3750. astman_send_error(s, m, "Template category not found");
  3751. break;
  3752. }
  3753. }
  3754. return 0;
  3755. }
  3756. static int action_createconfig(struct mansession *s, const struct message *m)
  3757. {
  3758. int fd;
  3759. const char *fn = astman_get_header(m, "Filename");
  3760. struct ast_str *filepath = ast_str_alloca(PATH_MAX);
  3761. ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
  3762. ast_str_append(&filepath, 0, "%s", fn);
  3763. if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
  3764. close(fd);
  3765. astman_send_ack(s, m, "New configuration file created successfully");
  3766. } else {
  3767. astman_send_error(s, m, strerror(errno));
  3768. }
  3769. return 0;
  3770. }
  3771. static int action_waitevent(struct mansession *s, const struct message *m)
  3772. {
  3773. const char *timeouts = astman_get_header(m, "Timeout");
  3774. int timeout = -1;
  3775. int x;
  3776. int needexit = 0;
  3777. const char *id = astman_get_header(m, "ActionID");
  3778. char idText[256];
  3779. if (!ast_strlen_zero(id)) {
  3780. snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
  3781. } else {
  3782. idText[0] = '\0';
  3783. }
  3784. if (!ast_strlen_zero(timeouts)) {
  3785. sscanf(timeouts, "%30i", &timeout);
  3786. if (timeout < -1) {
  3787. timeout = -1;
  3788. }
  3789. /* XXX maybe put an upper bound, or prevent the use of 0 ? */
  3790. }
  3791. ao2_lock(s->session);
  3792. if (s->session->waiting_thread != AST_PTHREADT_NULL) {
  3793. pthread_kill(s->session->waiting_thread, SIGURG);
  3794. }
  3795. if (s->session->managerid) { /* AMI-over-HTTP session */
  3796. /*
  3797. * Make sure the timeout is within the expire time of the session,
  3798. * as the client will likely abort the request if it does not see
  3799. * data coming after some amount of time.
  3800. */
  3801. time_t now = time(NULL);
  3802. int max = s->session->sessiontimeout - now - 10;
  3803. if (max < 0) { /* We are already late. Strange but possible. */
  3804. max = 0;
  3805. }
  3806. if (timeout < 0 || timeout > max) {
  3807. timeout = max;
  3808. }
  3809. if (!s->session->send_events) { /* make sure we record events */
  3810. s->session->send_events = -1;
  3811. }
  3812. }
  3813. ao2_unlock(s->session);
  3814. /* XXX should this go inside the lock ? */
  3815. s->session->waiting_thread = pthread_self(); /* let new events wake up this thread */
  3816. ast_debug(1, "Starting waiting for an event!\n");
  3817. for (x = 0; x < timeout || timeout < 0; x++) {
  3818. ao2_lock(s->session);
  3819. if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
  3820. needexit = 1;
  3821. }
  3822. /* We can have multiple HTTP session point to the same mansession entry.
  3823. * The way we deal with it is not very nice: newcomers kick out the previous
  3824. * HTTP session. XXX this needs to be improved.
  3825. */
  3826. if (s->session->waiting_thread != pthread_self()) {
  3827. needexit = 1;
  3828. }
  3829. if (s->session->needdestroy) {
  3830. needexit = 1;
  3831. }
  3832. ao2_unlock(s->session);
  3833. if (needexit) {
  3834. break;
  3835. }
  3836. if (s->session->managerid == 0) { /* AMI session */
  3837. if (ast_wait_for_input(s->session->fd, 1000)) {
  3838. break;
  3839. }
  3840. } else { /* HTTP session */
  3841. sleep(1);
  3842. }
  3843. }
  3844. ast_debug(1, "Finished waiting for an event!\n");
  3845. ao2_lock(s->session);
  3846. if (s->session->waiting_thread == pthread_self()) {
  3847. struct eventqent *eqe = s->session->last_ev;
  3848. astman_send_response(s, m, "Success", "Waiting for Event completed.");
  3849. while ((eqe = advance_event(eqe))) {
  3850. if (((s->session->readperm & eqe->category) == eqe->category)
  3851. && ((s->session->send_events & eqe->category) == eqe->category)
  3852. && match_filter(s, eqe->eventdata)) {
  3853. astman_append(s, "%s", eqe->eventdata);
  3854. }
  3855. s->session->last_ev = eqe;
  3856. }
  3857. astman_append(s,
  3858. "Event: WaitEventComplete\r\n"
  3859. "%s"
  3860. "\r\n", idText);
  3861. s->session->waiting_thread = AST_PTHREADT_NULL;
  3862. } else {
  3863. ast_debug(1, "Abandoning event request!\n");
  3864. }
  3865. ao2_unlock(s->session);
  3866. return 0;
  3867. }
  3868. static int action_listcommands(struct mansession *s, const struct message *m)
  3869. {
  3870. struct manager_action *cur;
  3871. struct ast_str *temp = ast_str_alloca(MAX_AUTH_PERM_STRING);
  3872. astman_start_ack(s, m);
  3873. AST_RWLIST_RDLOCK(&actions);
  3874. AST_RWLIST_TRAVERSE(&actions, cur, list) {
  3875. if ((s->session->writeperm & cur->authority) || cur->authority == 0) {
  3876. astman_append(s, "%s: %s (Priv: %s)\r\n",
  3877. cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
  3878. }
  3879. }
  3880. AST_RWLIST_UNLOCK(&actions);
  3881. astman_append(s, "\r\n");
  3882. return 0;
  3883. }
  3884. static int action_events(struct mansession *s, const struct message *m)
  3885. {
  3886. const char *mask = astman_get_header(m, "EventMask");
  3887. int res, x;
  3888. const char *id = astman_get_header(m, "ActionID");
  3889. char id_text[256];
  3890. if (!ast_strlen_zero(id)) {
  3891. snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
  3892. } else {
  3893. id_text[0] = '\0';
  3894. }
  3895. res = set_eventmask(s, mask);
  3896. if (broken_events_action) {
  3897. /* if this option is set we should not return a response on
  3898. * error, or when all events are set */
  3899. if (res > 0) {
  3900. for (x = 0; x < ARRAY_LEN(perms); x++) {
  3901. if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
  3902. return 0;
  3903. }
  3904. }
  3905. astman_append(s, "Response: Success\r\n%s"
  3906. "Events: On\r\n\r\n", id_text);
  3907. } else if (res == 0)
  3908. astman_append(s, "Response: Success\r\n%s"
  3909. "Events: Off\r\n\r\n", id_text);
  3910. return 0;
  3911. }
  3912. if (res > 0)
  3913. astman_append(s, "Response: Success\r\n%s"
  3914. "Events: On\r\n\r\n", id_text);
  3915. else if (res == 0)
  3916. astman_append(s, "Response: Success\r\n%s"
  3917. "Events: Off\r\n\r\n", id_text);
  3918. else
  3919. astman_send_error(s, m, "Invalid event mask");
  3920. return 0;
  3921. }
  3922. static int action_logoff(struct mansession *s, const struct message *m)
  3923. {
  3924. astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
  3925. return -1;
  3926. }
  3927. static int action_login(struct mansession *s, const struct message *m)
  3928. {
  3929. /* still authenticated - don't process again */
  3930. if (s->session->authenticated) {
  3931. astman_send_ack(s, m, "Already authenticated");
  3932. return 0;
  3933. }
  3934. if (authenticate(s, m)) {
  3935. sleep(1);
  3936. astman_send_error(s, m, "Authentication failed");
  3937. return -1;
  3938. }
  3939. s->session->authenticated = 1;
  3940. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  3941. if (manager_displayconnects(s->session)) {
  3942. ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_sockaddr_stringify_addr(&s->session->addr));
  3943. }
  3944. astman_send_ack(s, m, "Authentication accepted");
  3945. if ((s->session->send_events & EVENT_FLAG_SYSTEM)
  3946. && (s->session->readperm & EVENT_FLAG_SYSTEM)
  3947. && ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
  3948. struct ast_str *auth = ast_str_alloca(MAX_AUTH_PERM_STRING);
  3949. const char *cat_str = authority_to_str(EVENT_FLAG_SYSTEM, &auth);
  3950. astman_append(s, "Event: FullyBooted\r\n"
  3951. "Privilege: %s\r\n"
  3952. "Status: Fully Booted\r\n\r\n", cat_str);
  3953. }
  3954. return 0;
  3955. }
  3956. static int action_challenge(struct mansession *s, const struct message *m)
  3957. {
  3958. const char *authtype = astman_get_header(m, "AuthType");
  3959. if (!strcasecmp(authtype, "MD5")) {
  3960. if (ast_strlen_zero(s->session->challenge)) {
  3961. snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
  3962. }
  3963. mansession_lock(s);
  3964. astman_start_ack(s, m);
  3965. astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
  3966. mansession_unlock(s);
  3967. } else {
  3968. astman_send_error(s, m, "Must specify AuthType");
  3969. }
  3970. return 0;
  3971. }
  3972. static int action_hangup(struct mansession *s, const struct message *m)
  3973. {
  3974. struct ast_channel *c = NULL;
  3975. int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
  3976. const char *id = astman_get_header(m, "ActionID");
  3977. const char *name_or_regex = astman_get_header(m, "Channel");
  3978. const char *cause = astman_get_header(m, "Cause");
  3979. char idText[256];
  3980. regex_t regexbuf;
  3981. struct ast_channel_iterator *iter = NULL;
  3982. struct ast_str *regex_string;
  3983. int channels_matched = 0;
  3984. if (ast_strlen_zero(name_or_regex)) {
  3985. astman_send_error(s, m, "No channel specified");
  3986. return 0;
  3987. }
  3988. if (!ast_strlen_zero(id)) {
  3989. snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
  3990. } else {
  3991. idText[0] = '\0';
  3992. }
  3993. if (!ast_strlen_zero(cause)) {
  3994. char *endptr;
  3995. causecode = strtol(cause, &endptr, 10);
  3996. if (causecode < 0 || causecode > 127 || *endptr != '\0') {
  3997. ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
  3998. /* keep going, better to hangup without cause than to not hang up at all */
  3999. causecode = 0; /* do not set channel's hangupcause */
  4000. }
  4001. }
  4002. /************************************************/
  4003. /* Regular explicit match channel byname hangup */
  4004. if (name_or_regex[0] != '/') {
  4005. if (!(c = ast_channel_get_by_name(name_or_regex))) {
  4006. ast_log(LOG_NOTICE, "Request to hangup non-existent channel: %s\n",
  4007. name_or_regex);
  4008. astman_send_error(s, m, "No such channel");
  4009. return 0;
  4010. }
  4011. ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
  4012. (s->session->managerid ? "HTTP " : ""),
  4013. s->session->username,
  4014. ast_sockaddr_stringify_addr(&s->session->addr),
  4015. ast_channel_name(c));
  4016. ast_channel_softhangup_withcause_locked(c, causecode);
  4017. c = ast_channel_unref(c);
  4018. astman_send_ack(s, m, "Channel Hungup");
  4019. return 0;
  4020. }
  4021. /***********************************************/
  4022. /* find and hangup any channels matching regex */
  4023. regex_string = ast_str_create(strlen(name_or_regex));
  4024. if (!regex_string) {
  4025. astman_send_error(s, m, "Memory Allocation Failure");
  4026. return 0;
  4027. }
  4028. /* Make "/regex/" into "regex" */
  4029. if (ast_regex_string_to_regex_pattern(name_or_regex, &regex_string) != 0) {
  4030. astman_send_error(s, m, "Regex format invalid, Channel param should be /regex/");
  4031. ast_free(regex_string);
  4032. return 0;
  4033. }
  4034. /* if regex compilation fails, hangup fails */
  4035. if (regcomp(&regexbuf, ast_str_buffer(regex_string), REG_EXTENDED | REG_NOSUB)) {
  4036. astman_send_error_va(s, m, "Regex compile failed on: %s", name_or_regex);
  4037. ast_free(regex_string);
  4038. return 0;
  4039. }
  4040. astman_send_listack(s, m, "Channels hung up will follow", "start");
  4041. iter = ast_channel_iterator_all_new();
  4042. if (iter) {
  4043. for (; (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
  4044. if (regexec(&regexbuf, ast_channel_name(c), 0, NULL, 0)) {
  4045. continue;
  4046. }
  4047. ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
  4048. (s->session->managerid ? "HTTP " : ""),
  4049. s->session->username,
  4050. ast_sockaddr_stringify_addr(&s->session->addr),
  4051. ast_channel_name(c));
  4052. ast_channel_softhangup_withcause_locked(c, causecode);
  4053. channels_matched++;
  4054. astman_append(s,
  4055. "Event: ChannelHungup\r\n"
  4056. "Channel: %s\r\n"
  4057. "%s"
  4058. "\r\n", ast_channel_name(c), idText);
  4059. }
  4060. ast_channel_iterator_destroy(iter);
  4061. }
  4062. regfree(&regexbuf);
  4063. ast_free(regex_string);
  4064. astman_send_list_complete_start(s, m, "ChannelsHungupListComplete", channels_matched);
  4065. astman_send_list_complete_end(s);
  4066. return 0;
  4067. }
  4068. static int action_setvar(struct mansession *s, const struct message *m)
  4069. {
  4070. struct ast_channel *c = NULL;
  4071. const char *name = astman_get_header(m, "Channel");
  4072. const char *varname = astman_get_header(m, "Variable");
  4073. const char *varval = astman_get_header(m, "Value");
  4074. int res = 0;
  4075. if (ast_strlen_zero(varname)) {
  4076. astman_send_error(s, m, "No variable specified");
  4077. return 0;
  4078. }
  4079. if (!ast_strlen_zero(name)) {
  4080. if (!(c = ast_channel_get_by_name(name))) {
  4081. astman_send_error(s, m, "No such channel");
  4082. return 0;
  4083. }
  4084. }
  4085. res = pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
  4086. if (c) {
  4087. c = ast_channel_unref(c);
  4088. }
  4089. if (res == 0) {
  4090. astman_send_ack(s, m, "Variable Set");
  4091. } else {
  4092. astman_send_error(s, m, "Variable not set");
  4093. }
  4094. return 0;
  4095. }
  4096. static int action_getvar(struct mansession *s, const struct message *m)
  4097. {
  4098. struct ast_channel *c = NULL;
  4099. const char *name = astman_get_header(m, "Channel");
  4100. const char *varname = astman_get_header(m, "Variable");
  4101. char *varval;
  4102. char workspace[1024];
  4103. if (ast_strlen_zero(varname)) {
  4104. astman_send_error(s, m, "No variable specified");
  4105. return 0;
  4106. }
  4107. /* We don't want users with insufficient permissions using certain functions. */
  4108. if (!(function_capable_string_allowed_with_auths(varname, s->session->writeperm))) {
  4109. astman_send_error(s, m, "GetVar Access Forbidden: Variable");
  4110. return 0;
  4111. }
  4112. if (!ast_strlen_zero(name)) {
  4113. if (!(c = ast_channel_get_by_name(name))) {
  4114. astman_send_error(s, m, "No such channel");
  4115. return 0;
  4116. }
  4117. }
  4118. workspace[0] = '\0';
  4119. if (varname[strlen(varname) - 1] == ')') {
  4120. if (!c) {
  4121. c = ast_dummy_channel_alloc();
  4122. if (c) {
  4123. ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
  4124. } else
  4125. ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
  4126. } else {
  4127. ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
  4128. }
  4129. varval = workspace;
  4130. } else {
  4131. pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
  4132. }
  4133. if (c) {
  4134. c = ast_channel_unref(c);
  4135. }
  4136. astman_start_ack(s, m);
  4137. astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, S_OR(varval, ""));
  4138. return 0;
  4139. }
  4140. /*! \brief Manager "status" command to show channels */
  4141. /* Needs documentation... */
  4142. static int action_status(struct mansession *s, const struct message *m)
  4143. {
  4144. const char *name = astman_get_header(m, "Channel");
  4145. const char *chan_variables = astman_get_header(m, "Variables");
  4146. const char *id = astman_get_header(m, "ActionID");
  4147. char *variables = ast_strdupa(S_OR(chan_variables, ""));
  4148. struct ast_str *variable_str = ast_str_create(1024);
  4149. struct ast_str *write_transpath = ast_str_alloca(256);
  4150. struct ast_str *read_transpath = ast_str_alloca(256);
  4151. struct ast_channel *chan;
  4152. struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
  4153. int channels = 0;
  4154. int all = ast_strlen_zero(name); /* set if we want all channels */
  4155. char id_text[256];
  4156. struct ast_channel_iterator *it_chans = NULL;
  4157. AST_DECLARE_APP_ARGS(vars,
  4158. AST_APP_ARG(name)[100];
  4159. );
  4160. if (!variable_str) {
  4161. astman_send_error(s, m, "Memory Allocation Failure");
  4162. return 1;
  4163. }
  4164. if (!(function_capable_string_allowed_with_auths(variables, s->session->writeperm))) {
  4165. ast_free(variable_str);
  4166. astman_send_error(s, m, "Status Access Forbidden: Variables");
  4167. return 0;
  4168. }
  4169. if (all) {
  4170. if (!(it_chans = ast_channel_iterator_all_new())) {
  4171. ast_free(variable_str);
  4172. astman_send_error(s, m, "Memory Allocation Failure");
  4173. return 1;
  4174. }
  4175. chan = ast_channel_iterator_next(it_chans);
  4176. } else {
  4177. chan = ast_channel_get_by_name(name);
  4178. if (!chan) {
  4179. astman_send_error(s, m, "No such channel");
  4180. ast_free(variable_str);
  4181. return 0;
  4182. }
  4183. }
  4184. astman_send_listack(s, m, "Channel status will follow", "start");
  4185. if (!ast_strlen_zero(id)) {
  4186. snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
  4187. } else {
  4188. id_text[0] = '\0';
  4189. }
  4190. if (!ast_strlen_zero(chan_variables)) {
  4191. AST_STANDARD_APP_ARGS(vars, variables);
  4192. }
  4193. /* if we look by name, we break after the first iteration */
  4194. for (; chan; all ? chan = ast_channel_iterator_next(it_chans) : 0) {
  4195. struct timeval now;
  4196. long elapsed_seconds;
  4197. struct ast_bridge *bridge;
  4198. struct ast_party_id effective_id;
  4199. ast_channel_lock(chan);
  4200. now = ast_tvnow();
  4201. elapsed_seconds = ast_tvdiff_sec(now, ast_channel_creationtime(chan));
  4202. if (!ast_strlen_zero(chan_variables)) {
  4203. int i;
  4204. ast_str_reset(variable_str);
  4205. for (i = 0; i < vars.argc; i++) {
  4206. char valbuf[512], *ret = NULL;
  4207. if (vars.name[i][strlen(vars.name[i]) - 1] == ')') {
  4208. if (ast_func_read(chan, vars.name[i], valbuf, sizeof(valbuf)) < 0) {
  4209. valbuf[0] = '\0';
  4210. }
  4211. ret = valbuf;
  4212. } else {
  4213. pbx_retrieve_variable(chan, vars.name[i], &ret, valbuf, sizeof(valbuf), NULL);
  4214. }
  4215. ast_str_append(&variable_str, 0, "Variable: %s=%s\r\n", vars.name[i], ret);
  4216. }
  4217. }
  4218. channels++;
  4219. bridge = ast_channel_get_bridge(chan);
  4220. effective_id = ast_channel_connected_effective_id(chan);
  4221. astman_append(s,
  4222. "Event: Status\r\n"
  4223. "Privilege: Call\r\n"
  4224. /* v-- Start channel snapshot headers */
  4225. "Channel: %s\r\n"
  4226. "ChannelState: %u\r\n"
  4227. "ChannelStateDesc: %s\r\n"
  4228. "CallerIDNum: %s\r\n"
  4229. "CallerIDName: %s\r\n"
  4230. "ConnectedLineNum: %s\r\n"
  4231. "ConnectedLineName: %s\r\n"
  4232. "Accountcode: %s\r\n"
  4233. "Context: %s\r\n"
  4234. "Exten: %s\r\n"
  4235. "Priority: %d\r\n"
  4236. "Uniqueid: %s\r\n"
  4237. "Linkedid: %s\r\n"
  4238. /* ^-- End channel snapshot headers */
  4239. "Type: %s\r\n"
  4240. "DNID: %s\r\n"
  4241. "EffectiveConnectedLineNum: %s\r\n"
  4242. "EffectiveConnectedLineName: %s\r\n"
  4243. "TimeToHangup: %ld\r\n"
  4244. "BridgeID: %s\r\n"
  4245. "Application: %s\r\n"
  4246. "Data: %s\r\n"
  4247. "Nativeformats: %s\r\n"
  4248. "Readformat: %s\r\n"
  4249. "Readtrans: %s\r\n"
  4250. "Writeformat: %s\r\n"
  4251. "Writetrans: %s\r\n"
  4252. "Callgroup: %llu\r\n"
  4253. "Pickupgroup: %llu\r\n"
  4254. "Seconds: %ld\r\n"
  4255. "%s"
  4256. "%s"
  4257. "\r\n",
  4258. /* v-- Start channel snapshot headers */
  4259. ast_channel_name(chan),
  4260. ast_channel_state(chan),
  4261. ast_state2str(ast_channel_state(chan)),
  4262. S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
  4263. S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
  4264. S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
  4265. S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
  4266. ast_channel_accountcode(chan),
  4267. ast_channel_context(chan),
  4268. ast_channel_exten(chan),
  4269. ast_channel_priority(chan),
  4270. ast_channel_uniqueid(chan),
  4271. ast_channel_linkedid(chan),
  4272. /* ^-- End channel snapshot headers */
  4273. ast_channel_tech(chan)->type,
  4274. S_OR(ast_channel_dialed(chan)->number.str, ""),
  4275. S_COR(effective_id.number.valid, effective_id.number.str, "<unknown>"),
  4276. S_COR(effective_id.name.valid, effective_id.name.str, "<unknown>"),
  4277. (long)ast_channel_whentohangup(chan)->tv_sec,
  4278. bridge ? bridge->uniqueid : "",
  4279. ast_channel_appl(chan),
  4280. ast_channel_data(chan),
  4281. ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf),
  4282. ast_format_get_name(ast_channel_readformat(chan)),
  4283. ast_translate_path_to_str(ast_channel_readtrans(chan), &read_transpath),
  4284. ast_format_get_name(ast_channel_writeformat(chan)),
  4285. ast_translate_path_to_str(ast_channel_writetrans(chan), &write_transpath),
  4286. ast_channel_callgroup(chan),
  4287. ast_channel_pickupgroup(chan),
  4288. (long)elapsed_seconds,
  4289. ast_str_buffer(variable_str),
  4290. id_text);
  4291. ao2_cleanup(bridge);
  4292. ast_channel_unlock(chan);
  4293. chan = ast_channel_unref(chan);
  4294. }
  4295. if (it_chans) {
  4296. ast_channel_iterator_destroy(it_chans);
  4297. }
  4298. astman_send_list_complete_start(s, m, "StatusComplete", channels);
  4299. astman_append(s, "Items: %d\r\n", channels);
  4300. astman_send_list_complete_end(s);
  4301. ast_free(variable_str);
  4302. return 0;
  4303. }
  4304. static int action_sendtext(struct mansession *s, const struct message *m)
  4305. {
  4306. struct ast_channel *c;
  4307. const char *name = astman_get_header(m, "Channel");
  4308. const char *textmsg = astman_get_header(m, "Message");
  4309. struct ast_control_read_action_payload *frame_payload;
  4310. int payload_size;
  4311. int frame_size;
  4312. int res;
  4313. if (ast_strlen_zero(name)) {
  4314. astman_send_error(s, m, "No channel specified");
  4315. return 0;
  4316. }
  4317. if (ast_strlen_zero(textmsg)) {
  4318. astman_send_error(s, m, "No Message specified");
  4319. return 0;
  4320. }
  4321. c = ast_channel_get_by_name(name);
  4322. if (!c) {
  4323. astman_send_error(s, m, "No such channel");
  4324. return 0;
  4325. }
  4326. payload_size = strlen(textmsg) + 1;
  4327. frame_size = payload_size + sizeof(*frame_payload);
  4328. frame_payload = ast_malloc(frame_size);
  4329. if (!frame_payload) {
  4330. ast_channel_unref(c);
  4331. astman_send_error(s, m, "Failure");
  4332. return 0;
  4333. }
  4334. frame_payload->action = AST_FRAME_READ_ACTION_SEND_TEXT;
  4335. frame_payload->payload_size = payload_size;
  4336. memcpy(frame_payload->payload, textmsg, payload_size);
  4337. res = ast_queue_control_data(c, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
  4338. ast_free(frame_payload);
  4339. ast_channel_unref(c);
  4340. if (res >= 0) {
  4341. astman_send_ack(s, m, "Success");
  4342. } else {
  4343. astman_send_error(s, m, "Failure");
  4344. }
  4345. return 0;
  4346. }
  4347. /*! \brief action_redirect: The redirect manager command */
  4348. static int action_redirect(struct mansession *s, const struct message *m)
  4349. {
  4350. char buf[256];
  4351. const char *name = astman_get_header(m, "Channel");
  4352. const char *name2 = astman_get_header(m, "ExtraChannel");
  4353. const char *exten = astman_get_header(m, "Exten");
  4354. const char *exten2 = astman_get_header(m, "ExtraExten");
  4355. const char *context = astman_get_header(m, "Context");
  4356. const char *context2 = astman_get_header(m, "ExtraContext");
  4357. const char *priority = astman_get_header(m, "Priority");
  4358. const char *priority2 = astman_get_header(m, "ExtraPriority");
  4359. struct ast_channel *chan;
  4360. struct ast_channel *chan2;
  4361. int pi = 0;
  4362. int pi2 = 0;
  4363. int res;
  4364. int chan1_wait = 0;
  4365. int chan2_wait = 0;
  4366. if (ast_strlen_zero(name)) {
  4367. astman_send_error(s, m, "Channel not specified");
  4368. return 0;
  4369. }
  4370. if (ast_strlen_zero(context)) {
  4371. astman_send_error(s, m, "Context not specified");
  4372. return 0;
  4373. }
  4374. if (ast_strlen_zero(exten)) {
  4375. astman_send_error(s, m, "Exten not specified");
  4376. return 0;
  4377. }
  4378. if (ast_strlen_zero(priority)) {
  4379. astman_send_error(s, m, "Priority not specified");
  4380. return 0;
  4381. }
  4382. if (sscanf(priority, "%30d", &pi) != 1) {
  4383. pi = ast_findlabel_extension(NULL, context, exten, priority, NULL);
  4384. }
  4385. if (pi < 1) {
  4386. astman_send_error(s, m, "Priority is invalid");
  4387. return 0;
  4388. }
  4389. if (!ast_strlen_zero(name2) && !ast_strlen_zero(context2)) {
  4390. /* We have an ExtraChannel and an ExtraContext */
  4391. if (ast_strlen_zero(exten2)) {
  4392. astman_send_error(s, m, "ExtraExten not specified");
  4393. return 0;
  4394. }
  4395. if (ast_strlen_zero(priority2)) {
  4396. astman_send_error(s, m, "ExtraPriority not specified");
  4397. return 0;
  4398. }
  4399. if (sscanf(priority2, "%30d", &pi2) != 1) {
  4400. pi2 = ast_findlabel_extension(NULL, context2, exten2, priority2, NULL);
  4401. }
  4402. if (pi2 < 1) {
  4403. astman_send_error(s, m, "ExtraPriority is invalid");
  4404. return 0;
  4405. }
  4406. }
  4407. chan = ast_channel_get_by_name(name);
  4408. if (!chan) {
  4409. snprintf(buf, sizeof(buf), "Channel does not exist: %s", name);
  4410. astman_send_error(s, m, buf);
  4411. return 0;
  4412. }
  4413. if (ast_check_hangup_locked(chan)) {
  4414. astman_send_error(s, m, "Redirect failed, channel not up.");
  4415. chan = ast_channel_unref(chan);
  4416. return 0;
  4417. }
  4418. if (ast_strlen_zero(name2)) {
  4419. /* Single channel redirect in progress. */
  4420. res = ast_async_goto(chan, context, exten, pi);
  4421. if (!res) {
  4422. astman_send_ack(s, m, "Redirect successful");
  4423. } else {
  4424. astman_send_error(s, m, "Redirect failed");
  4425. }
  4426. chan = ast_channel_unref(chan);
  4427. return 0;
  4428. }
  4429. chan2 = ast_channel_get_by_name(name2);
  4430. if (!chan2) {
  4431. snprintf(buf, sizeof(buf), "ExtraChannel does not exist: %s", name2);
  4432. astman_send_error(s, m, buf);
  4433. chan = ast_channel_unref(chan);
  4434. return 0;
  4435. }
  4436. if (ast_check_hangup_locked(chan2)) {
  4437. astman_send_error(s, m, "Redirect failed, extra channel not up.");
  4438. chan2 = ast_channel_unref(chan2);
  4439. chan = ast_channel_unref(chan);
  4440. return 0;
  4441. }
  4442. /* Dual channel redirect in progress. */
  4443. ast_channel_lock(chan);
  4444. if (ast_channel_is_bridged(chan)) {
  4445. ast_set_flag(ast_channel_flags(chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
  4446. chan1_wait = 1;
  4447. }
  4448. ast_channel_unlock(chan);
  4449. ast_channel_lock(chan2);
  4450. if (ast_channel_is_bridged(chan2)) {
  4451. ast_set_flag(ast_channel_flags(chan2), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
  4452. chan2_wait = 1;
  4453. }
  4454. ast_channel_unlock(chan2);
  4455. res = ast_async_goto(chan, context, exten, pi);
  4456. if (!res) {
  4457. if (!ast_strlen_zero(context2)) {
  4458. res = ast_async_goto(chan2, context2, exten2, pi2);
  4459. } else {
  4460. res = ast_async_goto(chan2, context, exten, pi);
  4461. }
  4462. if (!res) {
  4463. astman_send_ack(s, m, "Dual Redirect successful");
  4464. } else {
  4465. astman_send_error(s, m, "Secondary redirect failed");
  4466. }
  4467. } else {
  4468. astman_send_error(s, m, "Redirect failed");
  4469. }
  4470. /* Release the bridge wait. */
  4471. if (chan1_wait) {
  4472. ast_channel_clear_flag(chan, AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
  4473. }
  4474. if (chan2_wait) {
  4475. ast_channel_clear_flag(chan2, AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
  4476. }
  4477. chan2 = ast_channel_unref(chan2);
  4478. chan = ast_channel_unref(chan);
  4479. return 0;
  4480. }
  4481. static int action_blind_transfer(struct mansession *s, const struct message *m)
  4482. {
  4483. const char *name = astman_get_header(m, "Channel");
  4484. const char *exten = astman_get_header(m, "Exten");
  4485. const char *context = astman_get_header(m, "Context");
  4486. struct ast_channel *chan;
  4487. if (ast_strlen_zero(name)) {
  4488. astman_send_error(s, m, "No channel specified");
  4489. return 0;
  4490. }
  4491. if (ast_strlen_zero(exten)) {
  4492. astman_send_error(s, m, "No extension specified");
  4493. return 0;
  4494. }
  4495. chan = ast_channel_get_by_name(name);
  4496. if (!chan) {
  4497. astman_send_error(s, m, "Channel specified does not exist");
  4498. return 0;
  4499. }
  4500. if (ast_strlen_zero(context)) {
  4501. context = ast_channel_context(chan);
  4502. }
  4503. switch (ast_bridge_transfer_blind(1, chan, exten, context, NULL, NULL)) {
  4504. case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
  4505. astman_send_error(s, m, "Transfer not permitted");
  4506. break;
  4507. case AST_BRIDGE_TRANSFER_INVALID:
  4508. astman_send_error(s, m, "Transfer invalid");
  4509. break;
  4510. case AST_BRIDGE_TRANSFER_FAIL:
  4511. astman_send_error(s, m, "Transfer failed");
  4512. break;
  4513. case AST_BRIDGE_TRANSFER_SUCCESS:
  4514. astman_send_ack(s, m, "Transfer succeeded");
  4515. break;
  4516. }
  4517. ast_channel_unref(chan);
  4518. return 0;
  4519. }
  4520. static int action_atxfer(struct mansession *s, const struct message *m)
  4521. {
  4522. const char *name = astman_get_header(m, "Channel");
  4523. const char *exten = astman_get_header(m, "Exten");
  4524. const char *context = astman_get_header(m, "Context");
  4525. struct ast_channel *chan = NULL;
  4526. char feature_code[AST_FEATURE_MAX_LEN];
  4527. const char *digit;
  4528. if (ast_strlen_zero(name)) {
  4529. astman_send_error(s, m, "No channel specified");
  4530. return 0;
  4531. }
  4532. if (ast_strlen_zero(exten)) {
  4533. astman_send_error(s, m, "No extension specified");
  4534. return 0;
  4535. }
  4536. if (!(chan = ast_channel_get_by_name(name))) {
  4537. astman_send_error(s, m, "Channel specified does not exist");
  4538. return 0;
  4539. }
  4540. ast_channel_lock(chan);
  4541. if (ast_get_builtin_feature(chan, "atxfer", feature_code, sizeof(feature_code)) ||
  4542. ast_strlen_zero(feature_code)) {
  4543. ast_channel_unlock(chan);
  4544. astman_send_error(s, m, "No attended transfer feature code found");
  4545. ast_channel_unref(chan);
  4546. return 0;
  4547. }
  4548. ast_channel_unlock(chan);
  4549. if (!ast_strlen_zero(context)) {
  4550. pbx_builtin_setvar_helper(chan, "TRANSFER_CONTEXT", context);
  4551. }
  4552. for (digit = feature_code; *digit; ++digit) {
  4553. struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *digit };
  4554. ast_queue_frame(chan, &f);
  4555. }
  4556. for (digit = exten; *digit; ++digit) {
  4557. struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *digit };
  4558. ast_queue_frame(chan, &f);
  4559. }
  4560. chan = ast_channel_unref(chan);
  4561. astman_send_ack(s, m, "Atxfer successfully queued");
  4562. return 0;
  4563. }
  4564. static int action_cancel_atxfer(struct mansession *s, const struct message *m)
  4565. {
  4566. const char *name = astman_get_header(m, "Channel");
  4567. struct ast_channel *chan = NULL;
  4568. char *feature_code;
  4569. const char *digit;
  4570. if (ast_strlen_zero(name)) {
  4571. astman_send_error(s, m, "No channel specified");
  4572. return 0;
  4573. }
  4574. if (!(chan = ast_channel_get_by_name(name))) {
  4575. astman_send_error(s, m, "Channel specified does not exist");
  4576. return 0;
  4577. }
  4578. ast_channel_lock(chan);
  4579. feature_code = ast_get_chan_features_atxferabort(chan);
  4580. ast_channel_unlock(chan);
  4581. if (!feature_code) {
  4582. astman_send_error(s, m, "No disconnect feature code found");
  4583. ast_channel_unref(chan);
  4584. return 0;
  4585. }
  4586. for (digit = feature_code; *digit; ++digit) {
  4587. struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *digit };
  4588. ast_queue_frame(chan, &f);
  4589. }
  4590. ast_free(feature_code);
  4591. chan = ast_channel_unref(chan);
  4592. astman_send_ack(s, m, "CancelAtxfer successfully queued");
  4593. return 0;
  4594. }
  4595. static int check_blacklist(const char *cmd)
  4596. {
  4597. char *cmd_copy, *cur_cmd;
  4598. char *cmd_words[AST_MAX_CMD_LEN] = { NULL, };
  4599. int i;
  4600. cmd_copy = ast_strdupa(cmd);
  4601. for (i = 0; i < MAX_BLACKLIST_CMD_LEN && (cur_cmd = strsep(&cmd_copy, " ")); i++) {
  4602. cur_cmd = ast_strip(cur_cmd);
  4603. if (ast_strlen_zero(cur_cmd)) {
  4604. i--;
  4605. continue;
  4606. }
  4607. cmd_words[i] = cur_cmd;
  4608. }
  4609. for (i = 0; i < ARRAY_LEN(command_blacklist); i++) {
  4610. int j, match = 1;
  4611. for (j = 0; command_blacklist[i].words[j]; j++) {
  4612. if (ast_strlen_zero(cmd_words[j]) || strcasecmp(cmd_words[j], command_blacklist[i].words[j])) {
  4613. match = 0;
  4614. break;
  4615. }
  4616. }
  4617. if (match) {
  4618. return 1;
  4619. }
  4620. }
  4621. return 0;
  4622. }
  4623. /*! \brief Manager command "command" - execute CLI command */
  4624. static int action_command(struct mansession *s, const struct message *m)
  4625. {
  4626. const char *cmd = astman_get_header(m, "Command");
  4627. const char *id = astman_get_header(m, "ActionID");
  4628. char *buf = NULL, *final_buf = NULL;
  4629. char template[] = "/tmp/ast-ami-XXXXXX"; /* template for temporary file */
  4630. int fd;
  4631. off_t l;
  4632. if (ast_strlen_zero(cmd)) {
  4633. astman_send_error(s, m, "No command provided");
  4634. return 0;
  4635. }
  4636. if (check_blacklist(cmd)) {
  4637. astman_send_error(s, m, "Command blacklisted");
  4638. return 0;
  4639. }
  4640. if ((fd = mkstemp(template)) < 0) {
  4641. ast_log(AST_LOG_WARNING, "Failed to create temporary file for command: %s\n", strerror(errno));
  4642. astman_send_error(s, m, "Command response construction error");
  4643. return 0;
  4644. }
  4645. astman_append(s, "Response: Follows\r\nPrivilege: Command\r\n");
  4646. if (!ast_strlen_zero(id)) {
  4647. astman_append(s, "ActionID: %s\r\n", id);
  4648. }
  4649. /* FIXME: Wedge a ActionID response in here, waiting for later changes */
  4650. ast_cli_command(fd, cmd); /* XXX need to change this to use a FILE * */
  4651. /* Determine number of characters available */
  4652. if ((l = lseek(fd, 0, SEEK_END)) < 0) {
  4653. ast_log(LOG_WARNING, "Failed to determine number of characters for command: %s\n", strerror(errno));
  4654. goto action_command_cleanup;
  4655. }
  4656. /* This has a potential to overflow the stack. Hence, use the heap. */
  4657. buf = ast_malloc(l + 1);
  4658. final_buf = ast_malloc(l + 1);
  4659. if (!buf || !final_buf) {
  4660. ast_log(LOG_WARNING, "Failed to allocate memory for temporary buffer\n");
  4661. goto action_command_cleanup;
  4662. }
  4663. if (lseek(fd, 0, SEEK_SET) < 0) {
  4664. ast_log(LOG_WARNING, "Failed to set position on temporary file for command: %s\n", strerror(errno));
  4665. goto action_command_cleanup;
  4666. }
  4667. if (read(fd, buf, l) < 0) {
  4668. ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
  4669. goto action_command_cleanup;
  4670. }
  4671. buf[l] = '\0';
  4672. term_strip(final_buf, buf, l);
  4673. final_buf[l] = '\0';
  4674. astman_append(s, "%s", final_buf);
  4675. action_command_cleanup:
  4676. close(fd);
  4677. unlink(template);
  4678. astman_append(s, "--END COMMAND--\r\n\r\n");
  4679. ast_free(buf);
  4680. ast_free(final_buf);
  4681. return 0;
  4682. }
  4683. /*! \brief helper function for originate */
  4684. struct fast_originate_helper {
  4685. int timeout;
  4686. struct ast_format_cap *cap; /*!< Codecs used for a call */
  4687. int early_media;
  4688. AST_DECLARE_STRING_FIELDS (
  4689. AST_STRING_FIELD(tech);
  4690. /*! data can contain a channel name, extension number, username, password, etc. */
  4691. AST_STRING_FIELD(data);
  4692. AST_STRING_FIELD(app);
  4693. AST_STRING_FIELD(appdata);
  4694. AST_STRING_FIELD(cid_name);
  4695. AST_STRING_FIELD(cid_num);
  4696. AST_STRING_FIELD(context);
  4697. AST_STRING_FIELD(exten);
  4698. AST_STRING_FIELD(idtext);
  4699. AST_STRING_FIELD(account);
  4700. AST_STRING_FIELD(channelid);
  4701. AST_STRING_FIELD(otherchannelid);
  4702. );
  4703. int priority;
  4704. struct ast_variable *vars;
  4705. };
  4706. /*!
  4707. * \internal
  4708. *
  4709. * \param doomed Struct to destroy.
  4710. *
  4711. * \return Nothing
  4712. */
  4713. static void destroy_fast_originate_helper(struct fast_originate_helper *doomed)
  4714. {
  4715. ao2_cleanup(doomed->cap);
  4716. ast_variables_destroy(doomed->vars);
  4717. ast_string_field_free_memory(doomed);
  4718. ast_free(doomed);
  4719. }
  4720. static void *fast_originate(void *data)
  4721. {
  4722. struct fast_originate_helper *in = data;
  4723. int res;
  4724. int reason = 0;
  4725. struct ast_channel *chan = NULL, *chans[1];
  4726. char requested_channel[AST_CHANNEL_NAME];
  4727. struct ast_assigned_ids assignedids = {
  4728. .uniqueid = in->channelid,
  4729. .uniqueid2 = in->otherchannelid
  4730. };
  4731. if (!ast_strlen_zero(in->app)) {
  4732. res = ast_pbx_outgoing_app(in->tech, in->cap, in->data,
  4733. in->timeout, in->app, in->appdata, &reason,
  4734. AST_OUTGOING_WAIT,
  4735. S_OR(in->cid_num, NULL),
  4736. S_OR(in->cid_name, NULL),
  4737. in->vars, in->account, &chan, &assignedids);
  4738. } else {
  4739. res = ast_pbx_outgoing_exten(in->tech, in->cap, in->data,
  4740. in->timeout, in->context, in->exten, in->priority, &reason,
  4741. AST_OUTGOING_WAIT,
  4742. S_OR(in->cid_num, NULL),
  4743. S_OR(in->cid_name, NULL),
  4744. in->vars, in->account, &chan, in->early_media, &assignedids);
  4745. }
  4746. if (!chan) {
  4747. snprintf(requested_channel, AST_CHANNEL_NAME, "%s/%s", in->tech, in->data);
  4748. }
  4749. /* Tell the manager what happened with the channel */
  4750. chans[0] = chan;
  4751. if (!ast_strlen_zero(in->app)) {
  4752. ast_manager_event_multichan(EVENT_FLAG_CALL, "OriginateResponse", chan ? 1 : 0, chans,
  4753. "%s"
  4754. "Response: %s\r\n"
  4755. "Channel: %s\r\n"
  4756. "Application: %s\r\n"
  4757. "Data: %s\r\n"
  4758. "Reason: %d\r\n"
  4759. "Uniqueid: %s\r\n"
  4760. "CallerIDNum: %s\r\n"
  4761. "CallerIDName: %s\r\n",
  4762. in->idtext, res ? "Failure" : "Success",
  4763. chan ? ast_channel_name(chan) : requested_channel,
  4764. in->app, in->appdata, reason,
  4765. chan ? ast_channel_uniqueid(chan) : S_OR(in->channelid, "<unknown>"),
  4766. S_OR(in->cid_num, "<unknown>"),
  4767. S_OR(in->cid_name, "<unknown>")
  4768. );
  4769. } else {
  4770. ast_manager_event_multichan(EVENT_FLAG_CALL, "OriginateResponse", chan ? 1 : 0, chans,
  4771. "%s"
  4772. "Response: %s\r\n"
  4773. "Channel: %s\r\n"
  4774. "Context: %s\r\n"
  4775. "Exten: %s\r\n"
  4776. "Reason: %d\r\n"
  4777. "Uniqueid: %s\r\n"
  4778. "CallerIDNum: %s\r\n"
  4779. "CallerIDName: %s\r\n",
  4780. in->idtext, res ? "Failure" : "Success",
  4781. chan ? ast_channel_name(chan) : requested_channel,
  4782. in->context, in->exten, reason,
  4783. chan ? ast_channel_uniqueid(chan) : S_OR(in->channelid, "<unknown>"),
  4784. S_OR(in->cid_num, "<unknown>"),
  4785. S_OR(in->cid_name, "<unknown>")
  4786. );
  4787. }
  4788. /* Locked and ref'd by ast_pbx_outgoing_exten or ast_pbx_outgoing_app */
  4789. if (chan) {
  4790. ast_channel_unlock(chan);
  4791. ast_channel_unref(chan);
  4792. }
  4793. destroy_fast_originate_helper(in);
  4794. return NULL;
  4795. }
  4796. static int aocmessage_get_unit_entry(const struct message *m, struct ast_aoc_unit_entry *entry, unsigned int entry_num)
  4797. {
  4798. const char *unitamount;
  4799. const char *unittype;
  4800. struct ast_str *str = ast_str_alloca(32);
  4801. memset(entry, 0, sizeof(*entry));
  4802. ast_str_set(&str, 0, "UnitAmount(%u)", entry_num);
  4803. unitamount = astman_get_header(m, ast_str_buffer(str));
  4804. ast_str_set(&str, 0, "UnitType(%u)", entry_num);
  4805. unittype = astman_get_header(m, ast_str_buffer(str));
  4806. if (!ast_strlen_zero(unitamount) && (sscanf(unitamount, "%30u", &entry->amount) == 1)) {
  4807. entry->valid_amount = 1;
  4808. }
  4809. if (!ast_strlen_zero(unittype) && sscanf(unittype, "%30u", &entry->type) == 1) {
  4810. entry->valid_type = 1;
  4811. }
  4812. return 0;
  4813. }
  4814. static int action_aocmessage(struct mansession *s, const struct message *m)
  4815. {
  4816. const char *channel = astman_get_header(m, "Channel");
  4817. const char *pchannel = astman_get_header(m, "ChannelPrefix");
  4818. const char *msgtype = astman_get_header(m, "MsgType");
  4819. const char *chargetype = astman_get_header(m, "ChargeType");
  4820. const char *currencyname = astman_get_header(m, "CurrencyName");
  4821. const char *currencyamount = astman_get_header(m, "CurrencyAmount");
  4822. const char *mult = astman_get_header(m, "CurrencyMultiplier");
  4823. const char *totaltype = astman_get_header(m, "TotalType");
  4824. const char *aocbillingid = astman_get_header(m, "AOCBillingId");
  4825. const char *association_id= astman_get_header(m, "ChargingAssociationId");
  4826. const char *association_num = astman_get_header(m, "ChargingAssociationNumber");
  4827. const char *association_plan = astman_get_header(m, "ChargingAssociationPlan");
  4828. enum ast_aoc_type _msgtype;
  4829. enum ast_aoc_charge_type _chargetype;
  4830. enum ast_aoc_currency_multiplier _mult = AST_AOC_MULT_ONE;
  4831. enum ast_aoc_total_type _totaltype = AST_AOC_TOTAL;
  4832. enum ast_aoc_billing_id _billingid = AST_AOC_BILLING_NA;
  4833. unsigned int _currencyamount = 0;
  4834. int _association_id = 0;
  4835. unsigned int _association_plan = 0;
  4836. struct ast_channel *chan = NULL;
  4837. struct ast_aoc_decoded *decoded = NULL;
  4838. struct ast_aoc_encoded *encoded = NULL;
  4839. size_t encoded_size = 0;
  4840. if (ast_strlen_zero(channel) && ast_strlen_zero(pchannel)) {
  4841. astman_send_error(s, m, "Channel and PartialChannel are not specified. Specify at least one of these.");
  4842. goto aocmessage_cleanup;
  4843. }
  4844. if (!(chan = ast_channel_get_by_name(channel)) && !ast_strlen_zero(pchannel)) {
  4845. chan = ast_channel_get_by_name_prefix(pchannel, strlen(pchannel));
  4846. }
  4847. if (!chan) {
  4848. astman_send_error(s, m, "No such channel");
  4849. goto aocmessage_cleanup;
  4850. }
  4851. if (ast_strlen_zero(msgtype) || (strcasecmp(msgtype, "d") && strcasecmp(msgtype, "e"))) {
  4852. astman_send_error(s, m, "Invalid MsgType");
  4853. goto aocmessage_cleanup;
  4854. }
  4855. if (ast_strlen_zero(chargetype)) {
  4856. astman_send_error(s, m, "ChargeType not specified");
  4857. goto aocmessage_cleanup;
  4858. }
  4859. _msgtype = strcasecmp(msgtype, "d") ? AST_AOC_E : AST_AOC_D;
  4860. if (!strcasecmp(chargetype, "NA")) {
  4861. _chargetype = AST_AOC_CHARGE_NA;
  4862. } else if (!strcasecmp(chargetype, "Free")) {
  4863. _chargetype = AST_AOC_CHARGE_FREE;
  4864. } else if (!strcasecmp(chargetype, "Currency")) {
  4865. _chargetype = AST_AOC_CHARGE_CURRENCY;
  4866. } else if (!strcasecmp(chargetype, "Unit")) {
  4867. _chargetype = AST_AOC_CHARGE_UNIT;
  4868. } else {
  4869. astman_send_error(s, m, "Invalid ChargeType");
  4870. goto aocmessage_cleanup;
  4871. }
  4872. if (_chargetype == AST_AOC_CHARGE_CURRENCY) {
  4873. if (ast_strlen_zero(currencyamount) || (sscanf(currencyamount, "%30u", &_currencyamount) != 1)) {
  4874. astman_send_error(s, m, "Invalid CurrencyAmount, CurrencyAmount is a required when ChargeType is Currency");
  4875. goto aocmessage_cleanup;
  4876. }
  4877. if (ast_strlen_zero(mult)) {
  4878. astman_send_error(s, m, "ChargeMultiplier unspecified, ChargeMultiplier is required when ChargeType is Currency.");
  4879. goto aocmessage_cleanup;
  4880. } else if (!strcasecmp(mult, "onethousandth")) {
  4881. _mult = AST_AOC_MULT_ONETHOUSANDTH;
  4882. } else if (!strcasecmp(mult, "onehundredth")) {
  4883. _mult = AST_AOC_MULT_ONEHUNDREDTH;
  4884. } else if (!strcasecmp(mult, "onetenth")) {
  4885. _mult = AST_AOC_MULT_ONETENTH;
  4886. } else if (!strcasecmp(mult, "one")) {
  4887. _mult = AST_AOC_MULT_ONE;
  4888. } else if (!strcasecmp(mult, "ten")) {
  4889. _mult = AST_AOC_MULT_TEN;
  4890. } else if (!strcasecmp(mult, "hundred")) {
  4891. _mult = AST_AOC_MULT_HUNDRED;
  4892. } else if (!strcasecmp(mult, "thousand")) {
  4893. _mult = AST_AOC_MULT_THOUSAND;
  4894. } else {
  4895. astman_send_error(s, m, "Invalid ChargeMultiplier");
  4896. goto aocmessage_cleanup;
  4897. }
  4898. }
  4899. /* create decoded object and start setting values */
  4900. if (!(decoded = ast_aoc_create(_msgtype, _chargetype, 0))) {
  4901. astman_send_error(s, m, "Message Creation Failed");
  4902. goto aocmessage_cleanup;
  4903. }
  4904. if (_msgtype == AST_AOC_D) {
  4905. if (!ast_strlen_zero(totaltype) && !strcasecmp(totaltype, "subtotal")) {
  4906. _totaltype = AST_AOC_SUBTOTAL;
  4907. }
  4908. if (ast_strlen_zero(aocbillingid)) {
  4909. /* ignore this is optional */
  4910. } else if (!strcasecmp(aocbillingid, "Normal")) {
  4911. _billingid = AST_AOC_BILLING_NORMAL;
  4912. } else if (!strcasecmp(aocbillingid, "ReverseCharge")) {
  4913. _billingid = AST_AOC_BILLING_REVERSE_CHARGE;
  4914. } else if (!strcasecmp(aocbillingid, "CreditCard")) {
  4915. _billingid = AST_AOC_BILLING_CREDIT_CARD;
  4916. } else {
  4917. astman_send_error(s, m, "Invalid AOC-D AOCBillingId");
  4918. goto aocmessage_cleanup;
  4919. }
  4920. } else {
  4921. if (ast_strlen_zero(aocbillingid)) {
  4922. /* ignore this is optional */
  4923. } else if (!strcasecmp(aocbillingid, "Normal")) {
  4924. _billingid = AST_AOC_BILLING_NORMAL;
  4925. } else if (!strcasecmp(aocbillingid, "ReverseCharge")) {
  4926. _billingid = AST_AOC_BILLING_REVERSE_CHARGE;
  4927. } else if (!strcasecmp(aocbillingid, "CreditCard")) {
  4928. _billingid = AST_AOC_BILLING_CREDIT_CARD;
  4929. } else if (!strcasecmp(aocbillingid, "CallFwdUnconditional")) {
  4930. _billingid = AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL;
  4931. } else if (!strcasecmp(aocbillingid, "CallFwdBusy")) {
  4932. _billingid = AST_AOC_BILLING_CALL_FWD_BUSY;
  4933. } else if (!strcasecmp(aocbillingid, "CallFwdNoReply")) {
  4934. _billingid = AST_AOC_BILLING_CALL_FWD_NO_REPLY;
  4935. } else if (!strcasecmp(aocbillingid, "CallDeflection")) {
  4936. _billingid = AST_AOC_BILLING_CALL_DEFLECTION;
  4937. } else if (!strcasecmp(aocbillingid, "CallTransfer")) {
  4938. _billingid = AST_AOC_BILLING_CALL_TRANSFER;
  4939. } else {
  4940. astman_send_error(s, m, "Invalid AOC-E AOCBillingId");
  4941. goto aocmessage_cleanup;
  4942. }
  4943. if (!ast_strlen_zero(association_id) && (sscanf(association_id, "%30d", &_association_id) != 1)) {
  4944. astman_send_error(s, m, "Invalid ChargingAssociationId");
  4945. goto aocmessage_cleanup;
  4946. }
  4947. if (!ast_strlen_zero(association_plan) && (sscanf(association_plan, "%30u", &_association_plan) != 1)) {
  4948. astman_send_error(s, m, "Invalid ChargingAssociationPlan");
  4949. goto aocmessage_cleanup;
  4950. }
  4951. if (_association_id) {
  4952. ast_aoc_set_association_id(decoded, _association_id);
  4953. } else if (!ast_strlen_zero(association_num)) {
  4954. ast_aoc_set_association_number(decoded, association_num, _association_plan);
  4955. }
  4956. }
  4957. if (_chargetype == AST_AOC_CHARGE_CURRENCY) {
  4958. ast_aoc_set_currency_info(decoded, _currencyamount, _mult, ast_strlen_zero(currencyname) ? NULL : currencyname);
  4959. } else if (_chargetype == AST_AOC_CHARGE_UNIT) {
  4960. struct ast_aoc_unit_entry entry;
  4961. int i;
  4962. /* multiple unit entries are possible, lets get them all */
  4963. for (i = 0; i < 32; i++) {
  4964. if (aocmessage_get_unit_entry(m, &entry, i)) {
  4965. break; /* that's the end then */
  4966. }
  4967. ast_aoc_add_unit_entry(decoded, entry.valid_amount, entry.amount, entry.valid_type, entry.type);
  4968. }
  4969. /* at least one unit entry is required */
  4970. if (!i) {
  4971. astman_send_error(s, m, "Invalid UnitAmount(0), At least one valid unit entry is required when ChargeType is set to Unit");
  4972. goto aocmessage_cleanup;
  4973. }
  4974. }
  4975. ast_aoc_set_billing_id(decoded, _billingid);
  4976. ast_aoc_set_total_type(decoded, _totaltype);
  4977. if ((encoded = ast_aoc_encode(decoded, &encoded_size, NULL)) && !ast_indicate_data(chan, AST_CONTROL_AOC, encoded, encoded_size)) {
  4978. astman_send_ack(s, m, "AOC Message successfully queued on channel");
  4979. } else {
  4980. astman_send_error(s, m, "Error encoding AOC message, could not queue onto channel");
  4981. }
  4982. aocmessage_cleanup:
  4983. ast_aoc_destroy_decoded(decoded);
  4984. ast_aoc_destroy_encoded(encoded);
  4985. if (chan) {
  4986. chan = ast_channel_unref(chan);
  4987. }
  4988. return 0;
  4989. }
  4990. static int action_originate(struct mansession *s, const struct message *m)
  4991. {
  4992. const char *name = astman_get_header(m, "Channel");
  4993. const char *exten = astman_get_header(m, "Exten");
  4994. const char *context = astman_get_header(m, "Context");
  4995. const char *priority = astman_get_header(m, "Priority");
  4996. const char *timeout = astman_get_header(m, "Timeout");
  4997. const char *callerid = astman_get_header(m, "CallerID");
  4998. const char *account = astman_get_header(m, "Account");
  4999. const char *app = astman_get_header(m, "Application");
  5000. const char *appdata = astman_get_header(m, "Data");
  5001. const char *async = astman_get_header(m, "Async");
  5002. const char *id = astman_get_header(m, "ActionID");
  5003. const char *codecs = astman_get_header(m, "Codecs");
  5004. const char *early_media = astman_get_header(m, "Earlymedia");
  5005. struct ast_assigned_ids assignedids = {
  5006. .uniqueid = astman_get_header(m, "ChannelId"),
  5007. .uniqueid2 = astman_get_header(m, "OtherChannelId"),
  5008. };
  5009. struct ast_variable *vars = NULL;
  5010. char *tech, *data;
  5011. char *l = NULL, *n = NULL;
  5012. int pi = 0;
  5013. int res;
  5014. int to = 30000;
  5015. int reason = 0;
  5016. char tmp[256];
  5017. char tmp2[256];
  5018. struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  5019. pthread_t th;
  5020. int bridge_early = 0;
  5021. if (!cap) {
  5022. astman_send_error(s, m, "Internal Error. Memory allocation failure.");
  5023. return 0;
  5024. }
  5025. ast_format_cap_append(cap, ast_format_slin, 0);
  5026. if ((assignedids.uniqueid && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid))
  5027. || (assignedids.uniqueid2 && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid2))) {
  5028. astman_send_error_va(s, m, "Uniqueid length exceeds maximum of %d\n",
  5029. AST_MAX_PUBLIC_UNIQUEID);
  5030. res = 0;
  5031. goto fast_orig_cleanup;
  5032. }
  5033. if (ast_strlen_zero(name)) {
  5034. astman_send_error(s, m, "Channel not specified");
  5035. res = 0;
  5036. goto fast_orig_cleanup;
  5037. }
  5038. if (!ast_strlen_zero(priority) && (sscanf(priority, "%30d", &pi) != 1)) {
  5039. if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
  5040. astman_send_error(s, m, "Invalid priority");
  5041. res = 0;
  5042. goto fast_orig_cleanup;
  5043. }
  5044. }
  5045. if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%30d", &to) != 1)) {
  5046. astman_send_error(s, m, "Invalid timeout");
  5047. res = 0;
  5048. goto fast_orig_cleanup;
  5049. }
  5050. ast_copy_string(tmp, name, sizeof(tmp));
  5051. tech = tmp;
  5052. data = strchr(tmp, '/');
  5053. if (!data) {
  5054. astman_send_error(s, m, "Invalid channel");
  5055. res = 0;
  5056. goto fast_orig_cleanup;
  5057. }
  5058. *data++ = '\0';
  5059. ast_copy_string(tmp2, callerid, sizeof(tmp2));
  5060. ast_callerid_parse(tmp2, &n, &l);
  5061. if (n) {
  5062. if (ast_strlen_zero(n)) {
  5063. n = NULL;
  5064. }
  5065. }
  5066. if (l) {
  5067. ast_shrink_phone_number(l);
  5068. if (ast_strlen_zero(l)) {
  5069. l = NULL;
  5070. }
  5071. }
  5072. if (!ast_strlen_zero(codecs)) {
  5073. ast_format_cap_remove_by_type(cap, AST_MEDIA_TYPE_UNKNOWN);
  5074. ast_format_cap_update_by_allow_disallow(cap, codecs, 1);
  5075. }
  5076. if (!ast_strlen_zero(app) && s->session) {
  5077. int bad_appdata = 0;
  5078. /* To run the System application (or anything else that goes to
  5079. * shell), you must have the additional System privilege */
  5080. if (!(s->session->writeperm & EVENT_FLAG_SYSTEM)
  5081. && (
  5082. strcasestr(app, "system") || /* System(rm -rf /)
  5083. TrySystem(rm -rf /) */
  5084. strcasestr(app, "exec") || /* Exec(System(rm -rf /))
  5085. TryExec(System(rm -rf /)) */
  5086. strcasestr(app, "agi") || /* AGI(/bin/rm,-rf /)
  5087. EAGI(/bin/rm,-rf /) */
  5088. strcasestr(app, "mixmonitor") || /* MixMonitor(blah,,rm -rf) */
  5089. strcasestr(app, "externalivr") || /* ExternalIVR(rm -rf) */
  5090. (strstr(appdata, "SHELL") && (bad_appdata = 1)) || /* NoOp(${SHELL(rm -rf /)}) */
  5091. (strstr(appdata, "EVAL") && (bad_appdata = 1)) /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
  5092. )) {
  5093. char error_buf[64];
  5094. snprintf(error_buf, sizeof(error_buf), "Originate Access Forbidden: %s", bad_appdata ? "Data" : "Application");
  5095. astman_send_error(s, m, error_buf);
  5096. res = 0;
  5097. goto fast_orig_cleanup;
  5098. }
  5099. }
  5100. /* Check early if the extension exists. If not, we need to bail out here. */
  5101. if (exten && context && pi) {
  5102. if (! ast_exists_extension(NULL, context, exten, pi, l)) {
  5103. /* The extension does not exist. */
  5104. astman_send_error(s, m, "Extension does not exist.");
  5105. res = 0;
  5106. goto fast_orig_cleanup;
  5107. }
  5108. }
  5109. /* Allocate requested channel variables */
  5110. vars = astman_get_variables(m);
  5111. if (s->session && s->session->chanvars) {
  5112. struct ast_variable *v, *old;
  5113. old = vars;
  5114. vars = NULL;
  5115. /* The variables in the AMI originate action are appended at the end of the list, to override any user variables that apply*/
  5116. vars = ast_variables_dup(s->session->chanvars);
  5117. if (old) {
  5118. for (v = vars; v->next; v = v->next );
  5119. if (v->next) {
  5120. v->next = old; /* Append originate variables at end of list */
  5121. }
  5122. }
  5123. }
  5124. /* For originate async - we can bridge in early media stage */
  5125. bridge_early = ast_true(early_media);
  5126. if (ast_true(async)) {
  5127. struct fast_originate_helper *fast;
  5128. fast = ast_calloc(1, sizeof(*fast));
  5129. if (!fast || ast_string_field_init(fast, 252)) {
  5130. ast_free(fast);
  5131. ast_variables_destroy(vars);
  5132. res = -1;
  5133. } else {
  5134. if (!ast_strlen_zero(id)) {
  5135. ast_string_field_build(fast, idtext, "ActionID: %s\r\n", id);
  5136. }
  5137. ast_string_field_set(fast, tech, tech);
  5138. ast_string_field_set(fast, data, data);
  5139. ast_string_field_set(fast, app, app);
  5140. ast_string_field_set(fast, appdata, appdata);
  5141. ast_string_field_set(fast, cid_num, l);
  5142. ast_string_field_set(fast, cid_name, n);
  5143. ast_string_field_set(fast, context, context);
  5144. ast_string_field_set(fast, exten, exten);
  5145. ast_string_field_set(fast, account, account);
  5146. ast_string_field_set(fast, channelid, assignedids.uniqueid);
  5147. ast_string_field_set(fast, otherchannelid, assignedids.uniqueid2);
  5148. fast->vars = vars;
  5149. fast->cap = cap;
  5150. cap = NULL; /* transfered originate helper the capabilities structure. It is now responsible for freeing it. */
  5151. fast->timeout = to;
  5152. fast->early_media = bridge_early;
  5153. fast->priority = pi;
  5154. if (ast_pthread_create_detached(&th, NULL, fast_originate, fast)) {
  5155. destroy_fast_originate_helper(fast);
  5156. res = -1;
  5157. } else {
  5158. res = 0;
  5159. }
  5160. }
  5161. } else if (!ast_strlen_zero(app)) {
  5162. res = ast_pbx_outgoing_app(tech, cap, data, to, app, appdata, &reason,
  5163. AST_OUTGOING_WAIT, l, n, vars, account, NULL,
  5164. assignedids.uniqueid ? &assignedids : NULL);
  5165. ast_variables_destroy(vars);
  5166. } else {
  5167. if (exten && context && pi) {
  5168. res = ast_pbx_outgoing_exten(tech, cap, data, to,
  5169. context, exten, pi, &reason, AST_OUTGOING_WAIT,
  5170. l, n, vars, account, NULL, bridge_early,
  5171. assignedids.uniqueid ? &assignedids : NULL);
  5172. ast_variables_destroy(vars);
  5173. } else {
  5174. astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
  5175. ast_variables_destroy(vars);
  5176. res = 0;
  5177. goto fast_orig_cleanup;
  5178. }
  5179. }
  5180. if (!res) {
  5181. astman_send_ack(s, m, "Originate successfully queued");
  5182. } else {
  5183. astman_send_error(s, m, "Originate failed");
  5184. }
  5185. fast_orig_cleanup:
  5186. ao2_cleanup(cap);
  5187. return 0;
  5188. }
  5189. static int action_mailboxstatus(struct mansession *s, const struct message *m)
  5190. {
  5191. const char *mailbox = astman_get_header(m, "Mailbox");
  5192. int ret;
  5193. if (ast_strlen_zero(mailbox)) {
  5194. astman_send_error(s, m, "Mailbox not specified");
  5195. return 0;
  5196. }
  5197. ret = ast_app_has_voicemail(mailbox, NULL);
  5198. astman_start_ack(s, m);
  5199. astman_append(s, "Message: Mailbox Status\r\n"
  5200. "Mailbox: %s\r\n"
  5201. "Waiting: %d\r\n\r\n", mailbox, ret);
  5202. return 0;
  5203. }
  5204. static int action_mailboxcount(struct mansession *s, const struct message *m)
  5205. {
  5206. const char *mailbox = astman_get_header(m, "Mailbox");
  5207. int newmsgs = 0, oldmsgs = 0, urgentmsgs = 0;;
  5208. if (ast_strlen_zero(mailbox)) {
  5209. astman_send_error(s, m, "Mailbox not specified");
  5210. return 0;
  5211. }
  5212. ast_app_inboxcount2(mailbox, &urgentmsgs, &newmsgs, &oldmsgs);
  5213. astman_start_ack(s, m);
  5214. astman_append(s, "Message: Mailbox Message Count\r\n"
  5215. "Mailbox: %s\r\n"
  5216. "UrgMessages: %d\r\n"
  5217. "NewMessages: %d\r\n"
  5218. "OldMessages: %d\r\n"
  5219. "\r\n",
  5220. mailbox, urgentmsgs, newmsgs, oldmsgs);
  5221. return 0;
  5222. }
  5223. static int action_extensionstate(struct mansession *s, const struct message *m)
  5224. {
  5225. const char *exten = astman_get_header(m, "Exten");
  5226. const char *context = astman_get_header(m, "Context");
  5227. char hint[256];
  5228. int status;
  5229. if (ast_strlen_zero(exten)) {
  5230. astman_send_error(s, m, "Extension not specified");
  5231. return 0;
  5232. }
  5233. if (ast_strlen_zero(context)) {
  5234. context = "default";
  5235. }
  5236. status = ast_extension_state(NULL, context, exten);
  5237. hint[0] = '\0';
  5238. ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten);
  5239. astman_start_ack(s, m);
  5240. astman_append(s, "Message: Extension Status\r\n"
  5241. "Exten: %s\r\n"
  5242. "Context: %s\r\n"
  5243. "Hint: %s\r\n"
  5244. "Status: %d\r\n"
  5245. "StatusText: %s\r\n"
  5246. "\r\n",
  5247. exten, context, hint, status,
  5248. ast_extension_state2str(status));
  5249. return 0;
  5250. }
  5251. static int action_presencestate(struct mansession *s, const struct message *m)
  5252. {
  5253. const char *provider = astman_get_header(m, "Provider");
  5254. enum ast_presence_state state;
  5255. char *subtype;
  5256. char *message;
  5257. if (ast_strlen_zero(provider)) {
  5258. astman_send_error(s, m, "No provider specified");
  5259. return 0;
  5260. }
  5261. state = ast_presence_state(provider, &subtype, &message);
  5262. if (state == AST_PRESENCE_INVALID) {
  5263. astman_send_error_va(s, m, "Invalid provider %s or provider in invalid state", provider);
  5264. return 0;
  5265. }
  5266. astman_start_ack(s, m);
  5267. astman_append(s, "Message: Presence State\r\n"
  5268. "State: %s\r\n", ast_presence_state2str(state));
  5269. if (!ast_strlen_zero(subtype)) {
  5270. astman_append(s, "Subtype: %s\r\n", subtype);
  5271. }
  5272. if (!ast_strlen_zero(message)) {
  5273. /* XXX The Message header here is deprecated as it
  5274. * duplicates the action response header 'Message'.
  5275. * Remove it in the next major revision of AMI.
  5276. */
  5277. astman_append(s, "Message: %s\r\n"
  5278. "PresenceMessage: %s\r\n",
  5279. message, message);
  5280. }
  5281. astman_append(s, "\r\n");
  5282. return 0;
  5283. }
  5284. static int action_timeout(struct mansession *s, const struct message *m)
  5285. {
  5286. struct ast_channel *c;
  5287. const char *name = astman_get_header(m, "Channel");
  5288. double timeout = atof(astman_get_header(m, "Timeout"));
  5289. struct timeval when = { timeout, 0 };
  5290. if (ast_strlen_zero(name)) {
  5291. astman_send_error(s, m, "No channel specified");
  5292. return 0;
  5293. }
  5294. if (!timeout || timeout < 0) {
  5295. astman_send_error(s, m, "No timeout specified");
  5296. return 0;
  5297. }
  5298. if (!(c = ast_channel_get_by_name(name))) {
  5299. astman_send_error(s, m, "No such channel");
  5300. return 0;
  5301. }
  5302. when.tv_usec = (timeout - when.tv_sec) * 1000000.0;
  5303. ast_channel_lock(c);
  5304. ast_channel_setwhentohangup_tv(c, when);
  5305. ast_channel_unlock(c);
  5306. c = ast_channel_unref(c);
  5307. astman_send_ack(s, m, "Timeout Set");
  5308. return 0;
  5309. }
  5310. static int whitefilter_cmp_fn(void *obj, void *arg, void *data, int flags)
  5311. {
  5312. regex_t *regex_filter = obj;
  5313. const char *eventdata = arg;
  5314. int *result = data;
  5315. if (!regexec(regex_filter, eventdata, 0, NULL, 0)) {
  5316. *result = 1;
  5317. return (CMP_MATCH | CMP_STOP);
  5318. }
  5319. return 0;
  5320. }
  5321. static int blackfilter_cmp_fn(void *obj, void *arg, void *data, int flags)
  5322. {
  5323. regex_t *regex_filter = obj;
  5324. const char *eventdata = arg;
  5325. int *result = data;
  5326. if (!regexec(regex_filter, eventdata, 0, NULL, 0)) {
  5327. *result = 0;
  5328. return (CMP_MATCH | CMP_STOP);
  5329. }
  5330. *result = 1;
  5331. return 0;
  5332. }
  5333. /*!
  5334. * \brief Manager command to add an event filter to a manager session
  5335. * \see For more details look at manager_add_filter
  5336. */
  5337. static int action_filter(struct mansession *s, const struct message *m)
  5338. {
  5339. const char *filter = astman_get_header(m, "Filter");
  5340. const char *operation = astman_get_header(m, "Operation");
  5341. int res;
  5342. if (!strcasecmp(operation, "Add")) {
  5343. res = manager_add_filter(filter, s->session->whitefilters, s->session->blackfilters);
  5344. if (res != FILTER_SUCCESS) {
  5345. if (res == FILTER_ALLOC_FAILED) {
  5346. astman_send_error(s, m, "Internal Error. Failed to allocate regex for filter");
  5347. return 0;
  5348. } else if (res == FILTER_COMPILE_FAIL) {
  5349. astman_send_error(s, m, "Filter did not compile. Check the syntax of the filter given.");
  5350. return 0;
  5351. } else {
  5352. astman_send_error(s, m, "Internal Error. Failed adding filter.");
  5353. return 0;
  5354. }
  5355. }
  5356. astman_send_ack(s, m, "Success");
  5357. return 0;
  5358. }
  5359. astman_send_error(s, m, "Unknown operation");
  5360. return 0;
  5361. }
  5362. /*!
  5363. * \brief Add an event filter to a manager session
  5364. *
  5365. * \param filter_pattern Filter syntax to add, see below for syntax
  5366. *
  5367. * \return FILTER_ALLOC_FAILED Memory allocation failure
  5368. * \return FILTER_COMPILE_FAIL If the filter did not compile
  5369. * \return FILTER_SUCCESS Success
  5370. *
  5371. * Filter will be used to match against each line of a manager event
  5372. * Filter can be any valid regular expression
  5373. * Filter can be a valid regular expression prefixed with !, which will add the filter as a black filter
  5374. *
  5375. * Examples:
  5376. * \code
  5377. * filter_pattern = "Event: Newchannel"
  5378. * filter_pattern = "Event: New.*"
  5379. * filter_pattern = "!Channel: DAHDI.*"
  5380. * \endcode
  5381. *
  5382. */
  5383. static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters) {
  5384. regex_t *new_filter = ao2_t_alloc(sizeof(*new_filter), event_filter_destructor, "event_filter allocation");
  5385. int is_blackfilter;
  5386. if (!new_filter) {
  5387. return FILTER_ALLOC_FAILED;
  5388. }
  5389. if (filter_pattern[0] == '!') {
  5390. is_blackfilter = 1;
  5391. filter_pattern++;
  5392. } else {
  5393. is_blackfilter = 0;
  5394. }
  5395. if (regcomp(new_filter, filter_pattern, REG_EXTENDED | REG_NOSUB)) {
  5396. ao2_t_ref(new_filter, -1, "failed to make regex");
  5397. return FILTER_COMPILE_FAIL;
  5398. }
  5399. if (is_blackfilter) {
  5400. ao2_t_link(blackfilters, new_filter, "link new filter into black user container");
  5401. } else {
  5402. ao2_t_link(whitefilters, new_filter, "link new filter into white user container");
  5403. }
  5404. ao2_ref(new_filter, -1);
  5405. return FILTER_SUCCESS;
  5406. }
  5407. static int match_filter(struct mansession *s, char *eventdata)
  5408. {
  5409. int result = 0;
  5410. if (manager_debug) {
  5411. ast_verbose("<-- Examining AMI event: -->\n%s\n", eventdata);
  5412. } else {
  5413. ast_debug(3, "Examining AMI event:\n%s\n", eventdata);
  5414. }
  5415. if (!ao2_container_count(s->session->whitefilters) && !ao2_container_count(s->session->blackfilters)) {
  5416. return 1; /* no filtering means match all */
  5417. } else if (ao2_container_count(s->session->whitefilters) && !ao2_container_count(s->session->blackfilters)) {
  5418. /* white filters only: implied black all filter processed first, then white filters */
  5419. ao2_t_callback_data(s->session->whitefilters, OBJ_NODATA, whitefilter_cmp_fn, eventdata, &result, "find filter in session filter container");
  5420. } else if (!ao2_container_count(s->session->whitefilters) && ao2_container_count(s->session->blackfilters)) {
  5421. /* black filters only: implied white all filter processed first, then black filters */
  5422. ao2_t_callback_data(s->session->blackfilters, OBJ_NODATA, blackfilter_cmp_fn, eventdata, &result, "find filter in session filter container");
  5423. } else {
  5424. /* white and black filters: implied black all filter processed first, then white filters, and lastly black filters */
  5425. ao2_t_callback_data(s->session->whitefilters, OBJ_NODATA, whitefilter_cmp_fn, eventdata, &result, "find filter in session filter container");
  5426. if (result) {
  5427. result = 0;
  5428. ao2_t_callback_data(s->session->blackfilters, OBJ_NODATA, blackfilter_cmp_fn, eventdata, &result, "find filter in session filter container");
  5429. }
  5430. }
  5431. return result;
  5432. }
  5433. /*!
  5434. * Send any applicable events to the client listening on this socket.
  5435. * Wait only for a finite time on each event, and drop all events whether
  5436. * they are successfully sent or not.
  5437. */
  5438. static int process_events(struct mansession *s)
  5439. {
  5440. int ret = 0;
  5441. ao2_lock(s->session);
  5442. if (s->session->f != NULL) {
  5443. struct eventqent *eqe = s->session->last_ev;
  5444. while ((eqe = advance_event(eqe))) {
  5445. if (eqe->category == EVENT_FLAG_SHUTDOWN) {
  5446. ast_debug(3, "Received CloseSession event\n");
  5447. ret = -1;
  5448. }
  5449. if (!ret && s->session->authenticated &&
  5450. (s->session->readperm & eqe->category) == eqe->category &&
  5451. (s->session->send_events & eqe->category) == eqe->category) {
  5452. if (match_filter(s, eqe->eventdata)) {
  5453. if (send_string(s, eqe->eventdata) < 0)
  5454. ret = -1; /* don't send more */
  5455. }
  5456. }
  5457. s->session->last_ev = eqe;
  5458. }
  5459. }
  5460. ao2_unlock(s->session);
  5461. return ret;
  5462. }
  5463. static int action_userevent(struct mansession *s, const struct message *m)
  5464. {
  5465. const char *event = astman_get_header(m, "UserEvent");
  5466. struct ast_str *body = ast_str_thread_get(&userevent_buf, 16);
  5467. int x;
  5468. ast_str_reset(body);
  5469. for (x = 0; x < m->hdrcount; x++) {
  5470. if (strncasecmp("UserEvent:", m->headers[x], strlen("UserEvent:")) &&
  5471. strncasecmp("Action:", m->headers[x], strlen("Action:"))) {
  5472. ast_str_append(&body, 0, "%s\r\n", m->headers[x]);
  5473. }
  5474. }
  5475. astman_send_ack(s, m, "Event Sent");
  5476. manager_event(EVENT_FLAG_USER, "UserEvent", "UserEvent: %s\r\n%s", event, ast_str_buffer(body));
  5477. return 0;
  5478. }
  5479. /*! \brief Show PBX core settings information */
  5480. static int action_coresettings(struct mansession *s, const struct message *m)
  5481. {
  5482. const char *actionid = astman_get_header(m, "ActionID");
  5483. char idText[150];
  5484. if (!ast_strlen_zero(actionid)) {
  5485. snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
  5486. } else {
  5487. idText[0] = '\0';
  5488. }
  5489. astman_append(s, "Response: Success\r\n"
  5490. "%s"
  5491. "AMIversion: %s\r\n"
  5492. "AsteriskVersion: %s\r\n"
  5493. "SystemName: %s\r\n"
  5494. "CoreMaxCalls: %d\r\n"
  5495. "CoreMaxLoadAvg: %f\r\n"
  5496. "CoreRunUser: %s\r\n"
  5497. "CoreRunGroup: %s\r\n"
  5498. "CoreMaxFilehandles: %d\r\n"
  5499. "CoreRealTimeEnabled: %s\r\n"
  5500. "CoreCDRenabled: %s\r\n"
  5501. "CoreHTTPenabled: %s\r\n"
  5502. "\r\n",
  5503. idText,
  5504. AMI_VERSION,
  5505. ast_get_version(),
  5506. ast_config_AST_SYSTEM_NAME,
  5507. ast_option_maxcalls,
  5508. ast_option_maxload,
  5509. ast_config_AST_RUN_USER,
  5510. ast_config_AST_RUN_GROUP,
  5511. ast_option_maxfiles,
  5512. AST_CLI_YESNO(ast_realtime_enabled()),
  5513. AST_CLI_YESNO(ast_cdr_is_enabled()),
  5514. AST_CLI_YESNO(check_webmanager_enabled())
  5515. );
  5516. return 0;
  5517. }
  5518. /*! \brief Show PBX core status information */
  5519. static int action_corestatus(struct mansession *s, const struct message *m)
  5520. {
  5521. const char *actionid = astman_get_header(m, "ActionID");
  5522. char idText[150];
  5523. char startuptime[150], startupdate[150];
  5524. char reloadtime[150], reloaddate[150];
  5525. struct ast_tm tm;
  5526. if (!ast_strlen_zero(actionid)) {
  5527. snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
  5528. } else {
  5529. idText[0] = '\0';
  5530. }
  5531. ast_localtime(&ast_startuptime, &tm, NULL);
  5532. ast_strftime(startuptime, sizeof(startuptime), "%H:%M:%S", &tm);
  5533. ast_strftime(startupdate, sizeof(startupdate), "%Y-%m-%d", &tm);
  5534. ast_localtime(&ast_lastreloadtime, &tm, NULL);
  5535. ast_strftime(reloadtime, sizeof(reloadtime), "%H:%M:%S", &tm);
  5536. ast_strftime(reloaddate, sizeof(reloaddate), "%Y-%m-%d", &tm);
  5537. astman_append(s, "Response: Success\r\n"
  5538. "%s"
  5539. "CoreStartupDate: %s\r\n"
  5540. "CoreStartupTime: %s\r\n"
  5541. "CoreReloadDate: %s\r\n"
  5542. "CoreReloadTime: %s\r\n"
  5543. "CoreCurrentCalls: %d\r\n"
  5544. "\r\n",
  5545. idText,
  5546. startupdate,
  5547. startuptime,
  5548. reloaddate,
  5549. reloadtime,
  5550. ast_active_channels()
  5551. );
  5552. return 0;
  5553. }
  5554. /*! \brief Send a reload event */
  5555. static int action_reload(struct mansession *s, const struct message *m)
  5556. {
  5557. const char *module = astman_get_header(m, "Module");
  5558. enum ast_module_reload_result res = ast_module_reload(S_OR(module, NULL));
  5559. switch (res) {
  5560. case AST_MODULE_RELOAD_NOT_FOUND:
  5561. astman_send_error(s, m, "No such module");
  5562. break;
  5563. case AST_MODULE_RELOAD_NOT_IMPLEMENTED:
  5564. astman_send_error(s, m, "Module does not support reload");
  5565. break;
  5566. case AST_MODULE_RELOAD_ERROR:
  5567. astman_send_error(s, m, "An unknown error occurred");
  5568. break;
  5569. case AST_MODULE_RELOAD_IN_PROGRESS:
  5570. astman_send_error(s, m, "A reload is in progress");
  5571. break;
  5572. case AST_MODULE_RELOAD_UNINITIALIZED:
  5573. astman_send_error(s, m, "Module not initialized");
  5574. break;
  5575. case AST_MODULE_RELOAD_QUEUED:
  5576. case AST_MODULE_RELOAD_SUCCESS:
  5577. /* Treat a queued request as success */
  5578. astman_send_ack(s, m, "Module Reloaded");
  5579. break;
  5580. }
  5581. return 0;
  5582. }
  5583. /*! \brief Manager command "CoreShowChannels" - List currently defined channels
  5584. * and some information about them. */
  5585. static int action_coreshowchannels(struct mansession *s, const struct message *m)
  5586. {
  5587. const char *actionid = astman_get_header(m, "ActionID");
  5588. char idText[256];
  5589. int numchans = 0;
  5590. struct ao2_container *channels;
  5591. struct ao2_iterator it_chans;
  5592. struct stasis_message *msg;
  5593. if (!ast_strlen_zero(actionid)) {
  5594. snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
  5595. } else {
  5596. idText[0] = '\0';
  5597. }
  5598. channels = stasis_cache_dump(ast_channel_cache_by_name(), ast_channel_snapshot_type());
  5599. if (!channels) {
  5600. astman_send_error(s, m, "Could not get cached channels");
  5601. return 0;
  5602. }
  5603. astman_send_listack(s, m, "Channels will follow", "start");
  5604. it_chans = ao2_iterator_init(channels, 0);
  5605. for (; (msg = ao2_iterator_next(&it_chans)); ao2_ref(msg, -1)) {
  5606. struct ast_channel_snapshot *cs = stasis_message_data(msg);
  5607. struct ast_str *built = ast_manager_build_channel_state_string_prefix(cs, "");
  5608. char durbuf[16] = "";
  5609. if (!built) {
  5610. continue;
  5611. }
  5612. if (!ast_tvzero(cs->creationtime)) {
  5613. int duration, durh, durm, durs;
  5614. duration = (int)(ast_tvdiff_ms(ast_tvnow(), cs->creationtime) / 1000);
  5615. durh = duration / 3600;
  5616. durm = (duration % 3600) / 60;
  5617. durs = duration % 60;
  5618. snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
  5619. }
  5620. astman_append(s,
  5621. "Event: CoreShowChannel\r\n"
  5622. "%s"
  5623. "%s"
  5624. "Application: %s\r\n"
  5625. "ApplicationData: %s\r\n"
  5626. "Duration: %s\r\n"
  5627. "BridgeId: %s\r\n"
  5628. "\r\n",
  5629. idText,
  5630. ast_str_buffer(built),
  5631. cs->appl,
  5632. cs->data,
  5633. durbuf,
  5634. cs->bridgeid);
  5635. numchans++;
  5636. ast_free(built);
  5637. }
  5638. ao2_iterator_destroy(&it_chans);
  5639. astman_send_list_complete_start(s, m, "CoreShowChannelsComplete", numchans);
  5640. astman_send_list_complete_end(s);
  5641. ao2_ref(channels, -1);
  5642. return 0;
  5643. }
  5644. /*! \brief Manager command "LoggerRotate" - reloads and rotates the logger in
  5645. * the same manner as the CLI command 'logger rotate'. */
  5646. static int action_loggerrotate(struct mansession *s, const struct message *m)
  5647. {
  5648. if (ast_logger_rotate()) {
  5649. astman_send_error(s, m, "Failed to reload the logger and rotate log files");
  5650. return 0;
  5651. }
  5652. astman_send_ack(s, m, "Reloaded the logger and rotated log files");
  5653. return 0;
  5654. }
  5655. /*! \brief Manager function to check if module is loaded */
  5656. static int manager_modulecheck(struct mansession *s, const struct message *m)
  5657. {
  5658. int res;
  5659. const char *module = astman_get_header(m, "Module");
  5660. const char *id = astman_get_header(m, "ActionID");
  5661. char idText[256];
  5662. char filename[PATH_MAX];
  5663. char *cut;
  5664. ast_copy_string(filename, module, sizeof(filename));
  5665. if ((cut = strchr(filename, '.'))) {
  5666. *cut = '\0';
  5667. } else {
  5668. cut = filename + strlen(filename);
  5669. }
  5670. snprintf(cut, (sizeof(filename) - strlen(filename)) - 1, ".so");
  5671. ast_debug(1, "**** ModuleCheck .so file %s\n", filename);
  5672. res = ast_module_check(filename);
  5673. if (!res) {
  5674. astman_send_error(s, m, "Module not loaded");
  5675. return 0;
  5676. }
  5677. if (!ast_strlen_zero(id)) {
  5678. snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
  5679. } else {
  5680. idText[0] = '\0';
  5681. }
  5682. astman_append(s, "Response: Success\r\n%s", idText);
  5683. #if !defined(LOW_MEMORY)
  5684. astman_append(s, "Version: %s\r\n\r\n", ast_get_version());
  5685. #endif
  5686. return 0;
  5687. }
  5688. static int manager_moduleload(struct mansession *s, const struct message *m)
  5689. {
  5690. int res;
  5691. const char *module = astman_get_header(m, "Module");
  5692. const char *loadtype = astman_get_header(m, "LoadType");
  5693. if (!loadtype || strlen(loadtype) == 0) {
  5694. astman_send_error(s, m, "Incomplete ModuleLoad action.");
  5695. }
  5696. if ((!module || strlen(module) == 0) && strcasecmp(loadtype, "reload") != 0) {
  5697. astman_send_error(s, m, "Need module name");
  5698. }
  5699. if (!strcasecmp(loadtype, "load")) {
  5700. res = ast_load_resource(module);
  5701. if (res) {
  5702. astman_send_error(s, m, "Could not load module.");
  5703. } else {
  5704. astman_send_ack(s, m, "Module loaded.");
  5705. }
  5706. } else if (!strcasecmp(loadtype, "unload")) {
  5707. res = ast_unload_resource(module, AST_FORCE_SOFT);
  5708. if (res) {
  5709. astman_send_error(s, m, "Could not unload module.");
  5710. } else {
  5711. astman_send_ack(s, m, "Module unloaded.");
  5712. }
  5713. } else if (!strcasecmp(loadtype, "reload")) {
  5714. /* TODO: Unify the ack/error messages here with action_reload */
  5715. if (!ast_strlen_zero(module)) {
  5716. enum ast_module_reload_result reload_res = ast_module_reload(module);
  5717. switch (reload_res) {
  5718. case AST_MODULE_RELOAD_NOT_FOUND:
  5719. astman_send_error(s, m, "No such module.");
  5720. break;
  5721. case AST_MODULE_RELOAD_NOT_IMPLEMENTED:
  5722. astman_send_error(s, m, "Module does not support reload action.");
  5723. break;
  5724. case AST_MODULE_RELOAD_ERROR:
  5725. astman_send_error(s, m, "An unknown error occurred");
  5726. break;
  5727. case AST_MODULE_RELOAD_IN_PROGRESS:
  5728. astman_send_error(s, m, "A reload is in progress");
  5729. break;
  5730. case AST_MODULE_RELOAD_UNINITIALIZED:
  5731. astman_send_error(s, m, "Module not initialized");
  5732. break;
  5733. case AST_MODULE_RELOAD_QUEUED:
  5734. case AST_MODULE_RELOAD_SUCCESS:
  5735. /* Treat a queued request as success */
  5736. astman_send_ack(s, m, "Module reloaded.");
  5737. break;
  5738. }
  5739. } else {
  5740. ast_module_reload(NULL); /* Reload all modules */
  5741. astman_send_ack(s, m, "All modules reloaded");
  5742. }
  5743. } else
  5744. astman_send_error(s, m, "Incomplete ModuleLoad action.");
  5745. return 0;
  5746. }
  5747. /*
  5748. * Done with the action handlers here, we start with the code in charge
  5749. * of accepting connections and serving them.
  5750. * accept_thread() forks a new thread for each connection, session_do(),
  5751. * which in turn calls get_input() repeatedly until a full message has
  5752. * been accumulated, and then invokes process_message() to pass it to
  5753. * the appropriate handler.
  5754. */
  5755. /*! \brief
  5756. * Process an AMI message, performing desired action.
  5757. * Return 0 on success, -1 on error that require the session to be destroyed.
  5758. */
  5759. static int process_message(struct mansession *s, const struct message *m)
  5760. {
  5761. int ret = 0;
  5762. struct manager_action *act_found;
  5763. struct ast_manager_user *user = NULL;
  5764. const char *username;
  5765. const char *action;
  5766. action = __astman_get_header(m, "Action", GET_HEADER_SKIP_EMPTY);
  5767. if (ast_strlen_zero(action)) {
  5768. report_req_bad_format(s, "NONE");
  5769. mansession_lock(s);
  5770. astman_send_error(s, m, "Missing action in request");
  5771. mansession_unlock(s);
  5772. return 0;
  5773. }
  5774. if (ast_shutting_down()) {
  5775. ast_log(LOG_ERROR, "Unable to process manager action '%s'. Asterisk is shutting down.\n", action);
  5776. mansession_lock(s);
  5777. astman_send_error(s, m, "Asterisk is shutting down");
  5778. mansession_unlock(s);
  5779. return 0;
  5780. }
  5781. if (!s->session->authenticated
  5782. && strcasecmp(action, "Login")
  5783. && strcasecmp(action, "Logoff")
  5784. && strcasecmp(action, "Challenge")) {
  5785. if (!s->session->authenticated) {
  5786. report_req_not_allowed(s, action);
  5787. }
  5788. mansession_lock(s);
  5789. astman_send_error(s, m, "Permission denied");
  5790. mansession_unlock(s);
  5791. return 0;
  5792. }
  5793. if (!s->session->authenticated
  5794. && (!strcasecmp(action, "Login")
  5795. || !strcasecmp(action, "Challenge"))) {
  5796. username = astman_get_header(m, "Username");
  5797. if (!ast_strlen_zero(username) && check_manager_session_inuse(username)) {
  5798. AST_RWLIST_WRLOCK(&users);
  5799. user = get_manager_by_name_locked(username);
  5800. if (user && !user->allowmultiplelogin) {
  5801. AST_RWLIST_UNLOCK(&users);
  5802. report_session_limit(s);
  5803. sleep(1);
  5804. mansession_lock(s);
  5805. astman_send_error(s, m, "Login Already In Use");
  5806. mansession_unlock(s);
  5807. return -1;
  5808. }
  5809. AST_RWLIST_UNLOCK(&users);
  5810. }
  5811. }
  5812. act_found = action_find(action);
  5813. if (act_found) {
  5814. /* Found the requested AMI action. */
  5815. int acted = 0;
  5816. if ((s->session->writeperm & act_found->authority)
  5817. || act_found->authority == 0) {
  5818. /* We have the authority to execute the action. */
  5819. ao2_lock(act_found);
  5820. if (act_found->registered && act_found->func) {
  5821. ast_debug(1, "Running action '%s'\n", act_found->action);
  5822. if (act_found->module) {
  5823. ast_module_ref(act_found->module);
  5824. }
  5825. ao2_unlock(act_found);
  5826. ret = act_found->func(s, m);
  5827. acted = 1;
  5828. ao2_lock(act_found);
  5829. if (act_found->module) {
  5830. ast_module_unref(act_found->module);
  5831. }
  5832. }
  5833. ao2_unlock(act_found);
  5834. }
  5835. if (!acted) {
  5836. /*
  5837. * We did not execute the action because access was denied, it
  5838. * was no longer registered, or no action was really registered.
  5839. * Complain about it and leave.
  5840. */
  5841. report_req_not_allowed(s, action);
  5842. mansession_lock(s);
  5843. astman_send_error(s, m, "Permission denied");
  5844. mansession_unlock(s);
  5845. }
  5846. ao2_t_ref(act_found, -1, "done with found action object");
  5847. } else {
  5848. char buf[512];
  5849. report_req_bad_format(s, action);
  5850. snprintf(buf, sizeof(buf), "Invalid/unknown command: %s. Use Action: ListCommands to show available commands.", action);
  5851. mansession_lock(s);
  5852. astman_send_error(s, m, buf);
  5853. mansession_unlock(s);
  5854. }
  5855. if (ret) {
  5856. return ret;
  5857. }
  5858. /* Once done with our message, deliver any pending events unless the
  5859. requester doesn't want them as part of this response.
  5860. */
  5861. if (ast_strlen_zero(astman_get_header(m, "SuppressEvents"))) {
  5862. return process_events(s);
  5863. } else {
  5864. return ret;
  5865. }
  5866. }
  5867. /*!
  5868. * Read one full line (including crlf) from the manager socket.
  5869. * \note \verbatim
  5870. * \r\n is the only valid terminator for the line.
  5871. * (Note that, later, '\0' will be considered as the end-of-line marker,
  5872. * so everything between the '\0' and the '\r\n' will not be used).
  5873. * Also note that we assume output to have at least "maxlen" space.
  5874. * \endverbatim
  5875. */
  5876. static int get_input(struct mansession *s, char *output)
  5877. {
  5878. int res, x;
  5879. int maxlen = sizeof(s->session->inbuf) - 1;
  5880. char *src = s->session->inbuf;
  5881. int timeout = -1;
  5882. time_t now;
  5883. /*
  5884. * Look for \r\n within the buffer. If found, copy to the output
  5885. * buffer and return, trimming the \r\n (not used afterwards).
  5886. */
  5887. for (x = 0; x < s->session->inlen; x++) {
  5888. int cr; /* set if we have \r */
  5889. if (src[x] == '\r' && x+1 < s->session->inlen && src[x + 1] == '\n') {
  5890. cr = 2; /* Found. Update length to include \r\n */
  5891. } else if (src[x] == '\n') {
  5892. cr = 1; /* also accept \n only */
  5893. } else {
  5894. continue;
  5895. }
  5896. memmove(output, src, x); /*... but trim \r\n */
  5897. output[x] = '\0'; /* terminate the string */
  5898. x += cr; /* number of bytes used */
  5899. s->session->inlen -= x; /* remaining size */
  5900. memmove(src, src + x, s->session->inlen); /* remove used bytes */
  5901. return 1;
  5902. }
  5903. if (s->session->inlen >= maxlen) {
  5904. /* no crlf found, and buffer full - sorry, too long for us */
  5905. ast_log(LOG_WARNING, "Discarding message from %s. Line too long: %.25s...\n", ast_sockaddr_stringify_addr(&s->session->addr), src);
  5906. s->session->inlen = 0;
  5907. s->parsing = MESSAGE_LINE_TOO_LONG;
  5908. }
  5909. res = 0;
  5910. while (res == 0) {
  5911. /* calculate a timeout if we are not authenticated */
  5912. if (!s->session->authenticated) {
  5913. if(time(&now) == -1) {
  5914. ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
  5915. return -1;
  5916. }
  5917. timeout = (authtimeout - (now - s->session->authstart)) * 1000;
  5918. if (timeout < 0) {
  5919. /* we have timed out */
  5920. return 0;
  5921. }
  5922. }
  5923. ao2_lock(s->session);
  5924. if (s->session->pending_event) {
  5925. s->session->pending_event = 0;
  5926. ao2_unlock(s->session);
  5927. return 0;
  5928. }
  5929. s->session->waiting_thread = pthread_self();
  5930. ao2_unlock(s->session);
  5931. res = ast_wait_for_input(s->session->fd, timeout);
  5932. ao2_lock(s->session);
  5933. s->session->waiting_thread = AST_PTHREADT_NULL;
  5934. ao2_unlock(s->session);
  5935. }
  5936. if (res < 0) {
  5937. /* If we get a signal from some other thread (typically because
  5938. * there are new events queued), return 0 to notify the caller.
  5939. */
  5940. if (errno == EINTR || errno == EAGAIN) {
  5941. return 0;
  5942. }
  5943. ast_log(LOG_WARNING, "poll() returned error: %s\n", strerror(errno));
  5944. return -1;
  5945. }
  5946. ao2_lock(s->session);
  5947. /*
  5948. * It is worth noting here that you can all but ignore fread()'s documentation
  5949. * for the purposes of this call. The FILE * we are working with here was created
  5950. * as a result of a call to fopencookie() (or equivalent) in tcptls.c, and as such
  5951. * the behavior of fread() is not as documented. Frankly, I think this is gross.
  5952. */
  5953. res = fread(src + s->session->inlen, 1, maxlen - s->session->inlen, s->session->f);
  5954. if (res < 1) {
  5955. res = -1; /* error return */
  5956. } else {
  5957. s->session->inlen += res;
  5958. src[s->session->inlen] = '\0';
  5959. res = 0;
  5960. }
  5961. ao2_unlock(s->session);
  5962. return res;
  5963. }
  5964. /*!
  5965. * \internal
  5966. * \brief Error handling for sending parse errors. This function handles locking, and clearing the
  5967. * parse error flag.
  5968. *
  5969. * \param s AMI session to process action request.
  5970. * \param m Message that's in error.
  5971. * \param error Error message to send.
  5972. */
  5973. static void handle_parse_error(struct mansession *s, struct message *m, char *error)
  5974. {
  5975. mansession_lock(s);
  5976. astman_send_error(s, m, error);
  5977. s->parsing = MESSAGE_OKAY;
  5978. mansession_unlock(s);
  5979. }
  5980. /*!
  5981. * \internal
  5982. * \brief Read and process an AMI action request.
  5983. *
  5984. * \param s AMI session to process action request.
  5985. *
  5986. * \retval 0 Retain AMI connection for next command.
  5987. * \retval -1 Drop AMI connection due to logoff or connection error.
  5988. */
  5989. static int do_message(struct mansession *s)
  5990. {
  5991. struct message m = { 0 };
  5992. char header_buf[sizeof(s->session->inbuf)] = { '\0' };
  5993. int res;
  5994. int hdr_loss;
  5995. time_t now;
  5996. hdr_loss = 0;
  5997. for (;;) {
  5998. /* Check if any events are pending and do them if needed */
  5999. if (process_events(s)) {
  6000. res = -1;
  6001. break;
  6002. }
  6003. res = get_input(s, header_buf);
  6004. if (res == 0) {
  6005. /* No input line received. */
  6006. if (!s->session->authenticated) {
  6007. if (time(&now) == -1) {
  6008. ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
  6009. res = -1;
  6010. break;
  6011. }
  6012. if (now - s->session->authstart > authtimeout) {
  6013. if (displayconnects) {
  6014. ast_verb(2, "Client from %s, failed to authenticate in %d seconds\n", ast_sockaddr_stringify_addr(&s->session->addr), authtimeout);
  6015. }
  6016. res = -1;
  6017. break;
  6018. }
  6019. }
  6020. continue;
  6021. } else if (res > 0) {
  6022. /* Input line received. */
  6023. if (ast_strlen_zero(header_buf)) {
  6024. if (hdr_loss) {
  6025. mansession_lock(s);
  6026. astman_send_error(s, &m, "Too many lines in message or allocation failure");
  6027. mansession_unlock(s);
  6028. res = 0;
  6029. } else {
  6030. switch (s->parsing) {
  6031. case MESSAGE_OKAY:
  6032. res = process_message(s, &m) ? -1 : 0;
  6033. break;
  6034. case MESSAGE_LINE_TOO_LONG:
  6035. handle_parse_error(s, &m, "Failed to parse message: line too long");
  6036. res = 0;
  6037. break;
  6038. }
  6039. }
  6040. break;
  6041. } else if (m.hdrcount < ARRAY_LEN(m.headers)) {
  6042. m.headers[m.hdrcount] = ast_strdup(header_buf);
  6043. if (!m.headers[m.hdrcount]) {
  6044. /* Allocation failure. */
  6045. hdr_loss = 1;
  6046. } else {
  6047. ++m.hdrcount;
  6048. }
  6049. } else {
  6050. /* Too many lines in message. */
  6051. hdr_loss = 1;
  6052. }
  6053. } else {
  6054. /* Input error. */
  6055. break;
  6056. }
  6057. }
  6058. astman_free_headers(&m);
  6059. return res;
  6060. }
  6061. /*! \brief The body of the individual manager session.
  6062. * Call get_input() to read one line at a time
  6063. * (or be woken up on new events), collect the lines in a
  6064. * message until found an empty line, and execute the request.
  6065. * In any case, deliver events asynchronously through process_events()
  6066. * (called from here if no line is available, or at the end of
  6067. * process_message(). )
  6068. */
  6069. static void *session_do(void *data)
  6070. {
  6071. struct ast_tcptls_session_instance *ser = data;
  6072. struct mansession_session *session;
  6073. struct mansession s = {
  6074. .tcptls_session = data,
  6075. };
  6076. int flags = 1;
  6077. int res;
  6078. struct ast_sockaddr ser_remote_address_tmp;
  6079. if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
  6080. fclose(ser->f);
  6081. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  6082. goto done;
  6083. }
  6084. ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
  6085. session = build_mansession(&ser_remote_address_tmp);
  6086. if (session == NULL) {
  6087. fclose(ser->f);
  6088. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  6089. goto done;
  6090. }
  6091. /* here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
  6092. * This is necessary to prevent delays (caused by buffering) as we
  6093. * write to the socket in bits and pieces. */
  6094. if (setsockopt(ser->fd, IPPROTO_TCP, TCP_NODELAY, (char *) &flags, sizeof(flags)) < 0) {
  6095. ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on manager connection: %s\n", strerror(errno));
  6096. }
  6097. /* make sure socket is non-blocking */
  6098. ast_fd_set_flags(ser->fd, O_NONBLOCK);
  6099. ao2_lock(session);
  6100. /* Hook to the tail of the event queue */
  6101. session->last_ev = grab_last();
  6102. ast_mutex_init(&s.lock);
  6103. /* these fields duplicate those in the 'ser' structure */
  6104. session->fd = s.fd = ser->fd;
  6105. session->f = s.f = ser->f;
  6106. ast_sockaddr_copy(&session->addr, &ser_remote_address_tmp);
  6107. s.session = session;
  6108. AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
  6109. if(time(&session->authstart) == -1) {
  6110. ast_log(LOG_ERROR, "error executing time(): %s; disconnecting client\n", strerror(errno));
  6111. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  6112. ao2_unlock(session);
  6113. session_destroy(session);
  6114. goto done;
  6115. }
  6116. ao2_unlock(session);
  6117. /*
  6118. * We cannot let the stream exclusively wait for data to arrive.
  6119. * We have to wake up the task to send async events.
  6120. */
  6121. ast_tcptls_stream_set_exclusive_input(ser->stream_cookie, 0);
  6122. ast_tcptls_stream_set_timeout_sequence(ser->stream_cookie,
  6123. ast_tvnow(), authtimeout * 1000);
  6124. astman_append(&s, "Asterisk Call Manager/%s\r\n", AMI_VERSION); /* welcome prompt */
  6125. for (;;) {
  6126. if ((res = do_message(&s)) < 0 || s.write_error) {
  6127. break;
  6128. }
  6129. if (session->authenticated) {
  6130. ast_tcptls_stream_set_timeout_disable(ser->stream_cookie);
  6131. }
  6132. }
  6133. /* session is over, explain why and terminate */
  6134. if (session->authenticated) {
  6135. if (manager_displayconnects(session)) {
  6136. ast_verb(2, "Manager '%s' logged off from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
  6137. }
  6138. } else {
  6139. ast_atomic_fetchadd_int(&unauth_sessions, -1);
  6140. if (displayconnects) {
  6141. ast_verb(2, "Connect attempt from '%s' unable to authenticate\n", ast_sockaddr_stringify_addr(&session->addr));
  6142. }
  6143. }
  6144. session_destroy(session);
  6145. ast_mutex_destroy(&s.lock);
  6146. done:
  6147. ao2_ref(ser, -1);
  6148. ser = NULL;
  6149. return NULL;
  6150. }
  6151. /*! \brief remove at most n_max stale session from the list. */
  6152. static void purge_sessions(int n_max)
  6153. {
  6154. struct ao2_container *sessions;
  6155. struct mansession_session *session;
  6156. time_t now = time(NULL);
  6157. struct ao2_iterator i;
  6158. sessions = ao2_global_obj_ref(mgr_sessions);
  6159. if (!sessions) {
  6160. return;
  6161. }
  6162. i = ao2_iterator_init(sessions, 0);
  6163. ao2_ref(sessions, -1);
  6164. while ((session = ao2_iterator_next(&i)) && n_max > 0) {
  6165. ao2_lock(session);
  6166. if (session->sessiontimeout && (now > session->sessiontimeout) && !session->inuse) {
  6167. if (session->authenticated
  6168. && VERBOSITY_ATLEAST(2)
  6169. && manager_displayconnects(session)) {
  6170. ast_verb(2, "HTTP Manager '%s' timed out from %s\n",
  6171. session->username, ast_sockaddr_stringify_addr(&session->addr));
  6172. }
  6173. ao2_unlock(session);
  6174. session_destroy(session);
  6175. n_max--;
  6176. } else {
  6177. ao2_unlock(session);
  6178. unref_mansession(session);
  6179. }
  6180. }
  6181. ao2_iterator_destroy(&i);
  6182. }
  6183. /*! \brief
  6184. * events are appended to a queue from where they
  6185. * can be dispatched to clients.
  6186. */
  6187. static int append_event(const char *str, int category)
  6188. {
  6189. struct eventqent *tmp = ast_malloc(sizeof(*tmp) + strlen(str));
  6190. static int seq; /* sequence number */
  6191. if (!tmp) {
  6192. return -1;
  6193. }
  6194. /* need to init all fields, because ast_malloc() does not */
  6195. tmp->usecount = 0;
  6196. tmp->category = category;
  6197. tmp->seq = ast_atomic_fetchadd_int(&seq, 1);
  6198. tmp->tv = ast_tvnow();
  6199. AST_RWLIST_NEXT(tmp, eq_next) = NULL;
  6200. strcpy(tmp->eventdata, str);
  6201. AST_RWLIST_WRLOCK(&all_events);
  6202. AST_RWLIST_INSERT_TAIL(&all_events, tmp, eq_next);
  6203. AST_RWLIST_UNLOCK(&all_events);
  6204. return 0;
  6205. }
  6206. static void append_channel_vars(struct ast_str **pbuf, struct ast_channel *chan)
  6207. {
  6208. struct varshead *vars;
  6209. struct ast_var_t *var;
  6210. vars = ast_channel_get_manager_vars(chan);
  6211. if (!vars) {
  6212. return;
  6213. }
  6214. AST_LIST_TRAVERSE(vars, var, entries) {
  6215. ast_str_append(pbuf, 0, "ChanVariable(%s): %s=%s\r\n", ast_channel_name(chan), var->name, var->value);
  6216. }
  6217. ao2_ref(vars, -1);
  6218. }
  6219. /* XXX see if can be moved inside the function */
  6220. AST_THREADSTORAGE(manager_event_buf);
  6221. #define MANAGER_EVENT_BUF_INITSIZE 256
  6222. static int __attribute__((format(printf, 9, 0))) __manager_event_sessions_va(
  6223. struct ao2_container *sessions,
  6224. int category,
  6225. const char *event,
  6226. int chancount,
  6227. struct ast_channel **chans,
  6228. const char *file,
  6229. int line,
  6230. const char *func,
  6231. const char *fmt,
  6232. va_list ap)
  6233. {
  6234. struct ast_str *auth = ast_str_alloca(MAX_AUTH_PERM_STRING);
  6235. const char *cat_str;
  6236. struct timeval now;
  6237. struct ast_str *buf;
  6238. int i;
  6239. buf = ast_str_thread_get(&manager_event_buf, MANAGER_EVENT_BUF_INITSIZE);
  6240. if (!buf) {
  6241. return -1;
  6242. }
  6243. cat_str = authority_to_str(category, &auth);
  6244. ast_str_set(&buf, 0,
  6245. "Event: %s\r\n"
  6246. "Privilege: %s\r\n",
  6247. event, cat_str);
  6248. if (timestampevents) {
  6249. now = ast_tvnow();
  6250. ast_str_append(&buf, 0,
  6251. "Timestamp: %ld.%06lu\r\n",
  6252. (long)now.tv_sec, (unsigned long) now.tv_usec);
  6253. }
  6254. if (manager_debug) {
  6255. static int seq;
  6256. ast_str_append(&buf, 0,
  6257. "SequenceNumber: %d\r\n",
  6258. ast_atomic_fetchadd_int(&seq, 1));
  6259. ast_str_append(&buf, 0,
  6260. "File: %s\r\n"
  6261. "Line: %d\r\n"
  6262. "Func: %s\r\n",
  6263. file, line, func);
  6264. }
  6265. if (!ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
  6266. ast_str_append(&buf, 0,
  6267. "SystemName: %s\r\n",
  6268. ast_config_AST_SYSTEM_NAME);
  6269. }
  6270. ast_str_append_va(&buf, 0, fmt, ap);
  6271. for (i = 0; i < chancount; i++) {
  6272. append_channel_vars(&buf, chans[i]);
  6273. }
  6274. ast_str_append(&buf, 0, "\r\n");
  6275. append_event(ast_str_buffer(buf), category);
  6276. /* Wake up any sleeping sessions */
  6277. if (sessions) {
  6278. struct ao2_iterator iter;
  6279. struct mansession_session *session;
  6280. iter = ao2_iterator_init(sessions, 0);
  6281. while ((session = ao2_iterator_next(&iter))) {
  6282. ao2_lock(session);
  6283. if (session->waiting_thread != AST_PTHREADT_NULL) {
  6284. pthread_kill(session->waiting_thread, SIGURG);
  6285. } else {
  6286. /* We have an event to process, but the mansession is
  6287. * not waiting for it. We still need to indicate that there
  6288. * is an event waiting so that get_input processes the pending
  6289. * event instead of polling.
  6290. */
  6291. session->pending_event = 1;
  6292. }
  6293. ao2_unlock(session);
  6294. unref_mansession(session);
  6295. }
  6296. ao2_iterator_destroy(&iter);
  6297. }
  6298. if (category != EVENT_FLAG_SHUTDOWN && !AST_RWLIST_EMPTY(&manager_hooks)) {
  6299. struct manager_custom_hook *hook;
  6300. AST_RWLIST_RDLOCK(&manager_hooks);
  6301. AST_RWLIST_TRAVERSE(&manager_hooks, hook, list) {
  6302. hook->helper(category, event, ast_str_buffer(buf));
  6303. }
  6304. AST_RWLIST_UNLOCK(&manager_hooks);
  6305. }
  6306. return 0;
  6307. }
  6308. static int __attribute__((format(printf, 9, 0))) __manager_event_sessions(
  6309. struct ao2_container *sessions,
  6310. int category,
  6311. const char *event,
  6312. int chancount,
  6313. struct ast_channel **chans,
  6314. const char *file,
  6315. int line,
  6316. const char *func,
  6317. const char *fmt,
  6318. ...)
  6319. {
  6320. va_list ap;
  6321. int res;
  6322. va_start(ap, fmt);
  6323. res = __manager_event_sessions_va(sessions, category, event, chancount, chans,
  6324. file, line, func, fmt, ap);
  6325. va_end(ap);
  6326. return res;
  6327. }
  6328. int __ast_manager_event_multichan(int category, const char *event, int chancount,
  6329. struct ast_channel **chans, const char *file, int line, const char *func,
  6330. const char *fmt, ...)
  6331. {
  6332. struct ao2_container *sessions = ao2_global_obj_ref(mgr_sessions);
  6333. va_list ap;
  6334. int res;
  6335. if (!any_manager_listeners(sessions)) {
  6336. /* Nobody is listening */
  6337. ao2_cleanup(sessions);
  6338. return 0;
  6339. }
  6340. va_start(ap, fmt);
  6341. res = __manager_event_sessions_va(sessions, category, event, chancount, chans,
  6342. file, line, func, fmt, ap);
  6343. va_end(ap);
  6344. ao2_cleanup(sessions);
  6345. return res;
  6346. }
  6347. /*! \brief
  6348. * support functions to register/unregister AMI action handlers,
  6349. */
  6350. int ast_manager_unregister(const char *action)
  6351. {
  6352. struct manager_action *cur;
  6353. AST_RWLIST_WRLOCK(&actions);
  6354. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&actions, cur, list) {
  6355. if (!strcasecmp(action, cur->action)) {
  6356. AST_RWLIST_REMOVE_CURRENT(list);
  6357. break;
  6358. }
  6359. }
  6360. AST_RWLIST_TRAVERSE_SAFE_END;
  6361. AST_RWLIST_UNLOCK(&actions);
  6362. if (cur) {
  6363. /*
  6364. * We have removed the action object from the container so we
  6365. * are no longer in a hurry.
  6366. */
  6367. ao2_lock(cur);
  6368. cur->registered = 0;
  6369. ao2_unlock(cur);
  6370. ao2_t_ref(cur, -1, "action object removed from list");
  6371. ast_verb(2, "Manager unregistered action %s\n", action);
  6372. }
  6373. return 0;
  6374. }
  6375. static int manager_state_cb(char *context, char *exten, struct ast_state_cb_info *info, void *data)
  6376. {
  6377. /* Notify managers of change */
  6378. char hint[512];
  6379. hint[0] = '\0';
  6380. ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten);
  6381. switch(info->reason) {
  6382. case AST_HINT_UPDATE_DEVICE:
  6383. manager_event(EVENT_FLAG_CALL, "ExtensionStatus",
  6384. "Exten: %s\r\n"
  6385. "Context: %s\r\n"
  6386. "Hint: %s\r\n"
  6387. "Status: %d\r\n"
  6388. "StatusText: %s\r\n",
  6389. exten,
  6390. context,
  6391. hint,
  6392. info->exten_state,
  6393. ast_extension_state2str(info->exten_state));
  6394. break;
  6395. case AST_HINT_UPDATE_PRESENCE:
  6396. manager_event(EVENT_FLAG_CALL, "PresenceStatus",
  6397. "Exten: %s\r\n"
  6398. "Context: %s\r\n"
  6399. "Hint: %s\r\n"
  6400. "Status: %s\r\n"
  6401. "Subtype: %s\r\n"
  6402. "Message: %s\r\n",
  6403. exten,
  6404. context,
  6405. hint,
  6406. ast_presence_state2str(info->presence_state),
  6407. info->presence_subtype,
  6408. info->presence_message);
  6409. break;
  6410. }
  6411. return 0;
  6412. }
  6413. static int ast_manager_register_struct(struct manager_action *act)
  6414. {
  6415. struct manager_action *cur, *prev = NULL;
  6416. AST_RWLIST_WRLOCK(&actions);
  6417. AST_RWLIST_TRAVERSE(&actions, cur, list) {
  6418. int ret;
  6419. ret = strcasecmp(cur->action, act->action);
  6420. if (ret == 0) {
  6421. ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
  6422. AST_RWLIST_UNLOCK(&actions);
  6423. return -1;
  6424. }
  6425. if (ret > 0) { /* Insert these alphabetically */
  6426. break;
  6427. }
  6428. prev = cur;
  6429. }
  6430. ao2_t_ref(act, +1, "action object added to list");
  6431. act->registered = 1;
  6432. if (prev) {
  6433. AST_RWLIST_INSERT_AFTER(&actions, prev, act, list);
  6434. } else {
  6435. AST_RWLIST_INSERT_HEAD(&actions, act, list);
  6436. }
  6437. ast_verb(2, "Manager registered action %s\n", act->action);
  6438. AST_RWLIST_UNLOCK(&actions);
  6439. return 0;
  6440. }
  6441. /*!
  6442. * \internal
  6443. * \brief Destroy the registered AMI action object.
  6444. *
  6445. * \param obj Object to destroy.
  6446. *
  6447. * \return Nothing
  6448. */
  6449. static void action_destroy(void *obj)
  6450. {
  6451. struct manager_action *doomed = obj;
  6452. if (doomed->synopsis) {
  6453. /* The string fields were initialized. */
  6454. ast_string_field_free_memory(doomed);
  6455. }
  6456. ao2_cleanup(doomed->final_response);
  6457. ao2_cleanup(doomed->list_responses);
  6458. }
  6459. /*! \brief register a new command with manager, including online help. This is
  6460. the preferred way to register a manager command */
  6461. int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, const struct message *m), struct ast_module *module, const char *synopsis, const char *description)
  6462. {
  6463. struct manager_action *cur;
  6464. cur = ao2_t_alloc(sizeof(*cur), action_destroy, action);
  6465. if (!cur) {
  6466. return -1;
  6467. }
  6468. if (ast_string_field_init(cur, 128)) {
  6469. ao2_t_ref(cur, -1, "action object creation failed");
  6470. return -1;
  6471. }
  6472. cur->action = action;
  6473. cur->authority = auth;
  6474. cur->func = func;
  6475. cur->module = module;
  6476. #ifdef AST_XML_DOCS
  6477. if (ast_strlen_zero(synopsis) && ast_strlen_zero(description)) {
  6478. char *tmpxml;
  6479. tmpxml = ast_xmldoc_build_synopsis("manager", action, NULL);
  6480. ast_string_field_set(cur, synopsis, tmpxml);
  6481. ast_free(tmpxml);
  6482. tmpxml = ast_xmldoc_build_syntax("manager", action, NULL);
  6483. ast_string_field_set(cur, syntax, tmpxml);
  6484. ast_free(tmpxml);
  6485. tmpxml = ast_xmldoc_build_description("manager", action, NULL);
  6486. ast_string_field_set(cur, description, tmpxml);
  6487. ast_free(tmpxml);
  6488. tmpxml = ast_xmldoc_build_seealso("manager", action, NULL);
  6489. ast_string_field_set(cur, seealso, tmpxml);
  6490. ast_free(tmpxml);
  6491. tmpxml = ast_xmldoc_build_arguments("manager", action, NULL);
  6492. ast_string_field_set(cur, arguments, tmpxml);
  6493. ast_free(tmpxml);
  6494. cur->final_response = ast_xmldoc_build_final_response("manager", action, NULL);
  6495. cur->list_responses = ast_xmldoc_build_list_responses("manager", action, NULL);
  6496. cur->docsrc = AST_XML_DOC;
  6497. } else
  6498. #endif
  6499. {
  6500. ast_string_field_set(cur, synopsis, synopsis);
  6501. ast_string_field_set(cur, description, description);
  6502. #ifdef AST_XML_DOCS
  6503. cur->docsrc = AST_STATIC_DOC;
  6504. #endif
  6505. }
  6506. if (ast_manager_register_struct(cur)) {
  6507. ao2_t_ref(cur, -1, "action object registration failed");
  6508. return -1;
  6509. }
  6510. ao2_t_ref(cur, -1, "action object registration successful");
  6511. return 0;
  6512. }
  6513. /*! @}
  6514. END Doxygen group */
  6515. /*
  6516. * The following are support functions for AMI-over-http.
  6517. * The common entry point is generic_http_callback(),
  6518. * which extracts HTTP header and URI fields and reformats
  6519. * them into AMI messages, locates a proper session
  6520. * (using the mansession_id Cookie or GET variable),
  6521. * and calls process_message() as for regular AMI clients.
  6522. * When done, the output (which goes to a temporary file)
  6523. * is read back into a buffer and reformatted as desired,
  6524. * then fed back to the client over the original socket.
  6525. */
  6526. enum output_format {
  6527. FORMAT_RAW,
  6528. FORMAT_HTML,
  6529. FORMAT_XML,
  6530. };
  6531. static const char * const contenttype[] = {
  6532. [FORMAT_RAW] = "plain",
  6533. [FORMAT_HTML] = "html",
  6534. [FORMAT_XML] = "xml",
  6535. };
  6536. /*!
  6537. * locate an http session in the list. The search key (ident) is
  6538. * the value of the mansession_id cookie (0 is not valid and means
  6539. * a session on the AMI socket).
  6540. */
  6541. static struct mansession_session *find_session(uint32_t ident, int incinuse)
  6542. {
  6543. struct ao2_container *sessions;
  6544. struct mansession_session *session;
  6545. struct ao2_iterator i;
  6546. if (ident == 0) {
  6547. return NULL;
  6548. }
  6549. sessions = ao2_global_obj_ref(mgr_sessions);
  6550. if (!sessions) {
  6551. return NULL;
  6552. }
  6553. i = ao2_iterator_init(sessions, 0);
  6554. ao2_ref(sessions, -1);
  6555. while ((session = ao2_iterator_next(&i))) {
  6556. ao2_lock(session);
  6557. if (session->managerid == ident && !session->needdestroy) {
  6558. ast_atomic_fetchadd_int(&session->inuse, incinuse ? 1 : 0);
  6559. break;
  6560. }
  6561. ao2_unlock(session);
  6562. unref_mansession(session);
  6563. }
  6564. ao2_iterator_destroy(&i);
  6565. return session;
  6566. }
  6567. /*!
  6568. * locate an http session in the list.
  6569. * The search keys (nonce) and (username) is value from received
  6570. * "Authorization" http header.
  6571. * As well as in find_session() function, the value of the nonce can't be zero.
  6572. * (0 meansi, that the session used for AMI socket connection).
  6573. * Flag (stale) is set, if client used valid, but old, nonce value.
  6574. *
  6575. */
  6576. static struct mansession_session *find_session_by_nonce(const char *username, unsigned long nonce, int *stale)
  6577. {
  6578. struct mansession_session *session;
  6579. struct ao2_container *sessions;
  6580. struct ao2_iterator i;
  6581. if (nonce == 0 || username == NULL || stale == NULL) {
  6582. return NULL;
  6583. }
  6584. sessions = ao2_global_obj_ref(mgr_sessions);
  6585. if (!sessions) {
  6586. return NULL;
  6587. }
  6588. i = ao2_iterator_init(sessions, 0);
  6589. ao2_ref(sessions, -1);
  6590. while ((session = ao2_iterator_next(&i))) {
  6591. ao2_lock(session);
  6592. if (!strcasecmp(session->username, username) && session->managerid == nonce) {
  6593. *stale = 0;
  6594. break;
  6595. } else if (!strcasecmp(session->username, username) && session->oldnonce == nonce) {
  6596. *stale = 1;
  6597. break;
  6598. }
  6599. ao2_unlock(session);
  6600. unref_mansession(session);
  6601. }
  6602. ao2_iterator_destroy(&i);
  6603. return session;
  6604. }
  6605. int astman_is_authed(uint32_t ident)
  6606. {
  6607. int authed;
  6608. struct mansession_session *session;
  6609. if (!(session = find_session(ident, 0)))
  6610. return 0;
  6611. authed = (session->authenticated != 0);
  6612. ao2_unlock(session);
  6613. unref_mansession(session);
  6614. return authed;
  6615. }
  6616. int astman_verify_session_readpermissions(uint32_t ident, int perm)
  6617. {
  6618. int result = 0;
  6619. struct mansession_session *session;
  6620. struct ao2_container *sessions;
  6621. struct ao2_iterator i;
  6622. if (ident == 0) {
  6623. return 0;
  6624. }
  6625. sessions = ao2_global_obj_ref(mgr_sessions);
  6626. if (!sessions) {
  6627. return 0;
  6628. }
  6629. i = ao2_iterator_init(sessions, 0);
  6630. ao2_ref(sessions, -1);
  6631. while ((session = ao2_iterator_next(&i))) {
  6632. ao2_lock(session);
  6633. if ((session->managerid == ident) && (session->readperm & perm)) {
  6634. result = 1;
  6635. ao2_unlock(session);
  6636. unref_mansession(session);
  6637. break;
  6638. }
  6639. ao2_unlock(session);
  6640. unref_mansession(session);
  6641. }
  6642. ao2_iterator_destroy(&i);
  6643. return result;
  6644. }
  6645. int astman_verify_session_writepermissions(uint32_t ident, int perm)
  6646. {
  6647. int result = 0;
  6648. struct mansession_session *session;
  6649. struct ao2_container *sessions;
  6650. struct ao2_iterator i;
  6651. if (ident == 0) {
  6652. return 0;
  6653. }
  6654. sessions = ao2_global_obj_ref(mgr_sessions);
  6655. if (!sessions) {
  6656. return 0;
  6657. }
  6658. i = ao2_iterator_init(sessions, 0);
  6659. ao2_ref(sessions, -1);
  6660. while ((session = ao2_iterator_next(&i))) {
  6661. ao2_lock(session);
  6662. if ((session->managerid == ident) && (session->writeperm & perm)) {
  6663. result = 1;
  6664. ao2_unlock(session);
  6665. unref_mansession(session);
  6666. break;
  6667. }
  6668. ao2_unlock(session);
  6669. unref_mansession(session);
  6670. }
  6671. ao2_iterator_destroy(&i);
  6672. return result;
  6673. }
  6674. /*
  6675. * convert to xml with various conversion:
  6676. * mode & 1 -> lowercase;
  6677. * mode & 2 -> replace non-alphanumeric chars with underscore
  6678. */
  6679. static void xml_copy_escape(struct ast_str **out, const char *src, int mode)
  6680. {
  6681. /* store in a local buffer to avoid calling ast_str_append too often */
  6682. char buf[256];
  6683. char *dst = buf;
  6684. int space = sizeof(buf);
  6685. /* repeat until done and nothing to flush */
  6686. for ( ; *src || dst != buf ; src++) {
  6687. if (*src == '\0' || space < 10) { /* flush */
  6688. *dst++ = '\0';
  6689. ast_str_append(out, 0, "%s", buf);
  6690. dst = buf;
  6691. space = sizeof(buf);
  6692. if (*src == '\0') {
  6693. break;
  6694. }
  6695. }
  6696. if ( (mode & 2) && !isalnum(*src)) {
  6697. *dst++ = '_';
  6698. space--;
  6699. continue;
  6700. }
  6701. switch (*src) {
  6702. case '<':
  6703. strcpy(dst, "&lt;");
  6704. dst += 4;
  6705. space -= 4;
  6706. break;
  6707. case '>':
  6708. strcpy(dst, "&gt;");
  6709. dst += 4;
  6710. space -= 4;
  6711. break;
  6712. case '\"':
  6713. strcpy(dst, "&quot;");
  6714. dst += 6;
  6715. space -= 6;
  6716. break;
  6717. case '\'':
  6718. strcpy(dst, "&apos;");
  6719. dst += 6;
  6720. space -= 6;
  6721. break;
  6722. case '&':
  6723. strcpy(dst, "&amp;");
  6724. dst += 5;
  6725. space -= 5;
  6726. break;
  6727. default:
  6728. *dst++ = mode ? tolower(*src) : *src;
  6729. space--;
  6730. }
  6731. }
  6732. }
  6733. struct variable_count {
  6734. char *varname;
  6735. int count;
  6736. };
  6737. static int variable_count_hash_fn(const void *vvc, const int flags)
  6738. {
  6739. const struct variable_count *vc = vvc;
  6740. return ast_str_hash(vc->varname);
  6741. }
  6742. static int variable_count_cmp_fn(void *obj, void *vstr, int flags)
  6743. {
  6744. /* Due to the simplicity of struct variable_count, it makes no difference
  6745. * if you pass in objects or strings, the same operation applies. This is
  6746. * due to the fact that the hash occurs on the first element, which means
  6747. * the address of both the struct and the string are exactly the same. */
  6748. struct variable_count *vc = obj;
  6749. char *str = vstr;
  6750. return !strcmp(vc->varname, str) ? CMP_MATCH | CMP_STOP : 0;
  6751. }
  6752. /*! \brief Convert the input into XML or HTML.
  6753. * The input is supposed to be a sequence of lines of the form
  6754. * Name: value
  6755. * optionally followed by a blob of unformatted text.
  6756. * A blank line is a section separator. Basically, this is a
  6757. * mixture of the format of Manager Interface and CLI commands.
  6758. * The unformatted text is considered as a single value of a field
  6759. * named 'Opaque-data'.
  6760. *
  6761. * At the moment the output format is the following (but it may
  6762. * change depending on future requirements so don't count too
  6763. * much on it when writing applications):
  6764. *
  6765. * General: the unformatted text is used as a value of
  6766. * XML output: to be completed
  6767. *
  6768. * \verbatim
  6769. * Each section is within <response type="object" id="xxx">
  6770. * where xxx is taken from ajaxdest variable or defaults to unknown
  6771. * Each row is reported as an attribute Name="value" of an XML
  6772. * entity named from the variable ajaxobjtype, default to "generic"
  6773. * \endverbatim
  6774. *
  6775. * HTML output:
  6776. * each Name-value pair is output as a single row of a two-column table.
  6777. * Sections (blank lines in the input) are separated by a <HR>
  6778. *
  6779. */
  6780. static void xml_translate(struct ast_str **out, char *in, struct ast_variable *get_vars, enum output_format format)
  6781. {
  6782. struct ast_variable *v;
  6783. const char *dest = NULL;
  6784. char *var, *val;
  6785. const char *objtype = NULL;
  6786. int in_data = 0; /* parsing data */
  6787. int inobj = 0;
  6788. int xml = (format == FORMAT_XML);
  6789. struct variable_count *vc = NULL;
  6790. struct ao2_container *vco = NULL;
  6791. if (xml) {
  6792. /* dest and objtype need only for XML format */
  6793. for (v = get_vars; v; v = v->next) {
  6794. if (!strcasecmp(v->name, "ajaxdest")) {
  6795. dest = v->value;
  6796. } else if (!strcasecmp(v->name, "ajaxobjtype")) {
  6797. objtype = v->value;
  6798. }
  6799. }
  6800. if (ast_strlen_zero(dest)) {
  6801. dest = "unknown";
  6802. }
  6803. if (ast_strlen_zero(objtype)) {
  6804. objtype = "generic";
  6805. }
  6806. }
  6807. /* we want to stop when we find an empty line */
  6808. while (in && *in) {
  6809. val = strsep(&in, "\r\n"); /* mark start and end of line */
  6810. if (in && *in == '\n') { /* remove trailing \n if any */
  6811. in++;
  6812. }
  6813. ast_trim_blanks(val);
  6814. ast_debug(5, "inobj %d in_data %d line <%s>\n", inobj, in_data, val);
  6815. if (ast_strlen_zero(val)) {
  6816. /* empty line */
  6817. if (in_data) {
  6818. /* close data in Opaque mode */
  6819. ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
  6820. in_data = 0;
  6821. }
  6822. if (inobj) {
  6823. /* close block */
  6824. ast_str_append(out, 0, xml ? " /></response>\n" :
  6825. "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
  6826. inobj = 0;
  6827. ao2_ref(vco, -1);
  6828. vco = NULL;
  6829. }
  6830. continue;
  6831. }
  6832. if (!inobj) {
  6833. /* start new block */
  6834. if (xml) {
  6835. ast_str_append(out, 0, "<response type='object' id='%s'><%s", dest, objtype);
  6836. }
  6837. vco = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 37,
  6838. variable_count_hash_fn, NULL, variable_count_cmp_fn);
  6839. inobj = 1;
  6840. }
  6841. if (in_data) {
  6842. /* Process data field in Opaque mode. This is a
  6843. * followup, so we re-add line feeds. */
  6844. ast_str_append(out, 0, xml ? "\n" : "<br>\n");
  6845. xml_copy_escape(out, val, 0); /* data field */
  6846. continue;
  6847. }
  6848. /* We expect "Name: value" line here */
  6849. var = strsep(&val, ":");
  6850. if (val) {
  6851. /* found the field name */
  6852. val = ast_skip_blanks(val);
  6853. ast_trim_blanks(var);
  6854. } else {
  6855. /* field name not found, switch to opaque mode */
  6856. val = var;
  6857. var = "Opaque-data";
  6858. in_data = 1;
  6859. }
  6860. ast_str_append(out, 0, xml ? " " : "<tr><td>");
  6861. if ((vc = ao2_find(vco, var, 0))) {
  6862. vc->count++;
  6863. } else {
  6864. /* Create a new entry for this one */
  6865. vc = ao2_alloc(sizeof(*vc), NULL);
  6866. vc->varname = var;
  6867. vc->count = 1;
  6868. ao2_link(vco, vc);
  6869. }
  6870. xml_copy_escape(out, var, xml ? 1 | 2 : 0); /* data name */
  6871. if (vc->count > 1) {
  6872. ast_str_append(out, 0, "-%d", vc->count);
  6873. }
  6874. ao2_ref(vc, -1);
  6875. ast_str_append(out, 0, xml ? "='" : "</td><td>");
  6876. xml_copy_escape(out, val, 0); /* data field */
  6877. if (!in_data || !*in) {
  6878. ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
  6879. }
  6880. }
  6881. if (inobj) {
  6882. ast_str_append(out, 0, xml ? " /></response>\n" :
  6883. "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
  6884. ao2_ref(vco, -1);
  6885. }
  6886. }
  6887. static void close_mansession_file(struct mansession *s)
  6888. {
  6889. if (s->f) {
  6890. if (fclose(s->f)) {
  6891. ast_log(LOG_ERROR, "fclose() failed: %s\n", strerror(errno));
  6892. }
  6893. s->f = NULL;
  6894. s->fd = -1;
  6895. } else if (s->fd != -1) {
  6896. /*
  6897. * Issuing shutdown() is necessary here to avoid a race
  6898. * condition where the last data written may not appear
  6899. * in the TCP stream. See ASTERISK-23548
  6900. */
  6901. shutdown(s->fd, SHUT_RDWR);
  6902. if (close(s->fd)) {
  6903. ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
  6904. }
  6905. s->fd = -1;
  6906. } else {
  6907. ast_log(LOG_ERROR, "Attempted to close file/file descriptor on mansession without a valid file or file descriptor.\n");
  6908. }
  6909. }
  6910. static void process_output(struct mansession *s, struct ast_str **out, struct ast_variable *params, enum output_format format)
  6911. {
  6912. char *buf;
  6913. size_t l;
  6914. if (!s->f)
  6915. return;
  6916. /* Ensure buffer is NULL-terminated */
  6917. fprintf(s->f, "%c", 0);
  6918. fflush(s->f);
  6919. if ((l = ftell(s->f)) > 0) {
  6920. if (MAP_FAILED == (buf = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_PRIVATE, s->fd, 0))) {
  6921. ast_log(LOG_WARNING, "mmap failed. Manager output was not processed\n");
  6922. } else {
  6923. if (format == FORMAT_XML || format == FORMAT_HTML) {
  6924. xml_translate(out, buf, params, format);
  6925. } else {
  6926. ast_str_append(out, 0, "%s", buf);
  6927. }
  6928. munmap(buf, l);
  6929. }
  6930. } else if (format == FORMAT_XML || format == FORMAT_HTML) {
  6931. xml_translate(out, "", params, format);
  6932. }
  6933. close_mansession_file(s);
  6934. }
  6935. static int generic_http_callback(struct ast_tcptls_session_instance *ser,
  6936. enum ast_http_method method,
  6937. enum output_format format,
  6938. const struct ast_sockaddr *remote_address, const char *uri,
  6939. struct ast_variable *get_params,
  6940. struct ast_variable *headers)
  6941. {
  6942. struct mansession s = { .session = NULL, .tcptls_session = ser };
  6943. struct mansession_session *session = NULL;
  6944. uint32_t ident;
  6945. int blastaway = 0;
  6946. struct ast_variable *params = get_params;
  6947. char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
  6948. struct ast_str *http_header = NULL, *out = NULL;
  6949. struct message m = { 0 };
  6950. if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
  6951. ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
  6952. return 0;
  6953. }
  6954. ident = ast_http_manid_from_vars(headers);
  6955. if (!(session = find_session(ident, 1))) {
  6956. /**/
  6957. /* Create new session.
  6958. * While it is not in the list we don't need any locking
  6959. */
  6960. if (!(session = build_mansession(remote_address))) {
  6961. ast_http_request_close_on_completion(ser);
  6962. ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
  6963. return 0;
  6964. }
  6965. ao2_lock(session);
  6966. session->send_events = 0;
  6967. session->inuse = 1;
  6968. /*!
  6969. * \note There is approximately a 1 in 1.8E19 chance that the following
  6970. * calculation will produce 0, which is an invalid ID, but due to the
  6971. * properties of the rand() function (and the constantcy of s), that
  6972. * won't happen twice in a row.
  6973. */
  6974. while ((session->managerid = ast_random() ^ (unsigned long) session) == 0) {
  6975. }
  6976. session->last_ev = grab_last();
  6977. AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
  6978. }
  6979. ao2_unlock(session);
  6980. http_header = ast_str_create(128);
  6981. out = ast_str_create(2048);
  6982. ast_mutex_init(&s.lock);
  6983. if (http_header == NULL || out == NULL) {
  6984. ast_http_request_close_on_completion(ser);
  6985. ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)");
  6986. goto generic_callback_out;
  6987. }
  6988. s.session = session;
  6989. s.fd = mkstemp(template); /* create a temporary file for command output */
  6990. unlink(template);
  6991. if (s.fd <= -1) {
  6992. ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)");
  6993. goto generic_callback_out;
  6994. }
  6995. s.f = fdopen(s.fd, "w+");
  6996. if (!s.f) {
  6997. ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
  6998. ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)");
  6999. close(s.fd);
  7000. goto generic_callback_out;
  7001. }
  7002. if (method == AST_HTTP_POST) {
  7003. params = ast_http_get_post_vars(ser, headers);
  7004. if (!params) {
  7005. switch (errno) {
  7006. case EFBIG:
  7007. ast_http_error(ser, 413, "Request Entity Too Large", "Body too large");
  7008. close_mansession_file(&s);
  7009. goto generic_callback_out;
  7010. case ENOMEM:
  7011. ast_http_request_close_on_completion(ser);
  7012. ast_http_error(ser, 500, "Server Error", "Out of memory");
  7013. close_mansession_file(&s);
  7014. goto generic_callback_out;
  7015. case EIO:
  7016. ast_http_error(ser, 400, "Bad Request", "Error parsing request body");
  7017. close_mansession_file(&s);
  7018. goto generic_callback_out;
  7019. }
  7020. }
  7021. }
  7022. astman_append_headers(&m, params);
  7023. if (process_message(&s, &m)) {
  7024. if (session->authenticated) {
  7025. if (manager_displayconnects(session)) {
  7026. ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
  7027. }
  7028. } else {
  7029. if (displayconnects) {
  7030. ast_verb(2, "HTTP Connect attempt from '%s' unable to authenticate\n", ast_sockaddr_stringify_addr(&session->addr));
  7031. }
  7032. }
  7033. session->needdestroy = 1;
  7034. }
  7035. astman_free_headers(&m);
  7036. ast_str_append(&http_header, 0,
  7037. "Content-type: text/%s\r\n"
  7038. "Set-Cookie: mansession_id=\"%08x\"; Version=1; Max-Age=%d\r\n"
  7039. "Pragma: SuppressEvents\r\n",
  7040. contenttype[format],
  7041. session->managerid, httptimeout);
  7042. if (format == FORMAT_XML) {
  7043. ast_str_append(&out, 0, "<ajax-response>\n");
  7044. } else if (format == FORMAT_HTML) {
  7045. /*
  7046. * When handling AMI-over-HTTP in HTML format, we provide a simple form for
  7047. * debugging purposes. This HTML code should not be here, we
  7048. * should read from some config file...
  7049. */
  7050. #define ROW_FMT "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"
  7051. #define TEST_STRING \
  7052. "<form action=\"manager\" method=\"post\">\n\
  7053. Action: <select name=\"action\">\n\
  7054. <option value=\"\">-----&gt;</option>\n\
  7055. <option value=\"login\">login</option>\n\
  7056. <option value=\"command\">Command</option>\n\
  7057. <option value=\"waitevent\">waitevent</option>\n\
  7058. <option value=\"listcommands\">listcommands</option>\n\
  7059. </select>\n\
  7060. or <input name=\"action\"><br/>\n\
  7061. CLI Command <input name=\"command\"><br>\n\
  7062. user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\
  7063. <input type=\"submit\">\n</form>\n"
  7064. ast_str_append(&out, 0, "<title>Asterisk&trade; Manager Interface</title>");
  7065. ast_str_append(&out, 0, "<body bgcolor=\"#ffffff\"><table align=center bgcolor=\"#f1f1f1\" width=\"500\">\r\n");
  7066. ast_str_append(&out, 0, ROW_FMT, "<h1>Manager Tester</h1>");
  7067. ast_str_append(&out, 0, ROW_FMT, TEST_STRING);
  7068. }
  7069. process_output(&s, &out, params, format);
  7070. if (format == FORMAT_XML) {
  7071. ast_str_append(&out, 0, "</ajax-response>\n");
  7072. } else if (format == FORMAT_HTML) {
  7073. ast_str_append(&out, 0, "</table></body>\r\n");
  7074. }
  7075. ao2_lock(session);
  7076. /* Reset HTTP timeout. If we're not authenticated, keep it extremely short */
  7077. session->sessiontimeout = time(NULL) + ((session->authenticated || httptimeout < 5) ? httptimeout : 5);
  7078. if (session->needdestroy) {
  7079. if (session->inuse == 1) {
  7080. ast_debug(1, "Need destroy, doing it now!\n");
  7081. blastaway = 1;
  7082. } else {
  7083. ast_debug(1, "Need destroy, but can't do it yet!\n");
  7084. if (session->waiting_thread != AST_PTHREADT_NULL) {
  7085. pthread_kill(session->waiting_thread, SIGURG);
  7086. }
  7087. session->inuse--;
  7088. }
  7089. } else {
  7090. session->inuse--;
  7091. }
  7092. ao2_unlock(session);
  7093. ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
  7094. http_header = NULL;
  7095. out = NULL;
  7096. generic_callback_out:
  7097. ast_mutex_destroy(&s.lock);
  7098. /* Clear resource */
  7099. if (method == AST_HTTP_POST && params) {
  7100. ast_variables_destroy(params);
  7101. }
  7102. ast_free(http_header);
  7103. ast_free(out);
  7104. if (session) {
  7105. if (blastaway) {
  7106. session_destroy(session);
  7107. } else {
  7108. if (session->f) {
  7109. fclose(session->f);
  7110. session->f = NULL;
  7111. }
  7112. unref_mansession(session);
  7113. }
  7114. }
  7115. return 0;
  7116. }
  7117. static int auth_http_callback(struct ast_tcptls_session_instance *ser,
  7118. enum ast_http_method method,
  7119. enum output_format format,
  7120. const struct ast_sockaddr *remote_address, const char *uri,
  7121. struct ast_variable *get_params,
  7122. struct ast_variable *headers)
  7123. {
  7124. struct mansession_session *session = NULL;
  7125. struct mansession s = { .session = NULL, .tcptls_session = ser };
  7126. struct ast_variable *v, *params = get_params;
  7127. char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
  7128. struct ast_str *http_header = NULL, *out = NULL;
  7129. size_t result_size;
  7130. struct message m = { 0 };
  7131. time_t time_now = time(NULL);
  7132. unsigned long nonce = 0, nc;
  7133. struct ast_http_digest d = { NULL, };
  7134. struct ast_manager_user *user = NULL;
  7135. int stale = 0;
  7136. char resp_hash[256]="";
  7137. /* Cache for user data */
  7138. char u_username[80];
  7139. int u_readperm;
  7140. int u_writeperm;
  7141. int u_writetimeout;
  7142. int u_displayconnects;
  7143. if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
  7144. ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
  7145. return 0;
  7146. }
  7147. /* Find "Authorization: " header */
  7148. for (v = headers; v; v = v->next) {
  7149. if (!strcasecmp(v->name, "Authorization")) {
  7150. break;
  7151. }
  7152. }
  7153. if (!v || ast_strlen_zero(v->value)) {
  7154. goto out_401; /* Authorization Header not present - send auth request */
  7155. }
  7156. /* Digest found - parse */
  7157. if (ast_string_field_init(&d, 128)) {
  7158. ast_http_request_close_on_completion(ser);
  7159. ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
  7160. return 0;
  7161. }
  7162. if (ast_parse_digest(v->value, &d, 0, 1)) {
  7163. /* Error in Digest - send new one */
  7164. nonce = 0;
  7165. goto out_401;
  7166. }
  7167. if (sscanf(d.nonce, "%30lx", &nonce) != 1) {
  7168. ast_log(LOG_WARNING, "Received incorrect nonce in Digest <%s>\n", d.nonce);
  7169. nonce = 0;
  7170. goto out_401;
  7171. }
  7172. AST_RWLIST_WRLOCK(&users);
  7173. user = get_manager_by_name_locked(d.username);
  7174. if(!user) {
  7175. AST_RWLIST_UNLOCK(&users);
  7176. ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&session->addr), d.username);
  7177. nonce = 0;
  7178. goto out_401;
  7179. }
  7180. /* --- We have User for this auth, now check ACL */
  7181. if (user->acl && !ast_apply_acl(user->acl, remote_address, "Manager User ACL:")) {
  7182. AST_RWLIST_UNLOCK(&users);
  7183. ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&session->addr), d.username);
  7184. ast_http_request_close_on_completion(ser);
  7185. ast_http_error(ser, 403, "Permission denied", "Permission denied");
  7186. return 0;
  7187. }
  7188. /* --- We have auth, so check it */
  7189. /* compute the expected response to compare with what we received */
  7190. {
  7191. char *a2;
  7192. /* ast_md5_hash outputs 32 characters plus NULL terminator. */
  7193. char a2_hash[33];
  7194. char resp[256];
  7195. /* XXX Now request method are hardcoded in A2 */
  7196. if (ast_asprintf(&a2, "%s:%s", ast_get_http_method(method), d.uri) < 0) {
  7197. AST_RWLIST_UNLOCK(&users);
  7198. ast_http_request_close_on_completion(ser);
  7199. ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
  7200. return 0;
  7201. }
  7202. ast_md5_hash(a2_hash, a2);
  7203. ast_free(a2);
  7204. if (d.qop) {
  7205. /* RFC 2617 */
  7206. snprintf(resp, sizeof(resp), "%s:%08lx:%s:%s:auth:%s", user->a1_hash, nonce, d.nc, d.cnonce, a2_hash);
  7207. } else {
  7208. /* RFC 2069 */
  7209. snprintf(resp, sizeof(resp), "%s:%08lx:%s", user->a1_hash, nonce, a2_hash);
  7210. }
  7211. ast_md5_hash(resp_hash, resp);
  7212. }
  7213. if (strncasecmp(d.response, resp_hash, strlen(resp_hash))) {
  7214. /* Something was wrong, so give the client to try with a new challenge */
  7215. AST_RWLIST_UNLOCK(&users);
  7216. nonce = 0;
  7217. goto out_401;
  7218. }
  7219. /*
  7220. * User are pass Digest authentication.
  7221. * Now, cache the user data and unlock user list.
  7222. */
  7223. ast_copy_string(u_username, user->username, sizeof(u_username));
  7224. u_readperm = user->readperm;
  7225. u_writeperm = user->writeperm;
  7226. u_displayconnects = user->displayconnects;
  7227. u_writetimeout = user->writetimeout;
  7228. AST_RWLIST_UNLOCK(&users);
  7229. if (!(session = find_session_by_nonce(d.username, nonce, &stale))) {
  7230. /*
  7231. * Create new session.
  7232. * While it is not in the list we don't need any locking
  7233. */
  7234. if (!(session = build_mansession(remote_address))) {
  7235. ast_http_request_close_on_completion(ser);
  7236. ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
  7237. return 0;
  7238. }
  7239. ao2_lock(session);
  7240. ast_copy_string(session->username, u_username, sizeof(session->username));
  7241. session->managerid = nonce;
  7242. session->last_ev = grab_last();
  7243. AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
  7244. session->readperm = u_readperm;
  7245. session->writeperm = u_writeperm;
  7246. session->writetimeout = u_writetimeout;
  7247. if (u_displayconnects) {
  7248. ast_verb(2, "HTTP Manager '%s' logged in from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
  7249. }
  7250. session->noncetime = session->sessionstart = time_now;
  7251. session->authenticated = 1;
  7252. } else if (stale) {
  7253. /*
  7254. * Session found, but nonce is stale.
  7255. *
  7256. * This could be because an old request (w/old nonce) arrived.
  7257. *
  7258. * This may be as the result of http proxy usage (separate delay or
  7259. * multipath) or in a situation where a page was refreshed too quickly
  7260. * (seen in Firefox).
  7261. *
  7262. * In this situation, we repeat the 401 auth with the current nonce
  7263. * value.
  7264. */
  7265. nonce = session->managerid;
  7266. ao2_unlock(session);
  7267. stale = 1;
  7268. goto out_401;
  7269. } else {
  7270. sscanf(d.nc, "%30lx", &nc);
  7271. if (session->nc >= nc || ((time_now - session->noncetime) > 62) ) {
  7272. /*
  7273. * Nonce time expired (> 2 minutes) or something wrong with nonce
  7274. * counter.
  7275. *
  7276. * Create new nonce key and resend Digest auth request. Old nonce
  7277. * is saved for stale checking...
  7278. */
  7279. session->nc = 0; /* Reset nonce counter */
  7280. session->oldnonce = session->managerid;
  7281. nonce = session->managerid = ast_random();
  7282. session->noncetime = time_now;
  7283. ao2_unlock(session);
  7284. stale = 1;
  7285. goto out_401;
  7286. } else {
  7287. session->nc = nc; /* All OK, save nonce counter */
  7288. }
  7289. }
  7290. /* Reset session timeout. */
  7291. session->sessiontimeout = time(NULL) + (httptimeout > 5 ? httptimeout : 5);
  7292. ao2_unlock(session);
  7293. ast_mutex_init(&s.lock);
  7294. s.session = session;
  7295. s.fd = mkstemp(template); /* create a temporary file for command output */
  7296. unlink(template);
  7297. if (s.fd <= -1) {
  7298. ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)");
  7299. goto auth_callback_out;
  7300. }
  7301. s.f = fdopen(s.fd, "w+");
  7302. if (!s.f) {
  7303. ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
  7304. ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)");
  7305. close(s.fd);
  7306. goto auth_callback_out;
  7307. }
  7308. if (method == AST_HTTP_POST) {
  7309. params = ast_http_get_post_vars(ser, headers);
  7310. if (!params) {
  7311. switch (errno) {
  7312. case EFBIG:
  7313. ast_http_error(ser, 413, "Request Entity Too Large", "Body too large");
  7314. close_mansession_file(&s);
  7315. goto auth_callback_out;
  7316. case ENOMEM:
  7317. ast_http_request_close_on_completion(ser);
  7318. ast_http_error(ser, 500, "Server Error", "Out of memory");
  7319. close_mansession_file(&s);
  7320. goto auth_callback_out;
  7321. case EIO:
  7322. ast_http_error(ser, 400, "Bad Request", "Error parsing request body");
  7323. close_mansession_file(&s);
  7324. goto auth_callback_out;
  7325. }
  7326. }
  7327. }
  7328. astman_append_headers(&m, params);
  7329. if (process_message(&s, &m)) {
  7330. if (u_displayconnects) {
  7331. ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
  7332. }
  7333. session->needdestroy = 1;
  7334. }
  7335. astman_free_headers(&m);
  7336. result_size = ftell(s.f); /* Calculate approx. size of result */
  7337. http_header = ast_str_create(80);
  7338. out = ast_str_create(result_size * 2 + 512);
  7339. if (http_header == NULL || out == NULL) {
  7340. ast_http_request_close_on_completion(ser);
  7341. ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)");
  7342. close_mansession_file(&s);
  7343. goto auth_callback_out;
  7344. }
  7345. ast_str_append(&http_header, 0, "Content-type: text/%s\r\n", contenttype[format]);
  7346. if (format == FORMAT_XML) {
  7347. ast_str_append(&out, 0, "<ajax-response>\n");
  7348. } else if (format == FORMAT_HTML) {
  7349. ast_str_append(&out, 0,
  7350. "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
  7351. "<html><head>\r\n"
  7352. "<title>Asterisk&trade; Manager Interface</title>\r\n"
  7353. "</head><body style=\"background-color: #ffffff;\">\r\n"
  7354. "<form method=\"POST\">\r\n"
  7355. "<table align=\"center\" style=\"background-color: #f1f1f1;\" width=\"500\">\r\n"
  7356. "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\"><h1>Manager Tester</h1></th></tr>\r\n"
  7357. "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\">Action: <input name=\"action\" /> Cmd: <input name=\"command\" /><br>"
  7358. "<input type=\"submit\" value=\"Send request\" /></th></tr>\r\n");
  7359. }
  7360. process_output(&s, &out, params, format);
  7361. if (format == FORMAT_XML) {
  7362. ast_str_append(&out, 0, "</ajax-response>\n");
  7363. } else if (format == FORMAT_HTML) {
  7364. ast_str_append(&out, 0, "</table></form></body></html>\r\n");
  7365. }
  7366. ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
  7367. http_header = NULL;
  7368. out = NULL;
  7369. auth_callback_out:
  7370. ast_mutex_destroy(&s.lock);
  7371. /* Clear resources and unlock manager session */
  7372. if (method == AST_HTTP_POST && params) {
  7373. ast_variables_destroy(params);
  7374. }
  7375. ast_free(http_header);
  7376. ast_free(out);
  7377. ao2_lock(session);
  7378. if (session->f) {
  7379. fclose(session->f);
  7380. }
  7381. session->f = NULL;
  7382. session->fd = -1;
  7383. ao2_unlock(session);
  7384. if (session->needdestroy) {
  7385. ast_debug(1, "Need destroy, doing it now!\n");
  7386. session_destroy(session);
  7387. }
  7388. ast_string_field_free_memory(&d);
  7389. return 0;
  7390. out_401:
  7391. if (!nonce) {
  7392. nonce = ast_random();
  7393. }
  7394. ast_http_auth(ser, global_realm, nonce, nonce, stale, NULL);
  7395. ast_string_field_free_memory(&d);
  7396. return 0;
  7397. }
  7398. static int manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
  7399. {
  7400. int retval;
  7401. struct ast_sockaddr ser_remote_address_tmp;
  7402. ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
  7403. retval = generic_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
  7404. ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
  7405. return retval;
  7406. }
  7407. static int mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
  7408. {
  7409. int retval;
  7410. struct ast_sockaddr ser_remote_address_tmp;
  7411. ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
  7412. retval = generic_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
  7413. ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
  7414. return retval;
  7415. }
  7416. static int rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
  7417. {
  7418. int retval;
  7419. struct ast_sockaddr ser_remote_address_tmp;
  7420. ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
  7421. retval = generic_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
  7422. ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
  7423. return retval;
  7424. }
  7425. static struct ast_http_uri rawmanuri = {
  7426. .description = "Raw HTTP Manager Event Interface",
  7427. .uri = "rawman",
  7428. .callback = rawman_http_callback,
  7429. .data = NULL,
  7430. .key = __FILE__,
  7431. };
  7432. static struct ast_http_uri manageruri = {
  7433. .description = "HTML Manager Event Interface",
  7434. .uri = "manager",
  7435. .callback = manager_http_callback,
  7436. .data = NULL,
  7437. .key = __FILE__,
  7438. };
  7439. static struct ast_http_uri managerxmluri = {
  7440. .description = "XML Manager Event Interface",
  7441. .uri = "mxml",
  7442. .callback = mxml_http_callback,
  7443. .data = NULL,
  7444. .key = __FILE__,
  7445. };
  7446. /* Callback with Digest authentication */
  7447. static int auth_manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
  7448. {
  7449. int retval;
  7450. struct ast_sockaddr ser_remote_address_tmp;
  7451. ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
  7452. retval = auth_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
  7453. ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
  7454. return retval;
  7455. }
  7456. static int auth_mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
  7457. {
  7458. int retval;
  7459. struct ast_sockaddr ser_remote_address_tmp;
  7460. ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
  7461. retval = auth_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
  7462. ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
  7463. return retval;
  7464. }
  7465. static int auth_rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
  7466. {
  7467. int retval;
  7468. struct ast_sockaddr ser_remote_address_tmp;
  7469. ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
  7470. retval = auth_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
  7471. ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
  7472. return retval;
  7473. }
  7474. static struct ast_http_uri arawmanuri = {
  7475. .description = "Raw HTTP Manager Event Interface w/Digest authentication",
  7476. .uri = "arawman",
  7477. .has_subtree = 0,
  7478. .callback = auth_rawman_http_callback,
  7479. .data = NULL,
  7480. .key = __FILE__,
  7481. };
  7482. static struct ast_http_uri amanageruri = {
  7483. .description = "HTML Manager Event Interface w/Digest authentication",
  7484. .uri = "amanager",
  7485. .has_subtree = 0,
  7486. .callback = auth_manager_http_callback,
  7487. .data = NULL,
  7488. .key = __FILE__,
  7489. };
  7490. static struct ast_http_uri amanagerxmluri = {
  7491. .description = "XML Manager Event Interface w/Digest authentication",
  7492. .uri = "amxml",
  7493. .has_subtree = 0,
  7494. .callback = auth_mxml_http_callback,
  7495. .data = NULL,
  7496. .key = __FILE__,
  7497. };
  7498. /*! \brief Get number of logged in sessions for a login name */
  7499. static int get_manager_sessions_cb(void *obj, void *arg, void *data, int flags)
  7500. {
  7501. struct mansession_session *session = obj;
  7502. const char *login = (char *)arg;
  7503. int *no_sessions = data;
  7504. if (strcasecmp(session->username, login) == 0) {
  7505. (*no_sessions)++;
  7506. }
  7507. return 0;
  7508. }
  7509. /*! \brief ${AMI_CLIENT()} Dialplan function - reads manager client data */
  7510. static int function_amiclient(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  7511. {
  7512. struct ast_manager_user *user = NULL;
  7513. AST_DECLARE_APP_ARGS(args,
  7514. AST_APP_ARG(name);
  7515. AST_APP_ARG(param);
  7516. );
  7517. if (ast_strlen_zero(data) ) {
  7518. ast_log(LOG_WARNING, "AMI_CLIENT() requires two arguments: AMI_CLIENT(<name>[,<arg>])\n");
  7519. return -1;
  7520. }
  7521. AST_STANDARD_APP_ARGS(args, data);
  7522. args.name = ast_strip(args.name);
  7523. args.param = ast_strip(args.param);
  7524. AST_RWLIST_RDLOCK(&users);
  7525. if (!(user = get_manager_by_name_locked(args.name))) {
  7526. AST_RWLIST_UNLOCK(&users);
  7527. ast_log(LOG_ERROR, "There's no manager user called : \"%s\"\n", args.name);
  7528. return -1;
  7529. }
  7530. AST_RWLIST_UNLOCK(&users);
  7531. if (!strcasecmp(args.param, "sessions")) {
  7532. int no_sessions = 0;
  7533. struct ao2_container *sessions;
  7534. sessions = ao2_global_obj_ref(mgr_sessions);
  7535. if (sessions) {
  7536. ao2_callback_data(sessions, 0, get_manager_sessions_cb, /*login name*/ data, &no_sessions);
  7537. ao2_ref(sessions, -1);
  7538. }
  7539. snprintf(buf, len, "%d", no_sessions);
  7540. } else {
  7541. ast_log(LOG_ERROR, "Invalid arguments provided to function AMI_CLIENT: %s\n", args.param);
  7542. return -1;
  7543. }
  7544. return 0;
  7545. }
  7546. /*! \brief description of AMI_CLIENT dialplan function */
  7547. static struct ast_custom_function managerclient_function = {
  7548. .name = "AMI_CLIENT",
  7549. .read = function_amiclient,
  7550. .read_max = 12,
  7551. };
  7552. static int webregged = 0;
  7553. /*! \brief cleanup code called at each iteration of server_root,
  7554. * guaranteed to happen every 5 seconds at most
  7555. */
  7556. static void purge_old_stuff(void *data)
  7557. {
  7558. purge_sessions(1);
  7559. purge_events();
  7560. }
  7561. static struct ast_tls_config ami_tls_cfg;
  7562. static struct ast_tcptls_session_args ami_desc = {
  7563. .accept_fd = -1,
  7564. .master = AST_PTHREADT_NULL,
  7565. .tls_cfg = NULL,
  7566. .poll_timeout = 5000, /* wake up every 5 seconds */
  7567. .periodic_fn = purge_old_stuff,
  7568. .name = "AMI server",
  7569. .accept_fn = ast_tcptls_server_root, /* thread doing the accept() */
  7570. .worker_fn = session_do, /* thread handling the session */
  7571. };
  7572. static struct ast_tcptls_session_args amis_desc = {
  7573. .accept_fd = -1,
  7574. .master = AST_PTHREADT_NULL,
  7575. .tls_cfg = &ami_tls_cfg,
  7576. .poll_timeout = -1, /* the other does the periodic cleanup */
  7577. .name = "AMI TLS server",
  7578. .accept_fn = ast_tcptls_server_root, /* thread doing the accept() */
  7579. .worker_fn = session_do, /* thread handling the session */
  7580. };
  7581. /*! \brief CLI command manager show settings */
  7582. static char *handle_manager_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  7583. {
  7584. switch (cmd) {
  7585. case CLI_INIT:
  7586. e->command = "manager show settings";
  7587. e->usage =
  7588. "Usage: manager show settings\n"
  7589. " Provides detailed list of the configuration of the Manager.\n";
  7590. return NULL;
  7591. case CLI_GENERATE:
  7592. return NULL;
  7593. }
  7594. #define FORMAT " %-25.25s %-15.55s\n"
  7595. #define FORMAT2 " %-25.25s %-15d\n"
  7596. if (a->argc != 3) {
  7597. return CLI_SHOWUSAGE;
  7598. }
  7599. ast_cli(a->fd, "\nGlobal Settings:\n");
  7600. ast_cli(a->fd, "----------------\n");
  7601. ast_cli(a->fd, FORMAT, "Manager (AMI):", AST_CLI_YESNO(manager_enabled));
  7602. ast_cli(a->fd, FORMAT, "Web Manager (AMI/HTTP):", AST_CLI_YESNO(webmanager_enabled));
  7603. ast_cli(a->fd, FORMAT, "TCP Bindaddress:", manager_enabled != 0 ? ast_sockaddr_stringify(&ami_desc.local_address) : "Disabled");
  7604. ast_cli(a->fd, FORMAT2, "HTTP Timeout (seconds):", httptimeout);
  7605. ast_cli(a->fd, FORMAT, "TLS Enable:", AST_CLI_YESNO(ami_tls_cfg.enabled));
  7606. ast_cli(a->fd, FORMAT, "TLS Bindaddress:", ami_tls_cfg.enabled != 0 ? ast_sockaddr_stringify(&amis_desc.local_address) : "Disabled");
  7607. ast_cli(a->fd, FORMAT, "TLS Certfile:", ami_tls_cfg.certfile);
  7608. ast_cli(a->fd, FORMAT, "TLS Privatekey:", ami_tls_cfg.pvtfile);
  7609. ast_cli(a->fd, FORMAT, "TLS Cipher:", ami_tls_cfg.cipher);
  7610. ast_cli(a->fd, FORMAT, "Allow multiple login:", AST_CLI_YESNO(allowmultiplelogin));
  7611. ast_cli(a->fd, FORMAT, "Display connects:", AST_CLI_YESNO(displayconnects));
  7612. ast_cli(a->fd, FORMAT, "Timestamp events:", AST_CLI_YESNO(timestampevents));
  7613. ast_cli(a->fd, FORMAT, "Channel vars:", S_OR(manager_channelvars, ""));
  7614. ast_cli(a->fd, FORMAT, "Debug:", AST_CLI_YESNO(manager_debug));
  7615. #undef FORMAT
  7616. #undef FORMAT2
  7617. return CLI_SUCCESS;
  7618. }
  7619. #ifdef AST_XML_DOCS
  7620. static int ast_xml_doc_item_cmp_fn(const void *a, const void *b)
  7621. {
  7622. struct ast_xml_doc_item **item_a = (struct ast_xml_doc_item **)a;
  7623. struct ast_xml_doc_item **item_b = (struct ast_xml_doc_item **)b;
  7624. return strcmp((*item_a)->name, (*item_b)->name);
  7625. }
  7626. static char *handle_manager_show_events(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  7627. {
  7628. struct ao2_container *events;
  7629. struct ao2_iterator *it_events;
  7630. struct ast_xml_doc_item *item;
  7631. struct ast_xml_doc_item **items;
  7632. struct ast_str *buffer;
  7633. int i = 0, totalitems = 0;
  7634. switch (cmd) {
  7635. case CLI_INIT:
  7636. e->command = "manager show events";
  7637. e->usage =
  7638. "Usage: manager show events\n"
  7639. " Prints a listing of the available Asterisk manager interface events.\n";
  7640. return NULL;
  7641. case CLI_GENERATE:
  7642. return NULL;
  7643. }
  7644. if (a->argc != 3) {
  7645. return CLI_SHOWUSAGE;
  7646. }
  7647. buffer = ast_str_create(128);
  7648. if (!buffer) {
  7649. return CLI_SUCCESS;
  7650. }
  7651. events = ao2_global_obj_ref(event_docs);
  7652. if (!events) {
  7653. ast_cli(a->fd, "No manager event documentation loaded\n");
  7654. ast_free(buffer);
  7655. return CLI_SUCCESS;
  7656. }
  7657. ao2_lock(events);
  7658. if (!(it_events = ao2_callback(events, OBJ_MULTIPLE | OBJ_NOLOCK, NULL, NULL))) {
  7659. ao2_unlock(events);
  7660. ast_log(AST_LOG_ERROR, "Unable to create iterator for events container\n");
  7661. ast_free(buffer);
  7662. ao2_ref(events, -1);
  7663. return CLI_SUCCESS;
  7664. }
  7665. if (!(items = ast_calloc(sizeof(struct ast_xml_doc_item *), ao2_container_count(events)))) {
  7666. ao2_unlock(events);
  7667. ast_log(AST_LOG_ERROR, "Unable to create temporary sorting array for events\n");
  7668. ao2_iterator_destroy(it_events);
  7669. ast_free(buffer);
  7670. ao2_ref(events, -1);
  7671. return CLI_SUCCESS;
  7672. }
  7673. ao2_unlock(events);
  7674. while ((item = ao2_iterator_next(it_events))) {
  7675. items[totalitems++] = item;
  7676. ao2_ref(item, -1);
  7677. }
  7678. qsort(items, totalitems, sizeof(struct ast_xml_doc_item *), ast_xml_doc_item_cmp_fn);
  7679. ast_cli(a->fd, "Events:\n");
  7680. ast_cli(a->fd, " -------------------- -------------------- -------------------- \n");
  7681. for (i = 0; i < totalitems; i++) {
  7682. ast_str_append(&buffer, 0, " %-20.20s", items[i]->name);
  7683. if ((i + 1) % 3 == 0) {
  7684. ast_cli(a->fd, "%s\n", ast_str_buffer(buffer));
  7685. ast_str_set(&buffer, 0, "%s", "");
  7686. }
  7687. }
  7688. if ((i + 1) % 3 != 0) {
  7689. ast_cli(a->fd, "%s\n", ast_str_buffer(buffer));
  7690. }
  7691. ao2_iterator_destroy(it_events);
  7692. ast_free(items);
  7693. ao2_ref(events, -1);
  7694. ast_free(buffer);
  7695. return CLI_SUCCESS;
  7696. }
  7697. static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance)
  7698. {
  7699. char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64];
  7700. term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
  7701. term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
  7702. term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
  7703. term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
  7704. term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
  7705. if (!ast_strlen_zero(ast_str_buffer(instance->synopsis))) {
  7706. char *synopsis = ast_xmldoc_printable(ast_str_buffer(instance->synopsis), 1);
  7707. ast_cli(a->fd, "%s%s\n\n", synopsis_title, synopsis);
  7708. ast_free(synopsis);
  7709. }
  7710. if (!ast_strlen_zero(ast_str_buffer(instance->syntax))) {
  7711. char *syntax = ast_xmldoc_printable(ast_str_buffer(instance->syntax), 1);
  7712. ast_cli(a->fd, "%s%s\n\n", syntax_title, syntax);
  7713. ast_free(syntax);
  7714. }
  7715. if (!ast_strlen_zero(ast_str_buffer(instance->description))) {
  7716. char *description = ast_xmldoc_printable(ast_str_buffer(instance->description), 1);
  7717. ast_cli(a->fd, "%s%s\n\n", description_title, description);
  7718. ast_free(description);
  7719. }
  7720. if (!ast_strlen_zero(ast_str_buffer(instance->arguments))) {
  7721. char *arguments = ast_xmldoc_printable(ast_str_buffer(instance->arguments), 1);
  7722. ast_cli(a->fd, "%s%s\n\n", arguments_title, arguments);
  7723. ast_free(arguments);
  7724. }
  7725. if (!ast_strlen_zero(ast_str_buffer(instance->seealso))) {
  7726. char *seealso = ast_xmldoc_printable(ast_str_buffer(instance->seealso), 1);
  7727. ast_cli(a->fd, "%s%s\n\n", seealso_title, seealso);
  7728. ast_free(seealso);
  7729. }
  7730. }
  7731. static char *handle_manager_show_event(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  7732. {
  7733. RAII_VAR(struct ao2_container *, events, NULL, ao2_cleanup);
  7734. struct ao2_iterator it_events;
  7735. struct ast_xml_doc_item *item, *temp;
  7736. int length;
  7737. if (cmd == CLI_INIT) {
  7738. e->command = "manager show event";
  7739. e->usage =
  7740. "Usage: manager show event <eventname>\n"
  7741. " Provides a detailed description a Manager interface event.\n";
  7742. return NULL;
  7743. }
  7744. events = ao2_global_obj_ref(event_docs);
  7745. if (!events) {
  7746. ast_cli(a->fd, "No manager event documentation loaded\n");
  7747. return CLI_SUCCESS;
  7748. }
  7749. if (cmd == CLI_GENERATE) {
  7750. if (a->pos != 3) {
  7751. return NULL;
  7752. }
  7753. length = strlen(a->word);
  7754. it_events = ao2_iterator_init(events, 0);
  7755. while ((item = ao2_iterator_next(&it_events))) {
  7756. if (!strncasecmp(a->word, item->name, length)) {
  7757. if (ast_cli_completion_add(ast_strdup(item->name))) {
  7758. ao2_ref(item, -1);
  7759. break;
  7760. }
  7761. }
  7762. ao2_ref(item, -1);
  7763. }
  7764. ao2_iterator_destroy(&it_events);
  7765. return NULL;
  7766. }
  7767. if (a->argc != 4) {
  7768. return CLI_SHOWUSAGE;
  7769. }
  7770. if (!(item = ao2_find(events, a->argv[3], OBJ_KEY))) {
  7771. ast_cli(a->fd, "Could not find event '%s'\n", a->argv[3]);
  7772. return CLI_SUCCESS;
  7773. }
  7774. ast_cli(a->fd, "Event: %s\n", a->argv[3]);
  7775. for (temp = item; temp; temp = AST_LIST_NEXT(temp, next)) {
  7776. print_event_instance(a, temp);
  7777. }
  7778. ao2_ref(item, -1);
  7779. return CLI_SUCCESS;
  7780. }
  7781. #endif
  7782. static struct ast_cli_entry cli_manager[] = {
  7783. AST_CLI_DEFINE(handle_showmancmd, "Show a manager interface command"),
  7784. AST_CLI_DEFINE(handle_showmancmds, "List manager interface commands"),
  7785. AST_CLI_DEFINE(handle_showmanconn, "List connected manager interface users"),
  7786. AST_CLI_DEFINE(handle_showmaneventq, "List manager interface queued events"),
  7787. AST_CLI_DEFINE(handle_showmanagers, "List configured manager users"),
  7788. AST_CLI_DEFINE(handle_showmanager, "Display information on a specific manager user"),
  7789. AST_CLI_DEFINE(handle_mandebug, "Show, enable, disable debugging of the manager code"),
  7790. AST_CLI_DEFINE(handle_manager_reload, "Reload manager configurations"),
  7791. AST_CLI_DEFINE(handle_manager_show_settings, "Show manager global settings"),
  7792. #ifdef AST_XML_DOCS
  7793. AST_CLI_DEFINE(handle_manager_show_events, "List manager interface events"),
  7794. AST_CLI_DEFINE(handle_manager_show_event, "Show a manager interface event"),
  7795. #endif
  7796. };
  7797. /*!
  7798. * \internal
  7799. * \brief Load the config channelvars variable.
  7800. *
  7801. * \param var Config variable to load.
  7802. *
  7803. * \return Nothing
  7804. */
  7805. static void load_channelvars(struct ast_variable *var)
  7806. {
  7807. char *parse = NULL;
  7808. AST_DECLARE_APP_ARGS(args,
  7809. AST_APP_ARG(vars)[MAX_VARS];
  7810. );
  7811. ast_free(manager_channelvars);
  7812. manager_channelvars = ast_strdup(var->value);
  7813. /* parse the setting */
  7814. parse = ast_strdupa(manager_channelvars);
  7815. AST_STANDARD_APP_ARGS(args, parse);
  7816. ast_channel_set_manager_vars(args.argc, args.vars);
  7817. }
  7818. /*!
  7819. * \internal
  7820. * \brief Free a user record. Should already be removed from the list
  7821. */
  7822. static void manager_free_user(struct ast_manager_user *user)
  7823. {
  7824. ast_free(user->a1_hash);
  7825. ast_free(user->secret);
  7826. if (user->whitefilters) {
  7827. ao2_t_ref(user->whitefilters, -1, "decrement ref for white container, should be last one");
  7828. }
  7829. if (user->blackfilters) {
  7830. ao2_t_ref(user->blackfilters, -1, "decrement ref for black container, should be last one");
  7831. }
  7832. user->acl = ast_free_acl_list(user->acl);
  7833. ast_variables_destroy(user->chanvars);
  7834. ast_free(user);
  7835. }
  7836. /*!
  7837. * \internal
  7838. * \brief Clean up resources on Asterisk shutdown
  7839. */
  7840. static void manager_shutdown(void)
  7841. {
  7842. struct ast_manager_user *user;
  7843. /* This event is not actually transmitted, but causes all TCP sessions to be closed */
  7844. manager_event(EVENT_FLAG_SHUTDOWN, "CloseSession", "CloseSession: true\r\n");
  7845. ast_manager_unregister("Ping");
  7846. ast_manager_unregister("Events");
  7847. ast_manager_unregister("Logoff");
  7848. ast_manager_unregister("Login");
  7849. ast_manager_unregister("Challenge");
  7850. ast_manager_unregister("Hangup");
  7851. ast_manager_unregister("Status");
  7852. ast_manager_unregister("Setvar");
  7853. ast_manager_unregister("Getvar");
  7854. ast_manager_unregister("GetConfig");
  7855. ast_manager_unregister("GetConfigJSON");
  7856. ast_manager_unregister("UpdateConfig");
  7857. ast_manager_unregister("CreateConfig");
  7858. ast_manager_unregister("ListCategories");
  7859. ast_manager_unregister("Redirect");
  7860. ast_manager_unregister("Atxfer");
  7861. ast_manager_unregister("CancelAtxfer");
  7862. ast_manager_unregister("Originate");
  7863. ast_manager_unregister("Command");
  7864. ast_manager_unregister("ExtensionState");
  7865. ast_manager_unregister("PresenceState");
  7866. ast_manager_unregister("AbsoluteTimeout");
  7867. ast_manager_unregister("MailboxStatus");
  7868. ast_manager_unregister("MailboxCount");
  7869. ast_manager_unregister("ListCommands");
  7870. ast_manager_unregister("SendText");
  7871. ast_manager_unregister("UserEvent");
  7872. ast_manager_unregister("WaitEvent");
  7873. ast_manager_unregister("CoreSettings");
  7874. ast_manager_unregister("CoreStatus");
  7875. ast_manager_unregister("Reload");
  7876. ast_manager_unregister("LoggerRotate");
  7877. ast_manager_unregister("CoreShowChannels");
  7878. ast_manager_unregister("ModuleLoad");
  7879. ast_manager_unregister("ModuleCheck");
  7880. ast_manager_unregister("AOCMessage");
  7881. ast_manager_unregister("Filter");
  7882. ast_manager_unregister("BlindTransfer");
  7883. ast_custom_function_unregister(&managerclient_function);
  7884. ast_cli_unregister_multiple(cli_manager, ARRAY_LEN(cli_manager));
  7885. #ifdef AST_XML_DOCS
  7886. ao2_t_global_obj_release(event_docs, "Dispose of event_docs");
  7887. #endif
  7888. #ifdef TEST_FRAMEWORK
  7889. stasis_forward_cancel(test_suite_forwarder);
  7890. test_suite_forwarder = NULL;
  7891. #endif
  7892. if (stasis_router) {
  7893. stasis_message_router_unsubscribe_and_join(stasis_router);
  7894. stasis_router = NULL;
  7895. }
  7896. stasis_forward_cancel(rtp_topic_forwarder);
  7897. rtp_topic_forwarder = NULL;
  7898. stasis_forward_cancel(security_topic_forwarder);
  7899. security_topic_forwarder = NULL;
  7900. ao2_cleanup(manager_topic);
  7901. manager_topic = NULL;
  7902. STASIS_MESSAGE_TYPE_CLEANUP(ast_manager_get_generic_type);
  7903. ast_tcptls_server_stop(&ami_desc);
  7904. ast_tcptls_server_stop(&amis_desc);
  7905. ast_free(ami_tls_cfg.certfile);
  7906. ami_tls_cfg.certfile = NULL;
  7907. ast_free(ami_tls_cfg.pvtfile);
  7908. ami_tls_cfg.pvtfile = NULL;
  7909. ast_free(ami_tls_cfg.cipher);
  7910. ami_tls_cfg.cipher = NULL;
  7911. ast_free(ami_tls_cfg.cafile);
  7912. ami_tls_cfg.cafile = NULL;
  7913. ast_free(ami_tls_cfg.capath);
  7914. ami_tls_cfg.capath = NULL;
  7915. ao2_global_obj_release(mgr_sessions);
  7916. while ((user = AST_LIST_REMOVE_HEAD(&users, list))) {
  7917. manager_free_user(user);
  7918. }
  7919. acl_change_stasis_unsubscribe();
  7920. ast_free(manager_channelvars);
  7921. }
  7922. /*! \brief Initialize all \ref stasis topics and routers used by the various
  7923. * sub-components of AMI
  7924. */
  7925. static int manager_subscriptions_init(void)
  7926. {
  7927. int res = 0;
  7928. rtp_topic_forwarder = stasis_forward_all(ast_rtp_topic(), manager_topic);
  7929. if (!rtp_topic_forwarder) {
  7930. return -1;
  7931. }
  7932. security_topic_forwarder = stasis_forward_all(ast_security_topic(), manager_topic);
  7933. if (!security_topic_forwarder) {
  7934. return -1;
  7935. }
  7936. stasis_router = stasis_message_router_create(manager_topic);
  7937. if (!stasis_router) {
  7938. return -1;
  7939. }
  7940. stasis_message_router_set_congestion_limits(stasis_router, -1,
  7941. 6 * AST_TASKPROCESSOR_HIGH_WATER_LEVEL);
  7942. stasis_message_router_set_formatters_default(stasis_router,
  7943. manager_default_msg_cb, NULL, STASIS_SUBSCRIPTION_FORMATTER_AMI);
  7944. res |= stasis_message_router_add(stasis_router,
  7945. ast_manager_get_generic_type(), manager_generic_msg_cb, NULL);
  7946. if (res != 0) {
  7947. return -1;
  7948. }
  7949. return 0;
  7950. }
  7951. static int subscribe_all(void)
  7952. {
  7953. if (manager_subscriptions_init()) {
  7954. ast_log(AST_LOG_ERROR, "Failed to initialize manager subscriptions\n");
  7955. return -1;
  7956. }
  7957. if (manager_system_init()) {
  7958. ast_log(AST_LOG_ERROR, "Failed to initialize manager system handling\n");
  7959. return -1;
  7960. }
  7961. if (manager_channels_init()) {
  7962. ast_log(AST_LOG_ERROR, "Failed to initialize manager channel handling\n");
  7963. return -1;
  7964. }
  7965. if (manager_mwi_init()) {
  7966. ast_log(AST_LOG_ERROR, "Failed to initialize manager MWI handling\n");
  7967. return -1;
  7968. }
  7969. if (manager_bridging_init()) {
  7970. return -1;
  7971. }
  7972. if (manager_endpoints_init()) {
  7973. ast_log(AST_LOG_ERROR, "Failed to initialize manager endpoints handling\n");
  7974. return -1;
  7975. }
  7976. subscribed = 1;
  7977. return 0;
  7978. }
  7979. static void manager_set_defaults(void)
  7980. {
  7981. manager_enabled = 0;
  7982. displayconnects = 1;
  7983. broken_events_action = 0;
  7984. authtimeout = 30;
  7985. authlimit = 50;
  7986. manager_debug = 0; /* Debug disabled by default */
  7987. /* default values */
  7988. ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM),
  7989. sizeof(global_realm));
  7990. ast_sockaddr_setnull(&ami_desc.local_address);
  7991. ast_sockaddr_setnull(&amis_desc.local_address);
  7992. ami_tls_cfg.enabled = 0;
  7993. ast_free(ami_tls_cfg.certfile);
  7994. ami_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
  7995. ast_free(ami_tls_cfg.pvtfile);
  7996. ami_tls_cfg.pvtfile = ast_strdup("");
  7997. ast_free(ami_tls_cfg.cipher);
  7998. ami_tls_cfg.cipher = ast_strdup("");
  7999. ast_free(ami_tls_cfg.cafile);
  8000. ami_tls_cfg.cafile = ast_strdup("");
  8001. ast_free(ami_tls_cfg.capath);
  8002. ami_tls_cfg.capath = ast_strdup("");
  8003. }
  8004. static int __init_manager(int reload, int by_external_config)
  8005. {
  8006. struct ast_config *ucfg = NULL, *cfg = NULL;
  8007. const char *val;
  8008. char *cat = NULL;
  8009. int newhttptimeout = 60;
  8010. struct ast_manager_user *user = NULL;
  8011. struct ast_variable *var;
  8012. struct ast_flags config_flags = { (reload && !by_external_config) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  8013. char a1[256];
  8014. char a1_hash[256];
  8015. struct ast_sockaddr ami_desc_local_address_tmp;
  8016. struct ast_sockaddr amis_desc_local_address_tmp;
  8017. int tls_was_enabled = 0;
  8018. int acl_subscription_flag = 0;
  8019. if (!reload) {
  8020. struct ao2_container *sessions;
  8021. #ifdef AST_XML_DOCS
  8022. struct ao2_container *temp_event_docs;
  8023. #endif
  8024. int res;
  8025. ast_register_cleanup(manager_shutdown);
  8026. res = STASIS_MESSAGE_TYPE_INIT(ast_manager_get_generic_type);
  8027. if (res != 0) {
  8028. return -1;
  8029. }
  8030. manager_topic = stasis_topic_create("manager_topic");
  8031. if (!manager_topic) {
  8032. return -1;
  8033. }
  8034. /* Register default actions */
  8035. ast_manager_register_xml_core("Ping", 0, action_ping);
  8036. ast_manager_register_xml_core("Events", 0, action_events);
  8037. ast_manager_register_xml_core("Logoff", 0, action_logoff);
  8038. ast_manager_register_xml_core("Login", 0, action_login);
  8039. ast_manager_register_xml_core("Challenge", 0, action_challenge);
  8040. ast_manager_register_xml_core("Hangup", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_hangup);
  8041. ast_manager_register_xml_core("Status", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_status);
  8042. ast_manager_register_xml_core("Setvar", EVENT_FLAG_CALL, action_setvar);
  8043. ast_manager_register_xml_core("Getvar", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_getvar);
  8044. ast_manager_register_xml_core("GetConfig", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfig);
  8045. ast_manager_register_xml_core("GetConfigJSON", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfigjson);
  8046. ast_manager_register_xml_core("UpdateConfig", EVENT_FLAG_CONFIG, action_updateconfig);
  8047. ast_manager_register_xml_core("CreateConfig", EVENT_FLAG_CONFIG, action_createconfig);
  8048. ast_manager_register_xml_core("ListCategories", EVENT_FLAG_CONFIG, action_listcategories);
  8049. ast_manager_register_xml_core("Redirect", EVENT_FLAG_CALL, action_redirect);
  8050. ast_manager_register_xml_core("Atxfer", EVENT_FLAG_CALL, action_atxfer);
  8051. ast_manager_register_xml_core("CancelAtxfer", EVENT_FLAG_CALL, action_cancel_atxfer);
  8052. ast_manager_register_xml_core("Originate", EVENT_FLAG_ORIGINATE, action_originate);
  8053. ast_manager_register_xml_core("Command", EVENT_FLAG_COMMAND, action_command);
  8054. ast_manager_register_xml_core("ExtensionState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_extensionstate);
  8055. ast_manager_register_xml_core("PresenceState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_presencestate);
  8056. ast_manager_register_xml_core("AbsoluteTimeout", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_timeout);
  8057. ast_manager_register_xml_core("MailboxStatus", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxstatus);
  8058. ast_manager_register_xml_core("MailboxCount", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxcount);
  8059. ast_manager_register_xml_core("ListCommands", 0, action_listcommands);
  8060. ast_manager_register_xml_core("SendText", EVENT_FLAG_CALL, action_sendtext);
  8061. ast_manager_register_xml_core("UserEvent", EVENT_FLAG_USER, action_userevent);
  8062. ast_manager_register_xml_core("WaitEvent", 0, action_waitevent);
  8063. ast_manager_register_xml_core("CoreSettings", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coresettings);
  8064. ast_manager_register_xml_core("CoreStatus", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_corestatus);
  8065. ast_manager_register_xml_core("Reload", EVENT_FLAG_CONFIG | EVENT_FLAG_SYSTEM, action_reload);
  8066. ast_manager_register_xml_core("LoggerRotate", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_loggerrotate);
  8067. ast_manager_register_xml_core("CoreShowChannels", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coreshowchannels);
  8068. ast_manager_register_xml_core("ModuleLoad", EVENT_FLAG_SYSTEM, manager_moduleload);
  8069. ast_manager_register_xml_core("ModuleCheck", EVENT_FLAG_SYSTEM, manager_modulecheck);
  8070. ast_manager_register_xml_core("AOCMessage", EVENT_FLAG_AOC, action_aocmessage);
  8071. ast_manager_register_xml_core("Filter", EVENT_FLAG_SYSTEM, action_filter);
  8072. ast_manager_register_xml_core("BlindTransfer", EVENT_FLAG_CALL, action_blind_transfer);
  8073. #ifdef TEST_FRAMEWORK
  8074. test_suite_forwarder = stasis_forward_all(ast_test_suite_topic(), manager_topic);
  8075. #endif
  8076. ast_cli_register_multiple(cli_manager, ARRAY_LEN(cli_manager));
  8077. __ast_custom_function_register(&managerclient_function, NULL);
  8078. ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
  8079. /* Append placeholder event so master_eventq never runs dry */
  8080. if (append_event("Event: Placeholder\r\n\r\n", 0)) {
  8081. return -1;
  8082. }
  8083. #ifdef AST_XML_DOCS
  8084. temp_event_docs = ast_xmldoc_build_documentation("managerEvent");
  8085. if (temp_event_docs) {
  8086. ao2_t_global_obj_replace_unref(event_docs, temp_event_docs, "Toss old event docs");
  8087. ao2_t_ref(temp_event_docs, -1, "Remove creation ref - container holds only ref now");
  8088. }
  8089. #endif
  8090. /* If you have a NULL hash fn, you only need a single bucket */
  8091. sessions = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, mansession_cmp_fn);
  8092. if (!sessions) {
  8093. return -1;
  8094. }
  8095. ao2_global_obj_replace_unref(mgr_sessions, sessions);
  8096. ao2_ref(sessions, -1);
  8097. /* Initialize all settings before first configuration load. */
  8098. manager_set_defaults();
  8099. }
  8100. cfg = ast_config_load2("manager.conf", "manager", config_flags);
  8101. if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  8102. return 0;
  8103. } else if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
  8104. ast_log(LOG_NOTICE, "Unable to open AMI configuration manager.conf, or configuration is invalid.\n");
  8105. return 0;
  8106. }
  8107. /* If this wasn't performed due to a forced reload (because those can be created by ACL change events, we need to unsubscribe to ACL change events. */
  8108. if (!by_external_config) {
  8109. acl_change_stasis_unsubscribe();
  8110. }
  8111. if (reload) {
  8112. /* Reset all settings before reloading configuration */
  8113. tls_was_enabled = ami_tls_cfg.enabled;
  8114. manager_set_defaults();
  8115. }
  8116. ast_sockaddr_parse(&ami_desc_local_address_tmp, "[::]", 0);
  8117. ast_sockaddr_set_port(&ami_desc_local_address_tmp, DEFAULT_MANAGER_PORT);
  8118. for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
  8119. val = var->value;
  8120. /* read tls config options while preventing unsupported options from being set */
  8121. if (strcasecmp(var->name, "tlscafile")
  8122. && strcasecmp(var->name, "tlscapath")
  8123. && strcasecmp(var->name, "tlscadir")
  8124. && strcasecmp(var->name, "tlsverifyclient")
  8125. && strcasecmp(var->name, "tlsdontverifyserver")
  8126. && strcasecmp(var->name, "tlsclientmethod")
  8127. && strcasecmp(var->name, "sslclientmethod")
  8128. && !ast_tls_read_conf(&ami_tls_cfg, &amis_desc, var->name, val)) {
  8129. continue;
  8130. }
  8131. if (!strcasecmp(var->name, "enabled")) {
  8132. manager_enabled = ast_true(val);
  8133. } else if (!strcasecmp(var->name, "webenabled")) {
  8134. webmanager_enabled = ast_true(val);
  8135. } else if (!strcasecmp(var->name, "port")) {
  8136. int bindport;
  8137. if (ast_parse_arg(val, PARSE_UINT32|PARSE_IN_RANGE, &bindport, 1024, 65535)) {
  8138. ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
  8139. }
  8140. ast_sockaddr_set_port(&ami_desc_local_address_tmp, bindport);
  8141. } else if (!strcasecmp(var->name, "bindaddr")) {
  8142. /* remember port if it has already been set */
  8143. int setport = ast_sockaddr_port(&ami_desc_local_address_tmp);
  8144. if (ast_parse_arg(val, PARSE_ADDR|PARSE_PORT_IGNORE, NULL)) {
  8145. ast_log(LOG_WARNING, "Invalid address '%s' specified, default '%s' will be used\n", val,
  8146. ast_sockaddr_stringify_addr(&ami_desc_local_address_tmp));
  8147. } else {
  8148. ast_sockaddr_parse(&ami_desc_local_address_tmp, val, PARSE_PORT_IGNORE);
  8149. }
  8150. if (setport) {
  8151. ast_sockaddr_set_port(&ami_desc_local_address_tmp, setport);
  8152. }
  8153. } else if (!strcasecmp(var->name, "brokeneventsaction")) {
  8154. broken_events_action = ast_true(val);
  8155. } else if (!strcasecmp(var->name, "allowmultiplelogin")) {
  8156. allowmultiplelogin = ast_true(val);
  8157. } else if (!strcasecmp(var->name, "displayconnects")) {
  8158. displayconnects = ast_true(val);
  8159. } else if (!strcasecmp(var->name, "timestampevents")) {
  8160. timestampevents = ast_true(val);
  8161. } else if (!strcasecmp(var->name, "debug")) {
  8162. manager_debug = ast_true(val);
  8163. } else if (!strcasecmp(var->name, "httptimeout")) {
  8164. newhttptimeout = atoi(val);
  8165. } else if (!strcasecmp(var->name, "authtimeout")) {
  8166. int timeout = atoi(var->value);
  8167. if (timeout < 1) {
  8168. ast_log(LOG_WARNING, "Invalid authtimeout value '%s', using default value\n", var->value);
  8169. } else {
  8170. authtimeout = timeout;
  8171. }
  8172. } else if (!strcasecmp(var->name, "authlimit")) {
  8173. int limit = atoi(var->value);
  8174. if (limit < 1) {
  8175. ast_log(LOG_WARNING, "Invalid authlimit value '%s', using default value\n", var->value);
  8176. } else {
  8177. authlimit = limit;
  8178. }
  8179. } else if (!strcasecmp(var->name, "channelvars")) {
  8180. load_channelvars(var);
  8181. } else {
  8182. ast_log(LOG_NOTICE, "Invalid keyword <%s> = <%s> in manager.conf [general]\n",
  8183. var->name, val);
  8184. }
  8185. }
  8186. if (manager_enabled && !subscribed) {
  8187. if (subscribe_all() != 0) {
  8188. ast_log(LOG_ERROR, "Manager subscription error\n");
  8189. return -1;
  8190. }
  8191. }
  8192. ast_sockaddr_copy(&amis_desc_local_address_tmp, &amis_desc.local_address);
  8193. /* if the amis address has not been set, default is the same as non secure ami */
  8194. if (ast_sockaddr_isnull(&amis_desc_local_address_tmp)) {
  8195. ast_sockaddr_copy(&amis_desc_local_address_tmp, &ami_desc_local_address_tmp);
  8196. }
  8197. /* if the amis address was not set, it will have non-secure ami port set; if
  8198. amis address was set, we need to check that a port was set or not, if not
  8199. use the default tls port */
  8200. if (ast_sockaddr_port(&amis_desc_local_address_tmp) == 0 ||
  8201. (ast_sockaddr_port(&ami_desc_local_address_tmp) == ast_sockaddr_port(&amis_desc_local_address_tmp))) {
  8202. ast_sockaddr_set_port(&amis_desc_local_address_tmp, DEFAULT_MANAGER_TLS_PORT);
  8203. }
  8204. if (manager_enabled) {
  8205. ast_sockaddr_copy(&ami_desc.local_address, &ami_desc_local_address_tmp);
  8206. ast_sockaddr_copy(&amis_desc.local_address, &amis_desc_local_address_tmp);
  8207. }
  8208. AST_RWLIST_WRLOCK(&users);
  8209. /* First, get users from users.conf */
  8210. ucfg = ast_config_load2("users.conf", "manager", config_flags);
  8211. if (ucfg && (ucfg != CONFIG_STATUS_FILEUNCHANGED) && ucfg != CONFIG_STATUS_FILEINVALID) {
  8212. const char *hasmanager;
  8213. int genhasmanager = ast_true(ast_variable_retrieve(ucfg, "general", "hasmanager"));
  8214. while ((cat = ast_category_browse(ucfg, cat))) {
  8215. if (!strcasecmp(cat, "general")) {
  8216. continue;
  8217. }
  8218. hasmanager = ast_variable_retrieve(ucfg, cat, "hasmanager");
  8219. if ((!hasmanager && genhasmanager) || ast_true(hasmanager)) {
  8220. const char *user_secret = ast_variable_retrieve(ucfg, cat, "secret");
  8221. const char *user_read = ast_variable_retrieve(ucfg, cat, "read");
  8222. const char *user_write = ast_variable_retrieve(ucfg, cat, "write");
  8223. const char *user_displayconnects = ast_variable_retrieve(ucfg, cat, "displayconnects");
  8224. const char *user_allowmultiplelogin = ast_variable_retrieve(ucfg, cat, "allowmultiplelogin");
  8225. const char *user_writetimeout = ast_variable_retrieve(ucfg, cat, "writetimeout");
  8226. /* Look for an existing entry,
  8227. * if none found - create one and add it to the list
  8228. */
  8229. if (!(user = get_manager_by_name_locked(cat))) {
  8230. if (!(user = ast_calloc(1, sizeof(*user)))) {
  8231. break;
  8232. }
  8233. /* Copy name over */
  8234. ast_copy_string(user->username, cat, sizeof(user->username));
  8235. /* Insert into list */
  8236. AST_LIST_INSERT_TAIL(&users, user, list);
  8237. user->acl = NULL;
  8238. user->keep = 1;
  8239. user->readperm = -1;
  8240. user->writeperm = -1;
  8241. /* Default displayconnect from [general] */
  8242. user->displayconnects = displayconnects;
  8243. /* Default allowmultiplelogin from [general] */
  8244. user->allowmultiplelogin = allowmultiplelogin;
  8245. user->writetimeout = 100;
  8246. }
  8247. if (!user_secret) {
  8248. user_secret = ast_variable_retrieve(ucfg, "general", "secret");
  8249. }
  8250. if (!user_read) {
  8251. user_read = ast_variable_retrieve(ucfg, "general", "read");
  8252. }
  8253. if (!user_write) {
  8254. user_write = ast_variable_retrieve(ucfg, "general", "write");
  8255. }
  8256. if (!user_displayconnects) {
  8257. user_displayconnects = ast_variable_retrieve(ucfg, "general", "displayconnects");
  8258. }
  8259. if (!user_allowmultiplelogin) {
  8260. user_allowmultiplelogin = ast_variable_retrieve(ucfg, "general", "allowmultiplelogin");
  8261. }
  8262. if (!user_writetimeout) {
  8263. user_writetimeout = ast_variable_retrieve(ucfg, "general", "writetimeout");
  8264. }
  8265. if (!ast_strlen_zero(user_secret)) {
  8266. ast_free(user->secret);
  8267. user->secret = ast_strdup(user_secret);
  8268. }
  8269. if (user_read) {
  8270. user->readperm = get_perm(user_read);
  8271. }
  8272. if (user_write) {
  8273. user->writeperm = get_perm(user_write);
  8274. }
  8275. if (user_displayconnects) {
  8276. user->displayconnects = ast_true(user_displayconnects);
  8277. }
  8278. if (user_allowmultiplelogin) {
  8279. user->allowmultiplelogin = ast_true(user_allowmultiplelogin);
  8280. }
  8281. if (user_writetimeout) {
  8282. int value = atoi(user_writetimeout);
  8283. if (value < 100) {
  8284. ast_log(LOG_WARNING, "Invalid writetimeout value '%d' in users.conf\n", value);
  8285. } else {
  8286. user->writetimeout = value;
  8287. }
  8288. }
  8289. }
  8290. }
  8291. ast_config_destroy(ucfg);
  8292. }
  8293. /* cat is NULL here in any case */
  8294. while ((cat = ast_category_browse(cfg, cat))) {
  8295. struct ast_acl_list *oldacl;
  8296. if (!strcasecmp(cat, "general")) {
  8297. continue;
  8298. }
  8299. /* Look for an existing entry, if none found - create one and add it to the list */
  8300. if (!(user = get_manager_by_name_locked(cat))) {
  8301. if (!(user = ast_calloc(1, sizeof(*user)))) {
  8302. break;
  8303. }
  8304. /* Copy name over */
  8305. ast_copy_string(user->username, cat, sizeof(user->username));
  8306. user->acl = NULL;
  8307. user->readperm = 0;
  8308. user->writeperm = 0;
  8309. /* Default displayconnect from [general] */
  8310. user->displayconnects = displayconnects;
  8311. /* Default allowmultiplelogin from [general] */
  8312. user->allowmultiplelogin = allowmultiplelogin;
  8313. user->writetimeout = 100;
  8314. user->whitefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
  8315. user->blackfilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
  8316. if (!user->whitefilters || !user->blackfilters) {
  8317. manager_free_user(user);
  8318. break;
  8319. }
  8320. /* Insert into list */
  8321. AST_RWLIST_INSERT_TAIL(&users, user, list);
  8322. } else {
  8323. ao2_t_callback(user->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
  8324. ao2_t_callback(user->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
  8325. }
  8326. /* Make sure we keep this user and don't destroy it during cleanup */
  8327. user->keep = 1;
  8328. oldacl = user->acl;
  8329. user->acl = NULL;
  8330. ast_variables_destroy(user->chanvars);
  8331. var = ast_variable_browse(cfg, cat);
  8332. for (; var; var = var->next) {
  8333. if (!strcasecmp(var->name, "secret")) {
  8334. ast_free(user->secret);
  8335. user->secret = ast_strdup(var->value);
  8336. } else if (!strcasecmp(var->name, "deny") ||
  8337. !strcasecmp(var->name, "permit") ||
  8338. !strcasecmp(var->name, "acl")) {
  8339. ast_append_acl(var->name, var->value, &user->acl, NULL, &acl_subscription_flag);
  8340. } else if (!strcasecmp(var->name, "read") ) {
  8341. user->readperm = get_perm(var->value);
  8342. } else if (!strcasecmp(var->name, "write") ) {
  8343. user->writeperm = get_perm(var->value);
  8344. } else if (!strcasecmp(var->name, "displayconnects") ) {
  8345. user->displayconnects = ast_true(var->value);
  8346. } else if (!strcasecmp(var->name, "allowmultiplelogin") ) {
  8347. user->allowmultiplelogin = ast_true(var->value);
  8348. } else if (!strcasecmp(var->name, "writetimeout")) {
  8349. int value = atoi(var->value);
  8350. if (value < 100) {
  8351. ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at line %d\n", var->value, var->lineno);
  8352. } else {
  8353. user->writetimeout = value;
  8354. }
  8355. } else if (!strcasecmp(var->name, "setvar")) {
  8356. struct ast_variable *tmpvar;
  8357. char varbuf[256];
  8358. char *varval;
  8359. char *varname;
  8360. ast_copy_string(varbuf, var->value, sizeof(varbuf));
  8361. varname = varbuf;
  8362. if ((varval = strchr(varname,'='))) {
  8363. *varval++ = '\0';
  8364. if ((tmpvar = ast_variable_new(varname, varval, ""))) {
  8365. tmpvar->next = user->chanvars;
  8366. user->chanvars = tmpvar;
  8367. }
  8368. }
  8369. } else if (!strcasecmp(var->name, "eventfilter")) {
  8370. const char *value = var->value;
  8371. manager_add_filter(value, user->whitefilters, user->blackfilters);
  8372. } else {
  8373. ast_debug(1, "%s is an unknown option.\n", var->name);
  8374. }
  8375. }
  8376. oldacl = ast_free_acl_list(oldacl);
  8377. }
  8378. ast_config_destroy(cfg);
  8379. /* Check the flag for named ACL event subscription and if we need to, register a subscription. */
  8380. if (acl_subscription_flag && !by_external_config) {
  8381. acl_change_stasis_subscribe();
  8382. }
  8383. /* Perform cleanup - essentially prune out old users that no longer exist */
  8384. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&users, user, list) {
  8385. if (user->keep) { /* valid record. clear flag for the next round */
  8386. user->keep = 0;
  8387. /* Calculate A1 for Digest auth */
  8388. snprintf(a1, sizeof(a1), "%s:%s:%s", user->username, global_realm, user->secret);
  8389. ast_md5_hash(a1_hash,a1);
  8390. ast_free(user->a1_hash);
  8391. user->a1_hash = ast_strdup(a1_hash);
  8392. continue;
  8393. }
  8394. /* We do not need to keep this user so take them out of the list */
  8395. AST_RWLIST_REMOVE_CURRENT(list);
  8396. ast_debug(4, "Pruning user '%s'\n", user->username);
  8397. manager_free_user(user);
  8398. }
  8399. AST_RWLIST_TRAVERSE_SAFE_END;
  8400. AST_RWLIST_UNLOCK(&users);
  8401. if (webmanager_enabled && manager_enabled) {
  8402. if (!webregged) {
  8403. ast_http_uri_link(&rawmanuri);
  8404. ast_http_uri_link(&manageruri);
  8405. ast_http_uri_link(&managerxmluri);
  8406. ast_http_uri_link(&arawmanuri);
  8407. ast_http_uri_link(&amanageruri);
  8408. ast_http_uri_link(&amanagerxmluri);
  8409. webregged = 1;
  8410. }
  8411. } else {
  8412. if (webregged) {
  8413. ast_http_uri_unlink(&rawmanuri);
  8414. ast_http_uri_unlink(&manageruri);
  8415. ast_http_uri_unlink(&managerxmluri);
  8416. ast_http_uri_unlink(&arawmanuri);
  8417. ast_http_uri_unlink(&amanageruri);
  8418. ast_http_uri_unlink(&amanagerxmluri);
  8419. webregged = 0;
  8420. }
  8421. }
  8422. if (newhttptimeout > 0) {
  8423. httptimeout = newhttptimeout;
  8424. }
  8425. ast_tcptls_server_start(&ami_desc);
  8426. if (tls_was_enabled && !ami_tls_cfg.enabled) {
  8427. ast_tcptls_server_stop(&amis_desc);
  8428. } else if (ast_ssl_setup(amis_desc.tls_cfg)) {
  8429. ast_tcptls_server_start(&amis_desc);
  8430. }
  8431. return 0;
  8432. }
  8433. static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
  8434. struct stasis_message *message)
  8435. {
  8436. if (stasis_message_type(message) != ast_named_acl_change_type()) {
  8437. return;
  8438. }
  8439. /* For now, this is going to be performed simply and just execute a forced reload. */
  8440. ast_log(LOG_NOTICE, "Reloading manager in response to ACL change event.\n");
  8441. __init_manager(1, 1);
  8442. }
  8443. int init_manager(void)
  8444. {
  8445. return __init_manager(0, 0);
  8446. }
  8447. int reload_manager(void)
  8448. {
  8449. return __init_manager(1, 0);
  8450. }
  8451. int astman_datastore_add(struct mansession *s, struct ast_datastore *datastore)
  8452. {
  8453. AST_LIST_INSERT_HEAD(&s->session->datastores, datastore, entry);
  8454. return 0;
  8455. }
  8456. int astman_datastore_remove(struct mansession *s, struct ast_datastore *datastore)
  8457. {
  8458. return AST_LIST_REMOVE(&s->session->datastores, datastore, entry) ? 0 : -1;
  8459. }
  8460. struct ast_datastore *astman_datastore_find(struct mansession *s, const struct ast_datastore_info *info, const char *uid)
  8461. {
  8462. struct ast_datastore *datastore = NULL;
  8463. if (info == NULL)
  8464. return NULL;
  8465. AST_LIST_TRAVERSE_SAFE_BEGIN(&s->session->datastores, datastore, entry) {
  8466. if (datastore->info != info) {
  8467. continue;
  8468. }
  8469. if (uid == NULL) {
  8470. /* matched by type only */
  8471. break;
  8472. }
  8473. if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
  8474. /* Matched by type AND uid */
  8475. break;
  8476. }
  8477. }
  8478. AST_LIST_TRAVERSE_SAFE_END;
  8479. return datastore;
  8480. }
  8481. int ast_str_append_event_header(struct ast_str **fields_string,
  8482. const char *header, const char *value)
  8483. {
  8484. if (!*fields_string) {
  8485. *fields_string = ast_str_create(128);
  8486. if (!*fields_string) {
  8487. return -1;
  8488. }
  8489. }
  8490. return (ast_str_append(fields_string, 0, "%s: %s\r\n", header, value) < 0) ? -1 : 0;
  8491. }
  8492. static void manager_event_blob_dtor(void *obj)
  8493. {
  8494. struct ast_manager_event_blob *ev = obj;
  8495. ast_string_field_free_memory(ev);
  8496. }
  8497. struct ast_manager_event_blob *
  8498. __attribute__((format(printf, 3, 4)))
  8499. ast_manager_event_blob_create(
  8500. int event_flags,
  8501. const char *manager_event,
  8502. const char *extra_fields_fmt,
  8503. ...)
  8504. {
  8505. struct ast_manager_event_blob *ev;
  8506. va_list argp;
  8507. ast_assert(extra_fields_fmt != NULL);
  8508. ast_assert(manager_event != NULL);
  8509. ev = ao2_alloc_options(sizeof(*ev), manager_event_blob_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
  8510. if (!ev) {
  8511. return NULL;
  8512. }
  8513. if (ast_string_field_init(ev, 20)) {
  8514. ao2_ref(ev, -1);
  8515. return NULL;
  8516. }
  8517. ev->manager_event = manager_event;
  8518. ev->event_flags = event_flags;
  8519. va_start(argp, extra_fields_fmt);
  8520. ast_string_field_ptr_build_va(ev, &ev->extra_fields, extra_fields_fmt, argp);
  8521. va_end(argp);
  8522. return ev;
  8523. }