app_queue.c 359 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010
  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 True call queues with optional send URL on answer
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. *
  24. * \par Development notes
  25. * \note 2004-11-25: Persistent Dynamic Members added by:
  26. * NetNation Communications (www.netnation.com)
  27. * Kevin Lindsay <kevinl@netnation.com>
  28. *
  29. * Each dynamic agent in each queue is now stored in the astdb.
  30. * When asterisk is restarted, each agent will be automatically
  31. * readded into their recorded queues. This feature can be
  32. * configured with the 'persistent_members=<1|0>' setting in the
  33. * '[general]' category in queues.conf. The default is on.
  34. *
  35. * \note 2004-06-04: Priorities in queues added by inAccess Networks (work funded by Hellas On Line (HOL) www.hol.gr).
  36. *
  37. * \note These features added by David C. Troy <dave@toad.net>:
  38. * - Per-queue holdtime calculation
  39. * - Estimated holdtime announcement
  40. * - Position announcement
  41. * - Abandoned/completed call counters
  42. * - Failout timer passed as optional app parameter
  43. * - Optional monitoring of calls, started when call is answered
  44. *
  45. * Patch Version 1.07 2003-12-24 01
  46. *
  47. * Added servicelevel statistic by Michiel Betel <michiel@betel.nl>
  48. * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <asterisk@doilooklikeicare.com>
  49. *
  50. * Fixed to work with CVS as of 2004-02-25 and released as 1.07a
  51. * by Matthew Enger <m.enger@xi.com.au>
  52. *
  53. * \ingroup applications
  54. */
  55. /*! \li \ref app_queues.c uses configuration file \ref queues.conf
  56. * \addtogroup configuration_file
  57. */
  58. /*! \page queues.conf queues.conf
  59. * \verbinclude queues.conf.sample
  60. */
  61. /*** MODULEINFO
  62. <use type="module">res_monitor</use>
  63. <support_level>core</support_level>
  64. ***/
  65. #include "asterisk.h"
  66. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  67. #include <sys/time.h>
  68. #include <sys/signal.h>
  69. #include <netinet/in.h>
  70. #include <ctype.h>
  71. #include "asterisk/lock.h"
  72. #include "asterisk/file.h"
  73. #include "asterisk/channel.h"
  74. #include "asterisk/pbx.h"
  75. #include "asterisk/app.h"
  76. #include "asterisk/linkedlists.h"
  77. #include "asterisk/module.h"
  78. #include "asterisk/translate.h"
  79. #include "asterisk/say.h"
  80. #include "asterisk/features.h"
  81. #include "asterisk/musiconhold.h"
  82. #include "asterisk/cli.h"
  83. #include "asterisk/manager.h"
  84. #include "asterisk/config.h"
  85. #include "asterisk/monitor.h"
  86. #include "asterisk/utils.h"
  87. #include "asterisk/causes.h"
  88. #include "asterisk/astdb.h"
  89. #include "asterisk/devicestate.h"
  90. #include "asterisk/stringfields.h"
  91. #include "asterisk/astobj2.h"
  92. #include "asterisk/strings.h"
  93. #include "asterisk/global_datastores.h"
  94. #include "asterisk/taskprocessor.h"
  95. #include "asterisk/aoc.h"
  96. #include "asterisk/callerid.h"
  97. #include "asterisk/data.h"
  98. #include "asterisk/term.h"
  99. #include "asterisk/dial.h"
  100. #include "asterisk/stasis_channels.h"
  101. #include "asterisk/stasis_message_router.h"
  102. #include "asterisk/bridge_after.h"
  103. #include "asterisk/stasis_bridges.h"
  104. #include "asterisk/core_local.h"
  105. #include "asterisk/mixmonitor.h"
  106. #include "asterisk/core_unreal.h"
  107. #include "asterisk/bridge_basic.h"
  108. /*!
  109. * \par Please read before modifying this file.
  110. * There are three locks which are regularly used
  111. * throughout this file, the queue list lock, the lock
  112. * for each individual queue, and the interface list lock.
  113. * Please be extra careful to always lock in the following order
  114. * 1) queue list lock
  115. * 2) individual queue lock
  116. * 3) interface list lock
  117. * This order has sort of "evolved" over the lifetime of this
  118. * application, but it is now in place this way, so please adhere
  119. * to this order!
  120. */
  121. /*** DOCUMENTATION
  122. <application name="Queue" language="en_US">
  123. <synopsis>
  124. Queue a call for a call queue.
  125. </synopsis>
  126. <syntax>
  127. <parameter name="queuename" required="true" />
  128. <parameter name="options">
  129. <optionlist>
  130. <option name="C">
  131. <para>Mark all calls as "answered elsewhere" when cancelled.</para>
  132. </option>
  133. <option name="c">
  134. <para>Continue in the dialplan if the callee hangs up.</para>
  135. </option>
  136. <option name="d">
  137. <para>data-quality (modem) call (minimum delay).</para>
  138. </option>
  139. <option name="F" argsep="^">
  140. <argument name="context" required="false" />
  141. <argument name="exten" required="false" />
  142. <argument name="priority" required="true" />
  143. <para>When the caller hangs up, transfer the <emphasis>called member</emphasis>
  144. to the specified destination and <emphasis>start</emphasis> execution at that location.</para>
  145. <note>
  146. <para>Any channel variables you want the called channel to inherit from the caller channel must be
  147. prefixed with one or two underbars ('_').</para>
  148. </note>
  149. </option>
  150. <option name="F">
  151. <para>When the caller hangs up, transfer the <emphasis>called member</emphasis> to the next priority of
  152. the current extension and <emphasis>start</emphasis> execution at that location.</para>
  153. <note>
  154. <para>Any channel variables you want the called channel to inherit from the caller channel must be
  155. prefixed with one or two underbars ('_').</para>
  156. </note>
  157. <note>
  158. <para>Using this option from a Macro() or GoSub() might not make sense as there would be no return points.</para>
  159. </note>
  160. </option>
  161. <option name="h">
  162. <para>Allow <emphasis>callee</emphasis> to hang up by pressing <literal>*</literal>.</para>
  163. </option>
  164. <option name="H">
  165. <para>Allow <emphasis>caller</emphasis> to hang up by pressing <literal>*</literal>.</para>
  166. </option>
  167. <option name="n">
  168. <para>No retries on the timeout; will exit this application and
  169. go to the next step.</para>
  170. </option>
  171. <option name="i">
  172. <para>Ignore call forward requests from queue members and do nothing
  173. when they are requested.</para>
  174. </option>
  175. <option name="I">
  176. <para>Asterisk will ignore any connected line update requests or any redirecting party
  177. update requests it may receive on this dial attempt.</para>
  178. </option>
  179. <option name="r">
  180. <para>Ring instead of playing MOH. Periodic Announcements are still made, if applicable.</para>
  181. </option>
  182. <option name="R">
  183. <para>Ring instead of playing MOH when a member channel is actually ringing.</para>
  184. </option>
  185. <option name="t">
  186. <para>Allow the <emphasis>called</emphasis> user to transfer the calling user.</para>
  187. </option>
  188. <option name="T">
  189. <para>Allow the <emphasis>calling</emphasis> user to transfer the call.</para>
  190. </option>
  191. <option name="w">
  192. <para>Allow the <emphasis>called</emphasis> user to write the conversation to
  193. disk via Monitor.</para>
  194. </option>
  195. <option name="W">
  196. <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
  197. disk via Monitor.</para>
  198. </option>
  199. <option name="k">
  200. <para>Allow the <emphasis>called</emphasis> party to enable parking of the call by sending
  201. the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
  202. </option>
  203. <option name="K">
  204. <para>Allow the <emphasis>calling</emphasis> party to enable parking of the call by sending
  205. the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
  206. </option>
  207. <option name="x">
  208. <para>Allow the <emphasis>called</emphasis> user to write the conversation
  209. to disk via MixMonitor.</para>
  210. </option>
  211. <option name="X">
  212. <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
  213. disk via MixMonitor.</para>
  214. </option>
  215. </optionlist>
  216. </parameter>
  217. <parameter name="URL">
  218. <para><replaceable>URL</replaceable> will be sent to the called party if the channel supports it.</para>
  219. </parameter>
  220. <parameter name="announceoverride" />
  221. <parameter name="timeout">
  222. <para>Will cause the queue to fail out after a specified number of
  223. seconds, checked between each <filename>queues.conf</filename> <replaceable>timeout</replaceable> and
  224. <replaceable>retry</replaceable> cycle.</para>
  225. </parameter>
  226. <parameter name="AGI">
  227. <para>Will setup an AGI script to be executed on the calling party's channel once they are
  228. connected to a queue member.</para>
  229. </parameter>
  230. <parameter name="macro">
  231. <para>Will run a macro on the called party's channel (the queue member) once the parties are connected.</para>
  232. </parameter>
  233. <parameter name="gosub">
  234. <para>Will run a gosub on the called party's channel (the queue member) once the parties are connected.</para>
  235. </parameter>
  236. <parameter name="rule">
  237. <para>Will cause the queue's defaultrule to be overridden by the rule specified.</para>
  238. </parameter>
  239. <parameter name="position">
  240. <para>Attempt to enter the caller into the queue at the numerical position specified. <literal>1</literal>
  241. would attempt to enter the caller at the head of the queue, and <literal>3</literal> would attempt to place
  242. the caller third in the queue.</para>
  243. </parameter>
  244. </syntax>
  245. <description>
  246. <para>In addition to transferring the call, a call may be parked and then picked
  247. up by another user.</para>
  248. <para>This application will return to the dialplan if the queue does not exist, or
  249. any of the join options cause the caller to not enter the queue.</para>
  250. <para>This application does not automatically answer and should be preceeded
  251. by an application such as Answer(), Progress(), or Ringing().</para>
  252. <para>This application sets the following channel variable upon completion:</para>
  253. <variablelist>
  254. <variable name="QUEUESTATUS">
  255. <para>The status of the call as a text string.</para>
  256. <value name="TIMEOUT" />
  257. <value name="FULL" />
  258. <value name="JOINEMPTY" />
  259. <value name="LEAVEEMPTY" />
  260. <value name="JOINUNAVAIL" />
  261. <value name="LEAVEUNAVAIL" />
  262. <value name="CONTINUE" />
  263. </variable>
  264. </variablelist>
  265. </description>
  266. <see-also>
  267. <ref type="application">Queue</ref>
  268. <ref type="application">QueueLog</ref>
  269. <ref type="application">AddQueueMember</ref>
  270. <ref type="application">RemoveQueueMember</ref>
  271. <ref type="application">PauseQueueMember</ref>
  272. <ref type="application">UnpauseQueueMember</ref>
  273. <ref type="function">QUEUE_VARIABLES</ref>
  274. <ref type="function">QUEUE_MEMBER</ref>
  275. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  276. <ref type="function">QUEUE_EXISTS</ref>
  277. <ref type="function">QUEUE_GET_CHANNEL</ref>
  278. <ref type="function">QUEUE_WAITING_COUNT</ref>
  279. <ref type="function">QUEUE_MEMBER_LIST</ref>
  280. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  281. </see-also>
  282. </application>
  283. <application name="AddQueueMember" language="en_US">
  284. <synopsis>
  285. Dynamically adds queue members.
  286. </synopsis>
  287. <syntax>
  288. <parameter name="queuename" required="true" />
  289. <parameter name="interface" />
  290. <parameter name="penalty" />
  291. <parameter name="options" />
  292. <parameter name="membername" />
  293. <parameter name="stateinterface" />
  294. </syntax>
  295. <description>
  296. <para>Dynamically adds interface to an existing queue. If the interface is
  297. already in the queue it will return an error.</para>
  298. <para>This application sets the following channel variable upon completion:</para>
  299. <variablelist>
  300. <variable name="AQMSTATUS">
  301. <para>The status of the attempt to add a queue member as a text string.</para>
  302. <value name="ADDED" />
  303. <value name="MEMBERALREADY" />
  304. <value name="NOSUCHQUEUE" />
  305. </variable>
  306. </variablelist>
  307. </description>
  308. <see-also>
  309. <ref type="application">Queue</ref>
  310. <ref type="application">QueueLog</ref>
  311. <ref type="application">AddQueueMember</ref>
  312. <ref type="application">RemoveQueueMember</ref>
  313. <ref type="application">PauseQueueMember</ref>
  314. <ref type="application">UnpauseQueueMember</ref>
  315. <ref type="function">QUEUE_VARIABLES</ref>
  316. <ref type="function">QUEUE_MEMBER</ref>
  317. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  318. <ref type="function">QUEUE_EXISTS</ref>
  319. <ref type="function">QUEUE_GET_CHANNEL</ref>
  320. <ref type="function">QUEUE_WAITING_COUNT</ref>
  321. <ref type="function">QUEUE_MEMBER_LIST</ref>
  322. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  323. </see-also>
  324. </application>
  325. <application name="RemoveQueueMember" language="en_US">
  326. <synopsis>
  327. Dynamically removes queue members.
  328. </synopsis>
  329. <syntax>
  330. <parameter name="queuename" required="true" />
  331. <parameter name="interface" />
  332. </syntax>
  333. <description>
  334. <para>If the interface is <emphasis>NOT</emphasis> in the queue it will return an error.</para>
  335. <para>This application sets the following channel variable upon completion:</para>
  336. <variablelist>
  337. <variable name="RQMSTATUS">
  338. <value name="REMOVED" />
  339. <value name="NOTINQUEUE" />
  340. <value name="NOSUCHQUEUE" />
  341. <value name="NOTDYNAMIC" />
  342. </variable>
  343. </variablelist>
  344. <para>Example: RemoveQueueMember(techsupport,SIP/3000)</para>
  345. </description>
  346. <see-also>
  347. <ref type="application">Queue</ref>
  348. <ref type="application">QueueLog</ref>
  349. <ref type="application">AddQueueMember</ref>
  350. <ref type="application">RemoveQueueMember</ref>
  351. <ref type="application">PauseQueueMember</ref>
  352. <ref type="application">UnpauseQueueMember</ref>
  353. <ref type="function">QUEUE_VARIABLES</ref>
  354. <ref type="function">QUEUE_MEMBER</ref>
  355. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  356. <ref type="function">QUEUE_EXISTS</ref>
  357. <ref type="function">QUEUE_GET_CHANNEL</ref>
  358. <ref type="function">QUEUE_WAITING_COUNT</ref>
  359. <ref type="function">QUEUE_MEMBER_LIST</ref>
  360. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  361. </see-also>
  362. </application>
  363. <application name="PauseQueueMember" language="en_US">
  364. <synopsis>
  365. Pauses a queue member.
  366. </synopsis>
  367. <syntax>
  368. <parameter name="queuename" />
  369. <parameter name="interface" required="true" />
  370. <parameter name="options" />
  371. <parameter name="reason">
  372. <para>Is used to add extra information to the appropriate queue_log entries and manager events.</para>
  373. </parameter>
  374. </syntax>
  375. <description>
  376. <para>Pauses (blocks calls for) a queue member. The given interface will be paused in the given queue.
  377. This prevents any calls from being sent from the queue to the interface until it is
  378. unpaused with UnpauseQueueMember or the manager interface. If no queuename is given,
  379. the interface is paused in every queue it is a member of. The application will fail if the
  380. interface is not found.</para>
  381. <para>This application sets the following channel variable upon completion:</para>
  382. <variablelist>
  383. <variable name="PQMSTATUS">
  384. <para>The status of the attempt to pause a queue member as a text string.</para>
  385. <value name="PAUSED" />
  386. <value name="NOTFOUND" />
  387. </variable>
  388. </variablelist>
  389. <para>Example: PauseQueueMember(,SIP/3000)</para>
  390. </description>
  391. <see-also>
  392. <ref type="application">Queue</ref>
  393. <ref type="application">QueueLog</ref>
  394. <ref type="application">AddQueueMember</ref>
  395. <ref type="application">RemoveQueueMember</ref>
  396. <ref type="application">PauseQueueMember</ref>
  397. <ref type="application">UnpauseQueueMember</ref>
  398. <ref type="function">QUEUE_VARIABLES</ref>
  399. <ref type="function">QUEUE_MEMBER</ref>
  400. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  401. <ref type="function">QUEUE_EXISTS</ref>
  402. <ref type="function">QUEUE_GET_CHANNEL</ref>
  403. <ref type="function">QUEUE_WAITING_COUNT</ref>
  404. <ref type="function">QUEUE_MEMBER_LIST</ref>
  405. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  406. </see-also>
  407. </application>
  408. <application name="UnpauseQueueMember" language="en_US">
  409. <synopsis>
  410. Unpauses a queue member.
  411. </synopsis>
  412. <syntax>
  413. <parameter name="queuename" />
  414. <parameter name="interface" required="true" />
  415. <parameter name="options" />
  416. <parameter name="reason">
  417. <para>Is used to add extra information to the appropriate queue_log entries and manager events.</para>
  418. </parameter>
  419. </syntax>
  420. <description>
  421. <para>Unpauses (resumes calls to) a queue member. This is the counterpart to <literal>PauseQueueMember()</literal>
  422. and operates exactly the same way, except it unpauses instead of pausing the given interface.</para>
  423. <para>This application sets the following channel variable upon completion:</para>
  424. <variablelist>
  425. <variable name="UPQMSTATUS">
  426. <para>The status of the attempt to unpause a queue member as a text string.</para>
  427. <value name="UNPAUSED" />
  428. <value name="NOTFOUND" />
  429. </variable>
  430. </variablelist>
  431. <para>Example: UnpauseQueueMember(,SIP/3000)</para>
  432. </description>
  433. <see-also>
  434. <ref type="application">Queue</ref>
  435. <ref type="application">QueueLog</ref>
  436. <ref type="application">AddQueueMember</ref>
  437. <ref type="application">RemoveQueueMember</ref>
  438. <ref type="application">PauseQueueMember</ref>
  439. <ref type="application">UnpauseQueueMember</ref>
  440. <ref type="function">QUEUE_VARIABLES</ref>
  441. <ref type="function">QUEUE_MEMBER</ref>
  442. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  443. <ref type="function">QUEUE_EXISTS</ref>
  444. <ref type="function">QUEUE_GET_CHANNEL</ref>
  445. <ref type="function">QUEUE_WAITING_COUNT</ref>
  446. <ref type="function">QUEUE_MEMBER_LIST</ref>
  447. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  448. </see-also>
  449. </application>
  450. <application name="QueueLog" language="en_US">
  451. <synopsis>
  452. Writes to the queue_log file.
  453. </synopsis>
  454. <syntax>
  455. <parameter name="queuename" required="true" />
  456. <parameter name="uniqueid" required="true" />
  457. <parameter name="agent" required="true" />
  458. <parameter name="event" required="true" />
  459. <parameter name="additionalinfo" />
  460. </syntax>
  461. <description>
  462. <para>Allows you to write your own events into the queue log.</para>
  463. <para>Example: QueueLog(101,${UNIQUEID},${AGENT},WENTONBREAK,600)</para>
  464. </description>
  465. <see-also>
  466. <ref type="application">Queue</ref>
  467. <ref type="application">QueueLog</ref>
  468. <ref type="application">AddQueueMember</ref>
  469. <ref type="application">RemoveQueueMember</ref>
  470. <ref type="application">PauseQueueMember</ref>
  471. <ref type="application">UnpauseQueueMember</ref>
  472. <ref type="function">QUEUE_VARIABLES</ref>
  473. <ref type="function">QUEUE_MEMBER</ref>
  474. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  475. <ref type="function">QUEUE_EXISTS</ref>
  476. <ref type="function">QUEUE_GET_CHANNEL</ref>
  477. <ref type="function">QUEUE_WAITING_COUNT</ref>
  478. <ref type="function">QUEUE_MEMBER_LIST</ref>
  479. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  480. </see-also>
  481. </application>
  482. <function name="QUEUE_VARIABLES" language="en_US">
  483. <synopsis>
  484. Return Queue information in variables.
  485. </synopsis>
  486. <syntax>
  487. <parameter name="queuename" required="true">
  488. <enumlist>
  489. <enum name="QUEUEMAX">
  490. <para>Maxmimum number of calls allowed.</para>
  491. </enum>
  492. <enum name="QUEUESTRATEGY">
  493. <para>The strategy of the queue.</para>
  494. </enum>
  495. <enum name="QUEUECALLS">
  496. <para>Number of calls currently in the queue.</para>
  497. </enum>
  498. <enum name="QUEUEHOLDTIME">
  499. <para>Current average hold time.</para>
  500. </enum>
  501. <enum name="QUEUECOMPLETED">
  502. <para>Number of completed calls for the queue.</para>
  503. </enum>
  504. <enum name="QUEUEABANDONED">
  505. <para>Number of abandoned calls.</para>
  506. </enum>
  507. <enum name="QUEUESRVLEVEL">
  508. <para>Queue service level.</para>
  509. </enum>
  510. <enum name="QUEUESRVLEVELPERF">
  511. <para>Current service level performance.</para>
  512. </enum>
  513. </enumlist>
  514. </parameter>
  515. </syntax>
  516. <description>
  517. <para>Makes the following queue variables available.</para>
  518. <para>Returns <literal>0</literal> if queue is found and setqueuevar is defined, <literal>-1</literal> otherwise.</para>
  519. </description>
  520. <see-also>
  521. <ref type="application">Queue</ref>
  522. <ref type="application">QueueLog</ref>
  523. <ref type="application">AddQueueMember</ref>
  524. <ref type="application">RemoveQueueMember</ref>
  525. <ref type="application">PauseQueueMember</ref>
  526. <ref type="application">UnpauseQueueMember</ref>
  527. <ref type="function">QUEUE_VARIABLES</ref>
  528. <ref type="function">QUEUE_MEMBER</ref>
  529. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  530. <ref type="function">QUEUE_EXISTS</ref>
  531. <ref type="function">QUEUE_GET_CHANNEL</ref>
  532. <ref type="function">QUEUE_WAITING_COUNT</ref>
  533. <ref type="function">QUEUE_MEMBER_LIST</ref>
  534. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  535. </see-also>
  536. </function>
  537. <function name="QUEUE_MEMBER" language="en_US">
  538. <synopsis>
  539. Count number of members answering a queue.
  540. </synopsis>
  541. <syntax>
  542. <parameter name="queuename" required="true" />
  543. <parameter name="option" required="true">
  544. <enumlist>
  545. <enum name="logged">
  546. <para>Returns the number of logged-in members for the specified queue.</para>
  547. </enum>
  548. <enum name="free">
  549. <para>Returns the number of logged-in members for the specified queue that either can take calls or are currently wrapping up after a previous call.</para>
  550. </enum>
  551. <enum name="ready">
  552. <para>Returns the number of logged-in members for the specified queue that are immediately available to answer a call.</para>
  553. </enum>
  554. <enum name="count">
  555. <para>Returns the total number of members for the specified queue.</para>
  556. </enum>
  557. <enum name="penalty">
  558. <para>Gets or sets queue member penalty.</para>
  559. </enum>
  560. <enum name="paused">
  561. <para>Gets or sets queue member paused status.</para>
  562. </enum>
  563. <enum name="ringinuse">
  564. <para>Gets or sets queue member ringinuse.</para>
  565. </enum>
  566. </enumlist>
  567. </parameter>
  568. <parameter name="interface" required="false" />
  569. </syntax>
  570. <description>
  571. <para>Allows access to queue counts [R] and member information [R/W].</para>
  572. <para>
  573. <replaceable>queuename</replaceable> is required for all operations
  574. <replaceable>interface</replaceable> is required for all member operations.
  575. </para>
  576. </description>
  577. <see-also>
  578. <ref type="application">Queue</ref>
  579. <ref type="application">QueueLog</ref>
  580. <ref type="application">AddQueueMember</ref>
  581. <ref type="application">RemoveQueueMember</ref>
  582. <ref type="application">PauseQueueMember</ref>
  583. <ref type="application">UnpauseQueueMember</ref>
  584. <ref type="function">QUEUE_VARIABLES</ref>
  585. <ref type="function">QUEUE_MEMBER</ref>
  586. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  587. <ref type="function">QUEUE_EXISTS</ref>
  588. <ref type="function">QUEUE_GET_CHANNEL</ref>
  589. <ref type="function">QUEUE_WAITING_COUNT</ref>
  590. <ref type="function">QUEUE_MEMBER_LIST</ref>
  591. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  592. </see-also>
  593. </function>
  594. <function name="QUEUE_MEMBER_COUNT" language="en_US">
  595. <synopsis>
  596. Count number of members answering a queue.
  597. </synopsis>
  598. <syntax>
  599. <parameter name="queuename" required="true" />
  600. </syntax>
  601. <description>
  602. <para>Returns the number of members currently associated with the specified <replaceable>queuename</replaceable>.</para>
  603. <warning><para>This function has been deprecated in favor of the <literal>QUEUE_MEMBER()</literal> function</para></warning>
  604. </description>
  605. <see-also>
  606. <ref type="application">Queue</ref>
  607. <ref type="application">QueueLog</ref>
  608. <ref type="application">AddQueueMember</ref>
  609. <ref type="application">RemoveQueueMember</ref>
  610. <ref type="application">PauseQueueMember</ref>
  611. <ref type="application">UnpauseQueueMember</ref>
  612. <ref type="function">QUEUE_VARIABLES</ref>
  613. <ref type="function">QUEUE_MEMBER</ref>
  614. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  615. <ref type="function">QUEUE_EXISTS</ref>
  616. <ref type="function">QUEUE_GET_CHANNEL</ref>
  617. <ref type="function">QUEUE_WAITING_COUNT</ref>
  618. <ref type="function">QUEUE_MEMBER_LIST</ref>
  619. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  620. </see-also>
  621. </function>
  622. <function name="QUEUE_EXISTS" language="en_US">
  623. <synopsis>
  624. Check if a named queue exists on this server
  625. </synopsis>
  626. <syntax>
  627. <parameter name="queuename" />
  628. </syntax>
  629. <description>
  630. <para>Returns 1 if the specified queue exists, 0 if it does not</para>
  631. </description>
  632. <see-also>
  633. <ref type="application">Queue</ref>
  634. <ref type="application">QueueLog</ref>
  635. <ref type="application">AddQueueMember</ref>
  636. <ref type="application">RemoveQueueMember</ref>
  637. <ref type="application">PauseQueueMember</ref>
  638. <ref type="application">UnpauseQueueMember</ref>
  639. <ref type="function">QUEUE_VARIABLES</ref>
  640. <ref type="function">QUEUE_MEMBER</ref>
  641. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  642. <ref type="function">QUEUE_EXISTS</ref>
  643. <ref type="function">QUEUE_GET_CHANNEL</ref>
  644. <ref type="function">QUEUE_WAITING_COUNT</ref>
  645. <ref type="function">QUEUE_MEMBER_LIST</ref>
  646. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  647. </see-also>
  648. </function>
  649. <function name="QUEUE_GET_CHANNEL" language="en_US">
  650. <synopsis>
  651. Return caller at the specified position in a queue.
  652. </synopsis>
  653. <syntax>
  654. <parameter name="queuename" required="true" />
  655. <parameter name="position" />
  656. </syntax>
  657. <description>
  658. <para>Returns the caller channel at <replaceable>position</replaceable> in the specified <replaceable>queuename</replaceable>.</para>
  659. <para>If <replaceable>position</replaceable> is unspecified the first channel is returned.</para>
  660. </description>
  661. <see-also>
  662. <ref type="application">Queue</ref>
  663. <ref type="application">QueueLog</ref>
  664. <ref type="application">AddQueueMember</ref>
  665. <ref type="application">RemoveQueueMember</ref>
  666. <ref type="application">PauseQueueMember</ref>
  667. <ref type="application">UnpauseQueueMember</ref>
  668. <ref type="function">QUEUE_VARIABLES</ref>
  669. <ref type="function">QUEUE_MEMBER</ref>
  670. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  671. <ref type="function">QUEUE_EXISTS</ref>
  672. <ref type="function">QUEUE_WAITING_COUNT</ref>
  673. <ref type="function">QUEUE_MEMBER_LIST</ref>
  674. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  675. </see-also>
  676. </function>
  677. <function name="QUEUE_WAITING_COUNT" language="en_US">
  678. <synopsis>
  679. Count number of calls currently waiting in a queue.
  680. </synopsis>
  681. <syntax>
  682. <parameter name="queuename" />
  683. </syntax>
  684. <description>
  685. <para>Returns the number of callers currently waiting in the specified <replaceable>queuename</replaceable>.</para>
  686. </description>
  687. <see-also>
  688. <ref type="application">Queue</ref>
  689. <ref type="application">QueueLog</ref>
  690. <ref type="application">AddQueueMember</ref>
  691. <ref type="application">RemoveQueueMember</ref>
  692. <ref type="application">PauseQueueMember</ref>
  693. <ref type="application">UnpauseQueueMember</ref>
  694. <ref type="function">QUEUE_VARIABLES</ref>
  695. <ref type="function">QUEUE_MEMBER</ref>
  696. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  697. <ref type="function">QUEUE_EXISTS</ref>
  698. <ref type="function">QUEUE_GET_CHANNEL</ref>
  699. <ref type="function">QUEUE_WAITING_COUNT</ref>
  700. <ref type="function">QUEUE_MEMBER_LIST</ref>
  701. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  702. </see-also>
  703. </function>
  704. <function name="QUEUE_MEMBER_LIST" language="en_US">
  705. <synopsis>
  706. Returns a list of interfaces on a queue.
  707. </synopsis>
  708. <syntax>
  709. <parameter name="queuename" required="true" />
  710. </syntax>
  711. <description>
  712. <para>Returns a comma-separated list of members associated with the specified <replaceable>queuename</replaceable>.</para>
  713. </description>
  714. <see-also>
  715. <ref type="application">Queue</ref>
  716. <ref type="application">QueueLog</ref>
  717. <ref type="application">AddQueueMember</ref>
  718. <ref type="application">RemoveQueueMember</ref>
  719. <ref type="application">PauseQueueMember</ref>
  720. <ref type="application">UnpauseQueueMember</ref>
  721. <ref type="function">QUEUE_VARIABLES</ref>
  722. <ref type="function">QUEUE_MEMBER</ref>
  723. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  724. <ref type="function">QUEUE_EXISTS</ref>
  725. <ref type="function">QUEUE_GET_CHANNEL</ref>
  726. <ref type="function">QUEUE_WAITING_COUNT</ref>
  727. <ref type="function">QUEUE_MEMBER_LIST</ref>
  728. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  729. </see-also>
  730. </function>
  731. <function name="QUEUE_MEMBER_PENALTY" language="en_US">
  732. <synopsis>
  733. Gets or sets queue members penalty.
  734. </synopsis>
  735. <syntax>
  736. <parameter name="queuename" required="true" />
  737. <parameter name="interface" required="true" />
  738. </syntax>
  739. <description>
  740. <para>Gets or sets queue members penalty.</para>
  741. <warning><para>This function has been deprecated in favor of the <literal>QUEUE_MEMBER()</literal> function</para></warning>
  742. </description>
  743. <see-also>
  744. <ref type="application">Queue</ref>
  745. <ref type="application">QueueLog</ref>
  746. <ref type="application">AddQueueMember</ref>
  747. <ref type="application">RemoveQueueMember</ref>
  748. <ref type="application">PauseQueueMember</ref>
  749. <ref type="application">UnpauseQueueMember</ref>
  750. <ref type="function">QUEUE_VARIABLES</ref>
  751. <ref type="function">QUEUE_MEMBER</ref>
  752. <ref type="function">QUEUE_MEMBER_COUNT</ref>
  753. <ref type="function">QUEUE_EXISTS</ref>
  754. <ref type="function">QUEUE_GET_CHANNEL</ref>
  755. <ref type="function">QUEUE_WAITING_COUNT</ref>
  756. <ref type="function">QUEUE_MEMBER_LIST</ref>
  757. <ref type="function">QUEUE_MEMBER_PENALTY</ref>
  758. </see-also>
  759. </function>
  760. <manager name="Queues" language="en_US">
  761. <synopsis>
  762. Queues.
  763. </synopsis>
  764. <syntax>
  765. </syntax>
  766. <description>
  767. <para>Show queues information.</para>
  768. </description>
  769. </manager>
  770. <manager name="QueueStatus" language="en_US">
  771. <synopsis>
  772. Show queue status.
  773. </synopsis>
  774. <syntax>
  775. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  776. <parameter name="Queue">
  777. <para>Limit the response to the status of the specified queue.</para>
  778. </parameter>
  779. <parameter name="Member">
  780. <para>Limit the response to the status of the specified member.</para>
  781. </parameter>
  782. </syntax>
  783. <description>
  784. <para>Check the status of one or more queues.</para>
  785. </description>
  786. </manager>
  787. <manager name="QueueSummary" language="en_US">
  788. <synopsis>
  789. Show queue summary.
  790. </synopsis>
  791. <syntax>
  792. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  793. <parameter name="Queue">
  794. <para>Queue for which the summary is requested.</para>
  795. </parameter>
  796. </syntax>
  797. <description>
  798. <para>Request the manager to send a QueueSummary event.</para>
  799. </description>
  800. </manager>
  801. <manager name="QueueAdd" language="en_US">
  802. <synopsis>
  803. Add interface to queue.
  804. </synopsis>
  805. <syntax>
  806. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  807. <parameter name="Queue" required="true">
  808. <para>Queue's name.</para>
  809. </parameter>
  810. <parameter name="Interface" required="true">
  811. <para>The name of the interface (tech/name) to add to the queue.</para>
  812. </parameter>
  813. <parameter name="Penalty">
  814. <para>A penalty (number) to apply to this member. Asterisk will distribute calls to members with higher penalties only after attempting to distribute calls to those with lower penalty.</para>
  815. </parameter>
  816. <parameter name="Paused">
  817. <para>To pause or not the member initially (true/false or 1/0).</para>
  818. </parameter>
  819. <parameter name="MemberName">
  820. <para>Text alias for the interface.</para>
  821. </parameter>
  822. <parameter name="StateInterface" />
  823. </syntax>
  824. <description>
  825. </description>
  826. </manager>
  827. <manager name="QueueRemove" language="en_US">
  828. <synopsis>
  829. Remove interface from queue.
  830. </synopsis>
  831. <syntax>
  832. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  833. <parameter name="Queue" required="true">
  834. <para>The name of the queue to take action on.</para>
  835. </parameter>
  836. <parameter name="Interface" required="true">
  837. <para>The interface (tech/name) to remove from queue.</para>
  838. </parameter>
  839. </syntax>
  840. <description>
  841. </description>
  842. </manager>
  843. <manager name="QueuePause" language="en_US">
  844. <synopsis>
  845. Makes a queue member temporarily unavailable.
  846. </synopsis>
  847. <syntax>
  848. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  849. <parameter name="Interface" required="true">
  850. <para>The name of the interface (tech/name) to pause or unpause.</para>
  851. </parameter>
  852. <parameter name="Paused" required="true">
  853. <para>Pause or unpause the interface. Set to 'true' to pause the member or 'false' to unpause.</para>
  854. </parameter>
  855. <parameter name="Queue">
  856. <para>The name of the queue in which to pause or unpause this member. If not specified, the member will be paused or unpaused in all the queues it is a member of.</para>
  857. </parameter>
  858. <parameter name="Reason">
  859. <para>Text description, returned in the event QueueMemberPaused.</para>
  860. </parameter>
  861. </syntax>
  862. <description>
  863. <para>Pause or unpause a member in a queue.</para>
  864. </description>
  865. </manager>
  866. <manager name="QueueLog" language="en_US">
  867. <synopsis>
  868. Adds custom entry in queue_log.
  869. </synopsis>
  870. <syntax>
  871. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  872. <parameter name="Queue" required="true" />
  873. <parameter name="Event" required="true" />
  874. <parameter name="Uniqueid" />
  875. <parameter name="Interface" />
  876. <parameter name="Message" />
  877. </syntax>
  878. <description>
  879. </description>
  880. </manager>
  881. <manager name="QueuePenalty" language="en_US">
  882. <synopsis>
  883. Set the penalty for a queue member.
  884. </synopsis>
  885. <syntax>
  886. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  887. <parameter name="Interface" required="true">
  888. <para>The interface (tech/name) of the member whose penalty to change.</para>
  889. </parameter>
  890. <parameter name="Penalty" required="true">
  891. <para>The new penalty (number) for the member. Must be nonnegative.</para>
  892. </parameter>
  893. <parameter name="Queue">
  894. <para>If specified, only set the penalty for the member of this queue. Otherwise, set the penalty for the member in all queues to which the member belongs.</para>
  895. </parameter>
  896. </syntax>
  897. <description>
  898. <para>Change the penalty of a queue member</para>
  899. </description>
  900. </manager>
  901. <manager name="QueueMemberRingInUse" language="en_US">
  902. <synopsis>
  903. Set the ringinuse value for a queue member.
  904. </synopsis>
  905. <syntax>
  906. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  907. <parameter name="Interface" required="true" />
  908. <parameter name="RingInUse" required="true" />
  909. <parameter name="Queue" />
  910. </syntax>
  911. <description>
  912. </description>
  913. </manager>
  914. <manager name="QueueRule" language="en_US">
  915. <synopsis>
  916. Queue Rules.
  917. </synopsis>
  918. <syntax>
  919. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  920. <parameter name="Rule">
  921. <para>The name of the rule in queuerules.conf whose contents to list.</para>
  922. </parameter>
  923. </syntax>
  924. <description>
  925. <para>List queue rules defined in queuerules.conf</para>
  926. </description>
  927. </manager>
  928. <manager name="QueueReload" language="en_US">
  929. <synopsis>
  930. Reload a queue, queues, or any sub-section of a queue or queues.
  931. </synopsis>
  932. <syntax>
  933. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  934. <parameter name="Queue">
  935. <para>The name of the queue to take action on. If no queue name is specified, then all queues are affected.</para>
  936. </parameter>
  937. <parameter name="Members">
  938. <para>Whether to reload the queue's members.</para>
  939. <enumlist>
  940. <enum name="yes" />
  941. <enum name="no" />
  942. </enumlist>
  943. </parameter>
  944. <parameter name="Rules">
  945. <para>Whether to reload queuerules.conf</para>
  946. <enumlist>
  947. <enum name="yes" />
  948. <enum name="no" />
  949. </enumlist>
  950. </parameter>
  951. <parameter name="Parameters">
  952. <para>Whether to reload the other queue options.</para>
  953. <enumlist>
  954. <enum name="yes" />
  955. <enum name="no" />
  956. </enumlist>
  957. </parameter>
  958. </syntax>
  959. <description>
  960. </description>
  961. </manager>
  962. <manager name="QueueReset" language="en_US">
  963. <synopsis>
  964. Reset queue statistics.
  965. </synopsis>
  966. <syntax>
  967. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  968. <parameter name="Queue">
  969. <para>The name of the queue on which to reset statistics.</para>
  970. </parameter>
  971. </syntax>
  972. <description>
  973. <para>Reset the statistics for a queue.</para>
  974. </description>
  975. </manager>
  976. <managerEvent language="en_US" name="QueueMemberStatus">
  977. <managerEventInstance class="EVENT_FLAG_AGENT">
  978. <synopsis>Raised when a Queue member's status has changed.</synopsis>
  979. <syntax>
  980. <parameter name="Queue">
  981. <para>The name of the queue.</para>
  982. </parameter>
  983. <parameter name="MemberName">
  984. <para>The name of the queue member.</para>
  985. </parameter>
  986. <parameter name="Interface">
  987. <para>The queue member's channel technology or location.</para>
  988. </parameter>
  989. <parameter name="StateInterface">
  990. <para>Channel technology or location from which to read device state changes.</para>
  991. </parameter>
  992. <parameter name="Membership">
  993. <enumlist>
  994. <enum name="dynamic"/>
  995. <enum name="realtime"/>
  996. <enum name="static"/>
  997. </enumlist>
  998. </parameter>
  999. <parameter name="Penalty">
  1000. <para>The penalty associated with the queue member.</para>
  1001. </parameter>
  1002. <parameter name="CallsTaken">
  1003. <para>The number of calls this queue member has serviced.</para>
  1004. </parameter>
  1005. <parameter name="LastCall">
  1006. <para>The time this member last took a call, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
  1007. </parameter>
  1008. <parameter name="Status">
  1009. <para>The numeric device state status of the queue member.</para>
  1010. <enumlist>
  1011. <enum name="0"><para>AST_DEVICE_UNKNOWN</para></enum>
  1012. <enum name="1"><para>AST_DEVICE_NOT_INUSE</para></enum>
  1013. <enum name="2"><para>AST_DEVICE_INUSE</para></enum>
  1014. <enum name="3"><para>AST_DEVICE_BUSY</para></enum>
  1015. <enum name="4"><para>AST_DEVICE_INVALID</para></enum>
  1016. <enum name="5"><para>AST_DEVICE_UNAVAILABLE</para></enum>
  1017. <enum name="6"><para>AST_DEVICE_RINGING</para></enum>
  1018. <enum name="7"><para>AST_DEVICE_RINGINUSE</para></enum>
  1019. <enum name="8"><para>AST_DEVICE_ONHOLD</para></enum>
  1020. </enumlist>
  1021. </parameter>
  1022. <parameter name="Paused">
  1023. <enumlist>
  1024. <enum name="0"/>
  1025. <enum name="1"/>
  1026. </enumlist>
  1027. </parameter>
  1028. <parameter name="Ringinuse">
  1029. <enumlist>
  1030. <enum name="0"/>
  1031. <enum name="1"/>
  1032. </enumlist>
  1033. </parameter>
  1034. </syntax>
  1035. </managerEventInstance>
  1036. </managerEvent>
  1037. <managerEvent language="en_US" name="QueueMemberAdded">
  1038. <managerEventInstance class="EVENT_FLAG_AGENT">
  1039. <synopsis>Raised when a member is added to the queue.</synopsis>
  1040. <syntax>
  1041. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
  1042. </syntax>
  1043. <see-also>
  1044. <ref type="managerEvent">QueueMemberRemoved</ref>
  1045. <ref type="application">AddQueueMember</ref>
  1046. </see-also>
  1047. </managerEventInstance>
  1048. </managerEvent>
  1049. <managerEvent language="en_US" name="QueueMemberRemoved">
  1050. <managerEventInstance class="EVENT_FLAG_AGENT">
  1051. <synopsis>Raised when a member is removed from the queue.</synopsis>
  1052. <syntax>
  1053. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
  1054. </syntax>
  1055. <see-also>
  1056. <ref type="managerEvent">QueueMemberAdded</ref>
  1057. <ref type="application">RemoveQueueMember</ref>
  1058. </see-also>
  1059. </managerEventInstance>
  1060. </managerEvent>
  1061. <managerEvent language="en_US" name="QueueMemberPause">
  1062. <managerEventInstance class="EVENT_FLAG_AGENT">
  1063. <synopsis>Raised when a member is paused/unpaused in the queue.</synopsis>
  1064. <syntax>
  1065. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
  1066. <parameter name="Reason">
  1067. <para>The reason a member was paused.</para>
  1068. </parameter>
  1069. </syntax>
  1070. <see-also>
  1071. <ref type="application">PauseQueueMember</ref>
  1072. <ref type="application">UnPauseQueueMember</ref>
  1073. </see-also>
  1074. </managerEventInstance>
  1075. </managerEvent>
  1076. <managerEvent language="en_US" name="QueueMemberPenalty">
  1077. <managerEventInstance class="EVENT_FLAG_AGENT">
  1078. <synopsis>Raised when a member's penalty is changed.</synopsis>
  1079. <syntax>
  1080. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
  1081. </syntax>
  1082. <see-also>
  1083. <ref type="function">QUEUE_MEMBER</ref>
  1084. </see-also>
  1085. </managerEventInstance>
  1086. </managerEvent>
  1087. <managerEvent language="en_US" name="QueueMemberRinginuse">
  1088. <managerEventInstance class="EVENT_FLAG_AGENT">
  1089. <synopsis>Raised when a member's ringinuse setting is changed.</synopsis>
  1090. <syntax>
  1091. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
  1092. </syntax>
  1093. <see-also>
  1094. <ref type="function">QUEUE_MEMBER</ref>
  1095. </see-also>
  1096. </managerEventInstance>
  1097. </managerEvent>
  1098. <managerEvent language="en_US" name="QueueCallerJoin">
  1099. <managerEventInstance class="EVENT_FLAG_AGENT">
  1100. <synopsis>Raised when a caller joins a Queue.</synopsis>
  1101. <syntax>
  1102. <channel_snapshot/>
  1103. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
  1104. <parameter name="Position">
  1105. <para>This channel's current position in the queue.</para>
  1106. </parameter>
  1107. <parameter name="Count">
  1108. <para>The total number of channels in the queue.</para>
  1109. </parameter>
  1110. </syntax>
  1111. <see-also>
  1112. <ref type="managerEvent">QueueCallerLeave</ref>
  1113. <ref type="application">Queue</ref>
  1114. </see-also>
  1115. </managerEventInstance>
  1116. </managerEvent>
  1117. <managerEvent language="en_US" name="QueueCallerLeave">
  1118. <managerEventInstance class="EVENT_FLAG_AGENT">
  1119. <synopsis>Raised when a caller leaves a Queue.</synopsis>
  1120. <syntax>
  1121. <channel_snapshot/>
  1122. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
  1123. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Count'])" />
  1124. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Position'])" />
  1125. </syntax>
  1126. <see-also>
  1127. <ref type="managerEvent">QueueCallerJoin</ref>
  1128. </see-also>
  1129. </managerEventInstance>
  1130. </managerEvent>
  1131. <managerEvent language="en_US" name="QueueCallerAbandon">
  1132. <managerEventInstance class="EVENT_FLAG_AGENT">
  1133. <synopsis>Raised when a caller abandons the queue.</synopsis>
  1134. <syntax>
  1135. <channel_snapshot/>
  1136. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
  1137. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Position'])" />
  1138. <parameter name="OriginalPosition">
  1139. <para>The channel's original position in the queue.</para>
  1140. </parameter>
  1141. <parameter name="HoldTime">
  1142. <para>The time the channel was in the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
  1143. </parameter>
  1144. </syntax>
  1145. </managerEventInstance>
  1146. </managerEvent>
  1147. <managerEvent language="en_US" name="AgentCalled">
  1148. <managerEventInstance class="EVENT_FLAG_AGENT">
  1149. <synopsis>Raised when an queue member is notified of a caller in the queue.</synopsis>
  1150. <syntax>
  1151. <channel_snapshot/>
  1152. <channel_snapshot prefix="Dest"/>
  1153. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
  1154. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
  1155. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
  1156. </syntax>
  1157. <see-also>
  1158. <ref type="managerEvent">AgentRingNoAnswer</ref>
  1159. <ref type="managerEvent">AgentComplete</ref>
  1160. <ref type="managerEvent">AgentConnect</ref>
  1161. </see-also>
  1162. </managerEventInstance>
  1163. </managerEvent>
  1164. <managerEvent language="en_US" name="AgentRingNoAnswer">
  1165. <managerEventInstance class="EVENT_FLAG_AGENT">
  1166. <synopsis>Raised when a queue member is notified of a caller in the queue and fails to answer.</synopsis>
  1167. <syntax>
  1168. <channel_snapshot/>
  1169. <channel_snapshot prefix="Dest"/>
  1170. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
  1171. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
  1172. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
  1173. <parameter name="RingTime">
  1174. <para>The time the queue member was rung, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
  1175. </parameter>
  1176. </syntax>
  1177. <see-also>
  1178. <ref type="managerEvent">AgentCalled</ref>
  1179. </see-also>
  1180. </managerEventInstance>
  1181. </managerEvent>
  1182. <managerEvent language="en_US" name="AgentComplete">
  1183. <managerEventInstance class="EVENT_FLAG_AGENT">
  1184. <synopsis>Raised when a queue member has finished servicing a caller in the queue.</synopsis>
  1185. <syntax>
  1186. <channel_snapshot/>
  1187. <channel_snapshot prefix="Dest"/>
  1188. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
  1189. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
  1190. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
  1191. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerAbandon']/managerEventInstance/syntax/parameter[@name='HoldTime'])" />
  1192. <parameter name="TalkTime">
  1193. <para>The time the queue member talked with the caller in the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
  1194. </parameter>
  1195. <parameter name="Reason">
  1196. <enumlist>
  1197. <enum name="caller"/>
  1198. <enum name="agent"/>
  1199. <enum name="transfer"/>
  1200. </enumlist>
  1201. </parameter>
  1202. </syntax>
  1203. <see-also>
  1204. <ref type="managerEvent">AgentCalled</ref>
  1205. <ref type="managerEvent">AgentConnect</ref>
  1206. </see-also>
  1207. </managerEventInstance>
  1208. </managerEvent>
  1209. <managerEvent language="en_US" name="AgentDump">
  1210. <managerEventInstance class="EVENT_FLAG_AGENT">
  1211. <synopsis>Raised when a queue member hangs up on a caller in the queue.</synopsis>
  1212. <syntax>
  1213. <channel_snapshot/>
  1214. <channel_snapshot prefix="Dest"/>
  1215. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
  1216. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
  1217. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
  1218. </syntax>
  1219. <see-also>
  1220. <ref type="managerEvent">AgentCalled</ref>
  1221. <ref type="managerEvent">AgentConnect</ref>
  1222. </see-also>
  1223. </managerEventInstance>
  1224. </managerEvent>
  1225. <managerEvent language="en_US" name="AgentConnect">
  1226. <managerEventInstance class="EVENT_FLAG_AGENT">
  1227. <synopsis>Raised when a queue member answers and is bridged to a caller in the queue.</synopsis>
  1228. <syntax>
  1229. <channel_snapshot/>
  1230. <channel_snapshot prefix="Dest"/>
  1231. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
  1232. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
  1233. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
  1234. <xi:include xpointer="xpointer(/docs/managerEvent[@name='AgentRingNoAnswer']/managerEventInstance/syntax/parameter[@name='RingTime'])" />
  1235. <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerAbandon']/managerEventInstance/syntax/parameter[@name='HoldTime'])" />
  1236. </syntax>
  1237. <see-also>
  1238. <ref type="managerEvent">AgentCalled</ref>
  1239. <ref type="managerEvent">AgentComplete</ref>
  1240. <ref type="managerEvent">AgentDump</ref>
  1241. </see-also>
  1242. </managerEventInstance>
  1243. </managerEvent>
  1244. ***/
  1245. enum {
  1246. OPT_MARK_AS_ANSWERED = (1 << 0),
  1247. OPT_GO_ON = (1 << 1),
  1248. OPT_DATA_QUALITY = (1 << 2),
  1249. OPT_CALLEE_GO_ON = (1 << 3),
  1250. OPT_CALLEE_HANGUP = (1 << 4),
  1251. OPT_CALLER_HANGUP = (1 << 5),
  1252. OPT_IGNORE_CALL_FW = (1 << 6),
  1253. OPT_IGNORE_CONNECTEDLINE = (1 << 7),
  1254. OPT_CALLEE_PARK = (1 << 8),
  1255. OPT_CALLER_PARK = (1 << 9),
  1256. OPT_NO_RETRY = (1 << 10),
  1257. OPT_RINGING = (1 << 11),
  1258. OPT_RING_WHEN_RINGING = (1 << 12),
  1259. OPT_CALLEE_TRANSFER = (1 << 13),
  1260. OPT_CALLER_TRANSFER = (1 << 14),
  1261. OPT_CALLEE_AUTOMIXMON = (1 << 15),
  1262. OPT_CALLER_AUTOMIXMON = (1 << 16),
  1263. OPT_CALLEE_AUTOMON = (1 << 17),
  1264. OPT_CALLER_AUTOMON = (1 << 18),
  1265. };
  1266. enum {
  1267. OPT_ARG_CALLEE_GO_ON = 0,
  1268. /* note: this entry _MUST_ be the last one in the enum */
  1269. OPT_ARG_ARRAY_SIZE
  1270. };
  1271. AST_APP_OPTIONS(queue_exec_options, BEGIN_OPTIONS
  1272. AST_APP_OPTION('C', OPT_MARK_AS_ANSWERED),
  1273. AST_APP_OPTION('c', OPT_GO_ON),
  1274. AST_APP_OPTION('d', OPT_DATA_QUALITY),
  1275. AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
  1276. AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
  1277. AST_APP_OPTION('H', OPT_CALLER_HANGUP),
  1278. AST_APP_OPTION('i', OPT_IGNORE_CALL_FW),
  1279. AST_APP_OPTION('I', OPT_IGNORE_CONNECTEDLINE),
  1280. AST_APP_OPTION('k', OPT_CALLEE_PARK),
  1281. AST_APP_OPTION('K', OPT_CALLER_PARK),
  1282. AST_APP_OPTION('n', OPT_NO_RETRY),
  1283. AST_APP_OPTION('r', OPT_RINGING),
  1284. AST_APP_OPTION('R', OPT_RING_WHEN_RINGING),
  1285. AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
  1286. AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
  1287. AST_APP_OPTION('x', OPT_CALLEE_AUTOMIXMON),
  1288. AST_APP_OPTION('X', OPT_CALLER_AUTOMIXMON),
  1289. AST_APP_OPTION('w', OPT_CALLEE_AUTOMON),
  1290. AST_APP_OPTION('W', OPT_CALLER_AUTOMON),
  1291. END_OPTIONS);
  1292. enum {
  1293. QUEUE_STRATEGY_RINGALL = 0,
  1294. QUEUE_STRATEGY_LEASTRECENT,
  1295. QUEUE_STRATEGY_FEWESTCALLS,
  1296. QUEUE_STRATEGY_RANDOM,
  1297. QUEUE_STRATEGY_RRMEMORY,
  1298. QUEUE_STRATEGY_LINEAR,
  1299. QUEUE_STRATEGY_WRANDOM,
  1300. QUEUE_STRATEGY_RRORDERED,
  1301. };
  1302. enum {
  1303. QUEUE_AUTOPAUSE_OFF = 0,
  1304. QUEUE_AUTOPAUSE_ON,
  1305. QUEUE_AUTOPAUSE_ALL
  1306. };
  1307. enum queue_reload_mask {
  1308. QUEUE_RELOAD_PARAMETERS = (1 << 0),
  1309. QUEUE_RELOAD_MEMBER = (1 << 1),
  1310. QUEUE_RELOAD_RULES = (1 << 2),
  1311. QUEUE_RESET_STATS = (1 << 3),
  1312. };
  1313. static const struct strategy {
  1314. int strategy;
  1315. const char *name;
  1316. } strategies[] = {
  1317. { QUEUE_STRATEGY_RINGALL, "ringall" },
  1318. { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
  1319. { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
  1320. { QUEUE_STRATEGY_RANDOM, "random" },
  1321. { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
  1322. { QUEUE_STRATEGY_RRMEMORY, "roundrobin" },
  1323. { QUEUE_STRATEGY_LINEAR, "linear" },
  1324. { QUEUE_STRATEGY_WRANDOM, "wrandom"},
  1325. { QUEUE_STRATEGY_RRORDERED, "rrordered"},
  1326. };
  1327. static const struct autopause {
  1328. int autopause;
  1329. const char *name;
  1330. } autopausesmodes [] = {
  1331. { QUEUE_AUTOPAUSE_OFF,"no" },
  1332. { QUEUE_AUTOPAUSE_ON, "yes" },
  1333. { QUEUE_AUTOPAUSE_ALL,"all" },
  1334. };
  1335. #define DEFAULT_RETRY 5
  1336. #define DEFAULT_TIMEOUT 15
  1337. #define RECHECK 1 /*!< Recheck every second to see we we're at the top yet */
  1338. #define MAX_PERIODIC_ANNOUNCEMENTS 10 /*!< The maximum periodic announcements we can have */
  1339. /*!
  1340. * \brief The minimum number of seconds between position announcements.
  1341. * \note The default value of 15 provides backwards compatibility.
  1342. */
  1343. #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15
  1344. #define MAX_QUEUE_BUCKETS 53
  1345. #define RES_OKAY 0 /*!< Action completed */
  1346. #define RES_EXISTS (-1) /*!< Entry already exists */
  1347. #define RES_OUTOFMEMORY (-2) /*!< Out of memory */
  1348. #define RES_NOSUCHQUEUE (-3) /*!< No such queue */
  1349. #define RES_NOT_DYNAMIC (-4) /*!< Member is not dynamic */
  1350. static char *app = "Queue";
  1351. static char *app_aqm = "AddQueueMember" ;
  1352. static char *app_rqm = "RemoveQueueMember" ;
  1353. static char *app_pqm = "PauseQueueMember" ;
  1354. static char *app_upqm = "UnpauseQueueMember" ;
  1355. static char *app_ql = "QueueLog" ;
  1356. /*! \brief Persistent Members astdb family */
  1357. static const char * const pm_family = "Queue/PersistentMembers";
  1358. /*! \brief queues.conf [general] option */
  1359. static int queue_persistent_members = 0;
  1360. /*! \brief queues.conf per-queue weight option */
  1361. static int use_weight = 0;
  1362. /*! \brief queues.conf [general] option */
  1363. static int autofill_default = 1;
  1364. /*! \brief queues.conf [general] option */
  1365. static int montype_default = 0;
  1366. /*! \brief queues.conf [general] option */
  1367. static int shared_lastcall = 1;
  1368. /*! \brief queuesrules.conf [general] option */
  1369. static int realtime_rules = 0;
  1370. /*! \brief Subscription to device state change messages */
  1371. static struct stasis_subscription *device_state_sub;
  1372. /*! \brief queues.conf [general] option */
  1373. static int update_cdr = 0;
  1374. /*! \brief queues.conf [general] option */
  1375. static int negative_penalty_invalid = 0;
  1376. /*! \brief queues.conf [general] option */
  1377. static int log_membername_as_agent = 0;
  1378. /*! \brief name of the ringinuse field in the realtime database */
  1379. static char *realtime_ringinuse_field;
  1380. enum queue_result {
  1381. QUEUE_UNKNOWN = 0,
  1382. QUEUE_TIMEOUT = 1,
  1383. QUEUE_JOINEMPTY = 2,
  1384. QUEUE_LEAVEEMPTY = 3,
  1385. QUEUE_JOINUNAVAIL = 4,
  1386. QUEUE_LEAVEUNAVAIL = 5,
  1387. QUEUE_FULL = 6,
  1388. QUEUE_CONTINUE = 7,
  1389. };
  1390. static const struct {
  1391. enum queue_result id;
  1392. char *text;
  1393. } queue_results[] = {
  1394. { QUEUE_UNKNOWN, "UNKNOWN" },
  1395. { QUEUE_TIMEOUT, "TIMEOUT" },
  1396. { QUEUE_JOINEMPTY,"JOINEMPTY" },
  1397. { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
  1398. { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
  1399. { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
  1400. { QUEUE_FULL, "FULL" },
  1401. { QUEUE_CONTINUE, "CONTINUE" },
  1402. };
  1403. enum queue_timeout_priority {
  1404. TIMEOUT_PRIORITY_APP,
  1405. TIMEOUT_PRIORITY_CONF,
  1406. };
  1407. /*! \brief We define a custom "local user" structure because we
  1408. * use it not only for keeping track of what is in use but
  1409. * also for keeping track of who we're dialing.
  1410. *
  1411. * There are two "links" defined in this structure, q_next and call_next.
  1412. * q_next links ALL defined callattempt structures into a linked list. call_next is
  1413. * a link which allows for a subset of the callattempts to be traversed. This subset
  1414. * is used in wait_for_answer so that irrelevant callattempts are not traversed. This
  1415. * also is helpful so that queue logs are always accurate in the case where a call to
  1416. * a member times out, especially if using the ringall strategy.
  1417. */
  1418. struct callattempt {
  1419. struct callattempt *q_next;
  1420. struct callattempt *call_next;
  1421. struct ast_channel *chan;
  1422. char interface[256]; /*!< An Asterisk dial string (not a channel name) */
  1423. int metric;
  1424. time_t lastcall;
  1425. struct call_queue *lastqueue;
  1426. struct member *member;
  1427. /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
  1428. struct ast_party_connected_line connected;
  1429. /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
  1430. unsigned int pending_connected_update:1;
  1431. /*! TRUE if the connected line update is blocked. */
  1432. unsigned int block_connected_update:1;
  1433. /*! TRUE if caller id is not available for connected line */
  1434. unsigned int dial_callerid_absent:1;
  1435. /*! TRUE if the call is still active */
  1436. unsigned int stillgoing:1;
  1437. struct ast_aoc_decoded *aoc_s_rate_list;
  1438. };
  1439. struct queue_ent {
  1440. struct call_queue *parent; /*!< What queue is our parent */
  1441. char moh[MAX_MUSICCLASS]; /*!< Name of musiconhold to be used */
  1442. char announce[PATH_MAX]; /*!< Announcement to play for member when call is answered */
  1443. char context[AST_MAX_CONTEXT]; /*!< Context when user exits queue */
  1444. char digits[AST_MAX_EXTENSION]; /*!< Digits entered while in queue */
  1445. int valid_digits; /*!< Digits entered correspond to valid extension. Exited */
  1446. int pos; /*!< Where we are in the queue */
  1447. int prio; /*!< Our priority */
  1448. int last_pos_said; /*!< Last position we told the user */
  1449. int ring_when_ringing; /*!< Should we only use ring indication when a channel is ringing? */
  1450. time_t last_periodic_announce_time; /*!< The last time we played a periodic announcement */
  1451. int last_periodic_announce_sound; /*!< The last periodic announcement we made */
  1452. time_t last_pos; /*!< Last time we told the user their position */
  1453. int opos; /*!< Where we started in the queue */
  1454. int handled; /*!< Whether our call was handled */
  1455. int pending; /*!< Non-zero if we are attempting to call a member */
  1456. int max_penalty; /*!< Limit the members that can take this call to this penalty or lower */
  1457. int min_penalty; /*!< Limit the members that can take this call to this penalty or higher */
  1458. int linpos; /*!< If using linear strategy, what position are we at? */
  1459. int linwrapped; /*!< Is the linpos wrapped? */
  1460. time_t start; /*!< When we started holding */
  1461. time_t expire; /*!< When this entry should expire (time out of queue) */
  1462. int cancel_answered_elsewhere; /*!< Whether we should force the CAE flag on this call (C) option*/
  1463. struct ast_channel *chan; /*!< Our channel */
  1464. AST_LIST_HEAD_NOLOCK(,penalty_rule) qe_rules; /*!< Local copy of the queue's penalty rules */
  1465. struct penalty_rule *pr; /*!< Pointer to the next penalty rule to implement */
  1466. struct queue_ent *next; /*!< The next queue entry */
  1467. };
  1468. struct member {
  1469. char interface[AST_CHANNEL_NAME]; /*!< Technology/Location to dial to reach this member*/
  1470. char state_exten[AST_MAX_EXTENSION]; /*!< Extension to get state from (if using hint) */
  1471. char state_context[AST_MAX_CONTEXT]; /*!< Context to use when getting state (if using hint) */
  1472. char state_interface[AST_CHANNEL_NAME]; /*!< Technology/Location from which to read devicestate changes */
  1473. char membername[80]; /*!< Member name to use in queue logs */
  1474. int penalty; /*!< Are we a last resort? */
  1475. int calls; /*!< Number of calls serviced by this member */
  1476. int dynamic; /*!< Are we dynamically added? */
  1477. int realtime; /*!< Is this member realtime? */
  1478. int status; /*!< Status of queue member */
  1479. int paused; /*!< Are we paused (not accepting calls)? */
  1480. int queuepos; /*!< In what order (pertains to certain strategies) should this member be called? */
  1481. time_t lastcall; /*!< When last successful call was hungup */
  1482. struct call_queue *lastqueue; /*!< Last queue we received a call */
  1483. unsigned int dead:1; /*!< Used to detect members deleted in realtime */
  1484. unsigned int delme:1; /*!< Flag to delete entry on reload */
  1485. unsigned int call_pending:1; /*!< TRUE if the Q is attempting to place a call to the member. */
  1486. char rt_uniqueid[80]; /*!< Unique id of realtime member entry */
  1487. unsigned int ringinuse:1; /*!< Flag to ring queue members even if their status is 'inuse' */
  1488. };
  1489. enum empty_conditions {
  1490. QUEUE_EMPTY_PENALTY = (1 << 0),
  1491. QUEUE_EMPTY_PAUSED = (1 << 1),
  1492. QUEUE_EMPTY_INUSE = (1 << 2),
  1493. QUEUE_EMPTY_RINGING = (1 << 3),
  1494. QUEUE_EMPTY_UNAVAILABLE = (1 << 4),
  1495. QUEUE_EMPTY_INVALID = (1 << 5),
  1496. QUEUE_EMPTY_UNKNOWN = (1 << 6),
  1497. QUEUE_EMPTY_WRAPUP = (1 << 7),
  1498. };
  1499. enum member_properties {
  1500. MEMBER_PENALTY = 0,
  1501. MEMBER_RINGINUSE = 1,
  1502. };
  1503. /* values used in multi-bit flags in call_queue */
  1504. #define ANNOUNCEHOLDTIME_ALWAYS 1
  1505. #define ANNOUNCEHOLDTIME_ONCE 2
  1506. #define QUEUE_EVENT_VARIABLES 3
  1507. struct penalty_rule {
  1508. int time; /*!< Number of seconds that need to pass before applying this rule */
  1509. int max_value; /*!< The amount specified in the penalty rule for max penalty */
  1510. int min_value; /*!< The amount specified in the penalty rule for min penalty */
  1511. int max_relative; /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
  1512. int min_relative; /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
  1513. AST_LIST_ENTRY(penalty_rule) list; /*!< Next penalty_rule */
  1514. };
  1515. #define ANNOUNCEPOSITION_YES 1 /*!< We announce position */
  1516. #define ANNOUNCEPOSITION_NO 2 /*!< We don't announce position */
  1517. #define ANNOUNCEPOSITION_MORE_THAN 3 /*!< We say "Currently there are more than <limit>" */
  1518. #define ANNOUNCEPOSITION_LIMIT 4 /*!< We not announce position more than <limit> */
  1519. struct call_queue {
  1520. AST_DECLARE_STRING_FIELDS(
  1521. /*! Queue name */
  1522. AST_STRING_FIELD(name);
  1523. /*! Music on Hold class */
  1524. AST_STRING_FIELD(moh);
  1525. /*! Announcement to play when call is answered */
  1526. AST_STRING_FIELD(announce);
  1527. /*! Exit context */
  1528. AST_STRING_FIELD(context);
  1529. /*! Macro to run upon member connection */
  1530. AST_STRING_FIELD(membermacro);
  1531. /*! Gosub to run upon member connection */
  1532. AST_STRING_FIELD(membergosub);
  1533. /*! Default rule to use if none specified in call to Queue() */
  1534. AST_STRING_FIELD(defaultrule);
  1535. /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
  1536. AST_STRING_FIELD(sound_next);
  1537. /*! Sound file: "There are currently" (def. queue-thereare) */
  1538. AST_STRING_FIELD(sound_thereare);
  1539. /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
  1540. AST_STRING_FIELD(sound_calls);
  1541. /*! Sound file: "Currently there are more than" (def. queue-quantity1) */
  1542. AST_STRING_FIELD(queue_quantity1);
  1543. /*! Sound file: "callers waiting to speak with a representative" (def. queue-quantity2) */
  1544. AST_STRING_FIELD(queue_quantity2);
  1545. /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
  1546. AST_STRING_FIELD(sound_holdtime);
  1547. /*! Sound file: "minutes." (def. queue-minutes) */
  1548. AST_STRING_FIELD(sound_minutes);
  1549. /*! Sound file: "minute." (def. queue-minute) */
  1550. AST_STRING_FIELD(sound_minute);
  1551. /*! Sound file: "seconds." (def. queue-seconds) */
  1552. AST_STRING_FIELD(sound_seconds);
  1553. /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
  1554. AST_STRING_FIELD(sound_thanks);
  1555. /*! Sound file: Custom announce for caller, no default */
  1556. AST_STRING_FIELD(sound_callerannounce);
  1557. /*! Sound file: "Hold time" (def. queue-reporthold) */
  1558. AST_STRING_FIELD(sound_reporthold);
  1559. );
  1560. /*! Sound files: Custom announce, no default */
  1561. struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
  1562. unsigned int dead:1;
  1563. unsigned int ringinuse:1;
  1564. unsigned int announce_to_first_user:1; /*!< Whether or not we announce to the first user in a queue */
  1565. unsigned int setinterfacevar:1;
  1566. unsigned int setqueuevar:1;
  1567. unsigned int setqueueentryvar:1;
  1568. unsigned int reportholdtime:1;
  1569. unsigned int wrapped:1;
  1570. unsigned int timeoutrestart:1;
  1571. unsigned int announceholdtime:2;
  1572. unsigned int announceposition:3;
  1573. int strategy:4;
  1574. unsigned int realtime:1;
  1575. unsigned int found:1;
  1576. unsigned int relativeperiodicannounce:1;
  1577. unsigned int autopausebusy:1;
  1578. unsigned int autopauseunavail:1;
  1579. enum empty_conditions joinempty;
  1580. enum empty_conditions leavewhenempty;
  1581. int announcepositionlimit; /*!< How many positions we announce? */
  1582. int announcefrequency; /*!< How often to announce their position */
  1583. int minannouncefrequency; /*!< The minimum number of seconds between position announcements (def. 15) */
  1584. int periodicannouncefrequency; /*!< How often to play periodic announcement */
  1585. int numperiodicannounce; /*!< The number of periodic announcements configured */
  1586. int randomperiodicannounce; /*!< Are periodic announcments randomly chosen */
  1587. int roundingseconds; /*!< How many seconds do we round to? */
  1588. int holdtime; /*!< Current avg holdtime, based on an exponential average */
  1589. int talktime; /*!< Current avg talktime, based on the same exponential average */
  1590. int callscompleted; /*!< Number of queue calls completed */
  1591. int callsabandoned; /*!< Number of queue calls abandoned */
  1592. int servicelevel; /*!< seconds setting for servicelevel*/
  1593. int callscompletedinsl; /*!< Number of calls answered with servicelevel*/
  1594. char monfmt[8]; /*!< Format to use when recording calls */
  1595. int montype; /*!< Monitor type Monitor vs. MixMonitor */
  1596. int count; /*!< How many entries */
  1597. int maxlen; /*!< Max number of entries */
  1598. int wrapuptime; /*!< Wrapup Time */
  1599. int penaltymemberslimit; /*!< Disregard penalty when queue has fewer than this many members */
  1600. int retry; /*!< Retry calling everyone after this amount of time */
  1601. int timeout; /*!< How long to wait for an answer */
  1602. int weight; /*!< Respective weight */
  1603. int autopause; /*!< Auto pause queue members if they fail to answer */
  1604. int autopausedelay; /*!< Delay auto pause for autopausedelay seconds since last call */
  1605. int timeoutpriority; /*!< Do we allow a fraction of the timeout to occur for a ring? */
  1606. /* Queue strategy things */
  1607. int rrpos; /*!< Round Robin - position */
  1608. int memberdelay; /*!< Seconds to delay connecting member to caller */
  1609. int autofill; /*!< Ignore the head call status and ring an available agent */
  1610. struct ao2_container *members; /*!< Head of the list of members */
  1611. struct queue_ent *head; /*!< Head of the list of callers */
  1612. AST_LIST_ENTRY(call_queue) list; /*!< Next call queue */
  1613. AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
  1614. };
  1615. struct rule_list {
  1616. char name[80];
  1617. AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
  1618. AST_LIST_ENTRY(rule_list) list;
  1619. };
  1620. static AST_LIST_HEAD_STATIC(rule_lists, rule_list);
  1621. static struct ao2_container *queues;
  1622. static void update_realtime_members(struct call_queue *q);
  1623. static struct member *interface_exists(struct call_queue *q, const char *interface);
  1624. static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
  1625. static struct member *find_member_by_queuename_and_interface(const char *queuename, const char *interface);
  1626. /*! \brief sets the QUEUESTATUS channel variable */
  1627. static void set_queue_result(struct ast_channel *chan, enum queue_result res)
  1628. {
  1629. int i;
  1630. for (i = 0; i < ARRAY_LEN(queue_results); i++) {
  1631. if (queue_results[i].id == res) {
  1632. pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
  1633. return;
  1634. }
  1635. }
  1636. }
  1637. static const char *int2strat(int strategy)
  1638. {
  1639. int x;
  1640. for (x = 0; x < ARRAY_LEN(strategies); x++) {
  1641. if (strategy == strategies[x].strategy) {
  1642. return strategies[x].name;
  1643. }
  1644. }
  1645. return "<unknown>";
  1646. }
  1647. static int strat2int(const char *strategy)
  1648. {
  1649. int x;
  1650. for (x = 0; x < ARRAY_LEN(strategies); x++) {
  1651. if (!strcasecmp(strategy, strategies[x].name)) {
  1652. return strategies[x].strategy;
  1653. }
  1654. }
  1655. return -1;
  1656. }
  1657. static int autopause2int(const char *autopause)
  1658. {
  1659. int x;
  1660. /*This 'double check' that default value is OFF */
  1661. if (ast_strlen_zero(autopause)) {
  1662. return QUEUE_AUTOPAUSE_OFF;
  1663. }
  1664. /*This 'double check' is to ensure old values works */
  1665. if(ast_true(autopause)) {
  1666. return QUEUE_AUTOPAUSE_ON;
  1667. }
  1668. for (x = 0; x < ARRAY_LEN(autopausesmodes); x++) {
  1669. if (!strcasecmp(autopause, autopausesmodes[x].name)) {
  1670. return autopausesmodes[x].autopause;
  1671. }
  1672. }
  1673. /*This 'double check' that default value is OFF */
  1674. return QUEUE_AUTOPAUSE_OFF;
  1675. }
  1676. static int queue_hash_cb(const void *obj, const int flags)
  1677. {
  1678. const struct call_queue *q = obj;
  1679. return ast_str_case_hash(q->name);
  1680. }
  1681. static int queue_cmp_cb(void *obj, void *arg, int flags)
  1682. {
  1683. struct call_queue *q = obj, *q2 = arg;
  1684. return !strcasecmp(q->name, q2->name) ? CMP_MATCH | CMP_STOP : 0;
  1685. }
  1686. /*! \internal
  1687. * \brief ao2_callback, Decreases queuepos of all followers with a queuepos greater than arg.
  1688. * \param obj the member being acted on
  1689. * \param arg pointer to an integer containing the position value that was removed and requires reduction for anything above
  1690. */
  1691. static int queue_member_decrement_followers(void *obj, void *arg, int flag)
  1692. {
  1693. struct member *mem = obj;
  1694. int *decrement_followers_after = arg;
  1695. if (mem->queuepos > *decrement_followers_after) {
  1696. mem->queuepos--;
  1697. }
  1698. return 0;
  1699. }
  1700. /*! \internal
  1701. * \brief ao2_callback, finds members in a queue marked for deletion and in a cascading fashion runs queue_member_decrement_followers
  1702. * on them. This callback should always be ran before performing mass unlinking of delmarked members from queues.
  1703. * \param obj member being acted on
  1704. * \param arg pointer to the queue members are being removed from
  1705. */
  1706. static int queue_delme_members_decrement_followers(void *obj, void *arg, int flag)
  1707. {
  1708. struct member *mem = obj;
  1709. struct call_queue *queue = arg;
  1710. int rrpos = mem->queuepos;
  1711. if (mem->delme) {
  1712. ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &rrpos);
  1713. }
  1714. return 0;
  1715. }
  1716. /*! \internal
  1717. * \brief Use this to decrement followers during removal of a member
  1718. * \param queue which queue the member is being removed from
  1719. * \param mem which member is being removed from the queue
  1720. */
  1721. static void queue_member_follower_removal(struct call_queue *queue, struct member *mem)
  1722. {
  1723. int pos = mem->queuepos;
  1724. /* If the position being removed is less than the current place in the queue, reduce the queue position by one so that we don't skip the member
  1725. * who would have been next otherwise. */
  1726. if (pos < queue->rrpos) {
  1727. queue->rrpos--;
  1728. }
  1729. ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &pos);
  1730. }
  1731. #ifdef REF_DEBUG
  1732. #define queue_ref(q) _queue_ref(q, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
  1733. #define queue_unref(q) _queue_unref(q, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
  1734. #define queue_t_ref(q, tag) _queue_ref(q, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
  1735. #define queue_t_unref(q, tag) _queue_unref(q, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
  1736. #define queues_t_link(c, q, tag) __ao2_link_debug(c, q, 0, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
  1737. #define queues_t_unlink(c, q, tag) __ao2_unlink_debug(c, q, 0, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
  1738. static inline struct call_queue *_queue_ref(struct call_queue *q, const char *tag, const char *file, int line, const char *filename)
  1739. {
  1740. __ao2_ref_debug(q, 1, tag, file, line, filename);
  1741. return q;
  1742. }
  1743. static inline struct call_queue *_queue_unref(struct call_queue *q, const char *tag, const char *file, int line, const char *filename)
  1744. {
  1745. if (q) {
  1746. __ao2_ref_debug(q, -1, tag, file, line, filename);
  1747. }
  1748. return NULL;
  1749. }
  1750. #else
  1751. #define queue_t_ref(q, tag) queue_ref(q)
  1752. #define queue_t_unref(q, tag) queue_unref(q)
  1753. #define queues_t_link(c, q, tag) ao2_t_link(c, q, tag)
  1754. #define queues_t_unlink(c, q, tag) ao2_t_unlink(c, q, tag)
  1755. static inline struct call_queue *queue_ref(struct call_queue *q)
  1756. {
  1757. ao2_ref(q, 1);
  1758. return q;
  1759. }
  1760. static inline struct call_queue *queue_unref(struct call_queue *q)
  1761. {
  1762. if (q) {
  1763. ao2_ref(q, -1);
  1764. }
  1765. return NULL;
  1766. }
  1767. #endif
  1768. /*! \brief Set variables of queue */
  1769. static void set_queue_variables(struct call_queue *q, struct ast_channel *chan)
  1770. {
  1771. char interfacevar[256]="";
  1772. float sl = 0;
  1773. ao2_lock(q);
  1774. if (q->setqueuevar) {
  1775. sl = 0;
  1776. if (q->callscompleted > 0) {
  1777. sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
  1778. }
  1779. snprintf(interfacevar, sizeof(interfacevar),
  1780. "QUEUENAME=%s,QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
  1781. q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned, q->servicelevel, sl);
  1782. ao2_unlock(q);
  1783. pbx_builtin_setvar_multiple(chan, interfacevar);
  1784. } else {
  1785. ao2_unlock(q);
  1786. }
  1787. }
  1788. /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
  1789. static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
  1790. {
  1791. struct queue_ent *cur;
  1792. if (!q || !new)
  1793. return;
  1794. if (prev) {
  1795. cur = prev->next;
  1796. prev->next = new;
  1797. } else {
  1798. cur = q->head;
  1799. q->head = new;
  1800. }
  1801. new->next = cur;
  1802. /* every queue_ent must have a reference to it's parent call_queue, this
  1803. * reference does not go away until the end of the queue_ent's life, meaning
  1804. * that even when the queue_ent leaves the call_queue this ref must remain. */
  1805. queue_ref(q);
  1806. new->parent = q;
  1807. new->pos = ++(*pos);
  1808. new->opos = *pos;
  1809. }
  1810. static struct ast_manager_event_blob *queue_channel_to_ami(const char *type, struct stasis_message *message)
  1811. {
  1812. struct ast_channel_blob *obj = stasis_message_data(message);
  1813. RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
  1814. RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
  1815. channel_string = ast_manager_build_channel_state_string(obj->snapshot);
  1816. event_string = ast_manager_str_from_json_object(obj->blob, NULL);
  1817. if (!channel_string || !event_string) {
  1818. return NULL;
  1819. }
  1820. return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
  1821. "%s"
  1822. "%s",
  1823. ast_str_buffer(channel_string),
  1824. ast_str_buffer(event_string));
  1825. }
  1826. static struct ast_manager_event_blob *queue_caller_join_to_ami(struct stasis_message *message)
  1827. {
  1828. return queue_channel_to_ami("QueueCallerJoin", message);
  1829. }
  1830. static struct ast_manager_event_blob *queue_caller_leave_to_ami(struct stasis_message *message)
  1831. {
  1832. return queue_channel_to_ami("QueueCallerLeave", message);
  1833. }
  1834. static struct ast_manager_event_blob *queue_caller_abandon_to_ami(struct stasis_message *message)
  1835. {
  1836. return queue_channel_to_ami("QueueCallerAbandon", message);
  1837. }
  1838. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_join_type,
  1839. .to_ami = queue_caller_join_to_ami,
  1840. );
  1841. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_leave_type,
  1842. .to_ami = queue_caller_leave_to_ami,
  1843. );
  1844. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_abandon_type,
  1845. .to_ami = queue_caller_abandon_to_ami,
  1846. );
  1847. static struct ast_manager_event_blob *queue_member_to_ami(const char *type, struct stasis_message *message)
  1848. {
  1849. struct ast_json_payload *payload = stasis_message_data(message);
  1850. RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
  1851. event_string = ast_manager_str_from_json_object(payload->json, NULL);
  1852. if (!event_string) {
  1853. return NULL;
  1854. }
  1855. return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
  1856. "%s",
  1857. ast_str_buffer(event_string));
  1858. }
  1859. static struct ast_manager_event_blob *queue_member_status_to_ami(struct stasis_message *message)
  1860. {
  1861. return queue_member_to_ami("QueueMemberStatus", message);
  1862. }
  1863. static struct ast_manager_event_blob *queue_member_added_to_ami(struct stasis_message *message)
  1864. {
  1865. return queue_member_to_ami("QueueMemberAdded", message);
  1866. }
  1867. static struct ast_manager_event_blob *queue_member_removed_to_ami(struct stasis_message *message)
  1868. {
  1869. return queue_member_to_ami("QueueMemberRemoved", message);
  1870. }
  1871. static struct ast_manager_event_blob *queue_member_pause_to_ami(struct stasis_message *message)
  1872. {
  1873. return queue_member_to_ami("QueueMemberPause", message);
  1874. }
  1875. static struct ast_manager_event_blob *queue_member_penalty_to_ami(struct stasis_message *message)
  1876. {
  1877. return queue_member_to_ami("QueueMemberPenalty", message);
  1878. }
  1879. static struct ast_manager_event_blob *queue_member_ringinuse_to_ami(struct stasis_message *message)
  1880. {
  1881. return queue_member_to_ami("QueueMemberRinginuse", message);
  1882. }
  1883. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_status_type,
  1884. .to_ami = queue_member_status_to_ami,
  1885. );
  1886. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_added_type,
  1887. .to_ami = queue_member_added_to_ami,
  1888. );
  1889. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_removed_type,
  1890. .to_ami = queue_member_removed_to_ami,
  1891. );
  1892. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_pause_type,
  1893. .to_ami = queue_member_pause_to_ami,
  1894. );
  1895. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_penalty_type,
  1896. .to_ami = queue_member_penalty_to_ami,
  1897. );
  1898. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_ringinuse_type,
  1899. .to_ami = queue_member_ringinuse_to_ami,
  1900. );
  1901. static struct ast_manager_event_blob *queue_multi_channel_to_ami(const char *type, struct stasis_message *message)
  1902. {
  1903. struct ast_multi_channel_blob *obj = stasis_message_data(message);
  1904. struct ast_channel_snapshot *caller;
  1905. struct ast_channel_snapshot *agent;
  1906. RAII_VAR(struct ast_str *, caller_event_string, NULL, ast_free);
  1907. RAII_VAR(struct ast_str *, agent_event_string, NULL, ast_free);
  1908. RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
  1909. caller = ast_multi_channel_blob_get_channel(obj, "caller");
  1910. if (caller) {
  1911. caller_event_string = ast_manager_build_channel_state_string(caller);
  1912. if (!caller_event_string) {
  1913. ast_log(LOG_NOTICE, "No caller event string, bailing\n");
  1914. return NULL;
  1915. }
  1916. }
  1917. agent = ast_multi_channel_blob_get_channel(obj, "agent");
  1918. if (agent) {
  1919. agent_event_string = ast_manager_build_channel_state_string_prefix(agent, "Dest");
  1920. if (!agent_event_string) {
  1921. ast_log(LOG_NOTICE, "No agent event string, bailing\n");
  1922. return NULL;
  1923. }
  1924. }
  1925. event_string = ast_manager_str_from_json_object(ast_multi_channel_blob_get_json(obj), NULL);
  1926. if (!event_string) {
  1927. return NULL;
  1928. }
  1929. return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
  1930. "%s"
  1931. "%s"
  1932. "%s",
  1933. caller_event_string ? ast_str_buffer(caller_event_string) : "",
  1934. agent_event_string ? ast_str_buffer(agent_event_string) : "",
  1935. ast_str_buffer(event_string));
  1936. }
  1937. static struct ast_manager_event_blob *queue_agent_called_to_ami(struct stasis_message *message)
  1938. {
  1939. return queue_multi_channel_to_ami("AgentCalled", message);
  1940. }
  1941. static struct ast_manager_event_blob *queue_agent_connect_to_ami(struct stasis_message *message)
  1942. {
  1943. return queue_multi_channel_to_ami("AgentConnect", message);
  1944. }
  1945. static struct ast_manager_event_blob *queue_agent_complete_to_ami(struct stasis_message *message)
  1946. {
  1947. return queue_multi_channel_to_ami("AgentComplete", message);
  1948. }
  1949. static struct ast_manager_event_blob *queue_agent_dump_to_ami(struct stasis_message *message)
  1950. {
  1951. return queue_multi_channel_to_ami("AgentDump", message);
  1952. }
  1953. static struct ast_manager_event_blob *queue_agent_ringnoanswer_to_ami(struct stasis_message *message)
  1954. {
  1955. return queue_multi_channel_to_ami("AgentRingNoAnswer", message);
  1956. }
  1957. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_called_type,
  1958. .to_ami = queue_agent_called_to_ami,
  1959. );
  1960. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_connect_type,
  1961. .to_ami = queue_agent_connect_to_ami,
  1962. );
  1963. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_complete_type,
  1964. .to_ami = queue_agent_complete_to_ami,
  1965. );
  1966. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_dump_type,
  1967. .to_ami = queue_agent_dump_to_ami,
  1968. );
  1969. STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_ringnoanswer_type,
  1970. .to_ami = queue_agent_ringnoanswer_to_ami,
  1971. );
  1972. static void queue_publish_multi_channel_snapshot_blob(struct stasis_topic *topic,
  1973. struct ast_channel_snapshot *caller_snapshot,
  1974. struct ast_channel_snapshot *agent_snapshot,
  1975. struct stasis_message_type *type, struct ast_json *blob)
  1976. {
  1977. RAII_VAR(struct ast_multi_channel_blob *, payload, NULL, ao2_cleanup);
  1978. RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
  1979. if (!type) {
  1980. return;
  1981. }
  1982. payload = ast_multi_channel_blob_create(blob);
  1983. if (!payload) {
  1984. return;
  1985. }
  1986. ast_multi_channel_blob_add_channel(payload, "caller", caller_snapshot);
  1987. if (agent_snapshot) {
  1988. ast_multi_channel_blob_add_channel(payload, "agent", agent_snapshot);
  1989. }
  1990. msg = stasis_message_create(type, payload);
  1991. if (!msg) {
  1992. return;
  1993. }
  1994. stasis_publish(topic, msg);
  1995. }
  1996. static void queue_publish_multi_channel_blob(struct ast_channel *caller, struct ast_channel *agent,
  1997. struct stasis_message_type *type, struct ast_json *blob)
  1998. {
  1999. RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
  2000. RAII_VAR(struct ast_channel_snapshot *, agent_snapshot, NULL, ao2_cleanup);
  2001. ast_channel_lock(caller);
  2002. caller_snapshot = ast_channel_snapshot_create(caller);
  2003. ast_channel_unlock(caller);
  2004. ast_channel_lock(agent);
  2005. agent_snapshot = ast_channel_snapshot_create(agent);
  2006. ast_channel_unlock(agent);
  2007. if (!caller_snapshot || !agent_snapshot) {
  2008. return;
  2009. }
  2010. queue_publish_multi_channel_snapshot_blob(ast_channel_topic(caller), caller_snapshot,
  2011. agent_snapshot, type, blob);
  2012. }
  2013. /*!
  2014. * \internal
  2015. * \brief Publish the member blob.
  2016. * \since 12.0.0
  2017. *
  2018. * \param type Stasis message type to publish.
  2019. * \param blob The information being published.
  2020. *
  2021. * \note The json blob reference is passed to this function.
  2022. *
  2023. * \return Nothing
  2024. */
  2025. static void queue_publish_member_blob(struct stasis_message_type *type, struct ast_json *blob)
  2026. {
  2027. RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
  2028. RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
  2029. if (!blob || !type) {
  2030. return;
  2031. }
  2032. payload = ast_json_payload_create(blob);
  2033. ast_json_unref(blob);
  2034. if (!payload) {
  2035. return;
  2036. }
  2037. msg = stasis_message_create(type, payload);
  2038. if (!msg) {
  2039. return;
  2040. }
  2041. stasis_publish(ast_manager_get_topic(), msg);
  2042. }
  2043. static struct ast_json *queue_member_blob_create(struct call_queue *q, struct member *mem)
  2044. {
  2045. return ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: i, s: i, s: i, s: i, s: i, s: i}",
  2046. "Queue", q->name,
  2047. "MemberName", mem->membername,
  2048. "Interface", mem->interface,
  2049. "StateInterface", mem->state_interface,
  2050. "Membership", (mem->dynamic ? "dynamic" : (mem->realtime ? "realtime" : "static")),
  2051. "Penalty", mem->penalty,
  2052. "CallsTaken", mem->calls,
  2053. "LastCall", (int)mem->lastcall,
  2054. "Status", mem->status,
  2055. "Paused", mem->paused,
  2056. "Ringinuse", mem->ringinuse);
  2057. }
  2058. /*! \brief Check if members are available
  2059. *
  2060. * This function checks to see if members are available to be called. If any member
  2061. * is available, the function immediately returns 0. If no members are available,
  2062. * then -1 is returned.
  2063. */
  2064. static int get_member_status(struct call_queue *q, int max_penalty, int min_penalty, enum empty_conditions conditions, int devstate)
  2065. {
  2066. struct member *member;
  2067. struct ao2_iterator mem_iter;
  2068. ao2_lock(q);
  2069. mem_iter = ao2_iterator_init(q->members, 0);
  2070. for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
  2071. if ((max_penalty != INT_MAX && member->penalty > max_penalty) || (min_penalty != INT_MAX && member->penalty < min_penalty)) {
  2072. if (conditions & QUEUE_EMPTY_PENALTY) {
  2073. ast_debug(4, "%s is unavailable because his penalty is not between %d and %d\n", member->membername, min_penalty, max_penalty);
  2074. continue;
  2075. }
  2076. }
  2077. switch (devstate ? ast_device_state(member->state_interface) : member->status) {
  2078. case AST_DEVICE_INVALID:
  2079. if (conditions & QUEUE_EMPTY_INVALID) {
  2080. ast_debug(4, "%s is unavailable because his device state is 'invalid'\n", member->membername);
  2081. break;
  2082. }
  2083. goto default_case;
  2084. case AST_DEVICE_UNAVAILABLE:
  2085. if (conditions & QUEUE_EMPTY_UNAVAILABLE) {
  2086. ast_debug(4, "%s is unavailable because his device state is 'unavailable'\n", member->membername);
  2087. break;
  2088. }
  2089. goto default_case;
  2090. case AST_DEVICE_INUSE:
  2091. if (conditions & QUEUE_EMPTY_INUSE) {
  2092. ast_debug(4, "%s is unavailable because his device state is 'inuse'\n", member->membername);
  2093. break;
  2094. }
  2095. goto default_case;
  2096. case AST_DEVICE_RINGING:
  2097. if (conditions & QUEUE_EMPTY_RINGING) {
  2098. ast_debug(4, "%s is unavailable because his device state is 'ringing'\n", member->membername);
  2099. break;
  2100. }
  2101. goto default_case;
  2102. case AST_DEVICE_UNKNOWN:
  2103. if (conditions & QUEUE_EMPTY_UNKNOWN) {
  2104. ast_debug(4, "%s is unavailable because his device state is 'unknown'\n", member->membername);
  2105. break;
  2106. }
  2107. /* Fall-through */
  2108. default:
  2109. default_case:
  2110. if (member->paused && (conditions & QUEUE_EMPTY_PAUSED)) {
  2111. ast_debug(4, "%s is unavailable because he is paused'\n", member->membername);
  2112. break;
  2113. } else if ((conditions & QUEUE_EMPTY_WRAPUP) && member->lastcall && q->wrapuptime && (time(NULL) - q->wrapuptime < member->lastcall)) {
  2114. ast_debug(4, "%s is unavailable because it has only been %d seconds since his last call (wrapup time is %d)\n", member->membername, (int) (time(NULL) - member->lastcall), q->wrapuptime);
  2115. break;
  2116. } else {
  2117. ao2_ref(member, -1);
  2118. ao2_iterator_destroy(&mem_iter);
  2119. ao2_unlock(q);
  2120. ast_debug(4, "%s is available.\n", member->membername);
  2121. return 0;
  2122. }
  2123. break;
  2124. }
  2125. }
  2126. ao2_iterator_destroy(&mem_iter);
  2127. ao2_unlock(q);
  2128. if (!devstate && (conditions & QUEUE_EMPTY_RINGING)) {
  2129. /* member state still may be RINGING due to lag in event message - check again with device state */
  2130. return get_member_status(q, max_penalty, min_penalty, conditions, 1);
  2131. }
  2132. return -1;
  2133. }
  2134. /*! \brief set a member's status based on device state of that member's state_interface.
  2135. *
  2136. * Lock interface list find sc, iterate through each queues queue_member list for member to
  2137. * update state inside queues
  2138. */
  2139. static void update_status(struct call_queue *q, struct member *m, const int status)
  2140. {
  2141. m->status = status;
  2142. queue_publish_member_blob(queue_member_status_type(), queue_member_blob_create(q, m));
  2143. }
  2144. /*!
  2145. * \internal
  2146. * \brief Determine if a queue member is available
  2147. * \retval 1 if the member is available
  2148. * \retval 0 if the member is not available
  2149. */
  2150. static int is_member_available(struct call_queue *q, struct member *mem)
  2151. {
  2152. int available = 0;
  2153. switch (mem->status) {
  2154. case AST_DEVICE_INVALID:
  2155. case AST_DEVICE_UNAVAILABLE:
  2156. break;
  2157. case AST_DEVICE_INUSE:
  2158. case AST_DEVICE_BUSY:
  2159. case AST_DEVICE_RINGING:
  2160. case AST_DEVICE_RINGINUSE:
  2161. case AST_DEVICE_ONHOLD:
  2162. if (!mem->ringinuse) {
  2163. break;
  2164. }
  2165. /* else fall through */
  2166. case AST_DEVICE_NOT_INUSE:
  2167. case AST_DEVICE_UNKNOWN:
  2168. if (!mem->paused) {
  2169. available = 1;
  2170. }
  2171. break;
  2172. }
  2173. /* Let wrapuptimes override device state availability */
  2174. if (mem->lastcall && q->wrapuptime && (time(NULL) - q->wrapuptime < mem->lastcall)) {
  2175. available = 0;
  2176. }
  2177. return available;
  2178. }
  2179. /*! \brief set a member's status based on device state of that member's interface*/
  2180. static void device_state_cb(void *unused, struct stasis_subscription *sub, struct stasis_message *msg)
  2181. {
  2182. struct ao2_iterator miter, qiter;
  2183. struct ast_device_state_message *dev_state;
  2184. struct member *m;
  2185. struct call_queue *q;
  2186. char interface[80], *slash_pos;
  2187. int found = 0; /* Found this member in any queue */
  2188. int found_member; /* Found this member in this queue */
  2189. int avail = 0; /* Found an available member in this queue */
  2190. if (ast_device_state_message_type() != stasis_message_type(msg)) {
  2191. return;
  2192. }
  2193. dev_state = stasis_message_data(msg);
  2194. if (dev_state->eid) {
  2195. /* ignore non-aggregate states */
  2196. return;
  2197. }
  2198. qiter = ao2_iterator_init(queues, 0);
  2199. while ((q = ao2_t_iterator_next(&qiter, "Iterate over queues"))) {
  2200. ao2_lock(q);
  2201. avail = 0;
  2202. found_member = 0;
  2203. miter = ao2_iterator_init(q->members, 0);
  2204. for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
  2205. if (!found_member) {
  2206. ast_copy_string(interface, m->state_interface, sizeof(interface));
  2207. if ((slash_pos = strchr(interface, '/'))) {
  2208. if (!strncasecmp(interface, "Local/", 6) && (slash_pos = strchr(slash_pos + 1, '/'))) {
  2209. *slash_pos = '\0';
  2210. }
  2211. }
  2212. if (!strcasecmp(interface, dev_state->device)) {
  2213. found_member = 1;
  2214. update_status(q, m, dev_state->state);
  2215. }
  2216. }
  2217. /* check every member until we find one NOT_INUSE */
  2218. if (!avail) {
  2219. avail = is_member_available(q, m);
  2220. }
  2221. if (avail && found_member) {
  2222. /* early exit as we've found an available member and the member of interest */
  2223. ao2_ref(m, -1);
  2224. break;
  2225. }
  2226. }
  2227. if (found_member) {
  2228. found = 1;
  2229. if (avail) {
  2230. ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
  2231. } else {
  2232. ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
  2233. }
  2234. }
  2235. ao2_iterator_destroy(&miter);
  2236. ao2_unlock(q);
  2237. queue_t_unref(q, "Done with iterator");
  2238. }
  2239. ao2_iterator_destroy(&qiter);
  2240. if (found) {
  2241. ast_debug(1, "Device '%s' changed to state '%u' (%s)\n",
  2242. dev_state->device,
  2243. dev_state->state,
  2244. ast_devstate2str(dev_state->state));
  2245. } else {
  2246. ast_debug(3, "Device '%s' changed to state '%u' (%s) but we don't care because they're not a member of any queue.\n",
  2247. dev_state->device,
  2248. dev_state->state,
  2249. ast_devstate2str(dev_state->state));
  2250. }
  2251. return;
  2252. }
  2253. /*! \brief Helper function which converts from extension state to device state values */
  2254. static int extensionstate2devicestate(int state)
  2255. {
  2256. switch (state) {
  2257. case AST_EXTENSION_NOT_INUSE:
  2258. state = AST_DEVICE_NOT_INUSE;
  2259. break;
  2260. case AST_EXTENSION_INUSE:
  2261. state = AST_DEVICE_INUSE;
  2262. break;
  2263. case AST_EXTENSION_BUSY:
  2264. state = AST_DEVICE_BUSY;
  2265. break;
  2266. case AST_EXTENSION_RINGING:
  2267. state = AST_DEVICE_RINGING;
  2268. break;
  2269. case AST_EXTENSION_ONHOLD:
  2270. state = AST_DEVICE_ONHOLD;
  2271. break;
  2272. case AST_EXTENSION_UNAVAILABLE:
  2273. state = AST_DEVICE_UNAVAILABLE;
  2274. break;
  2275. case AST_EXTENSION_REMOVED:
  2276. case AST_EXTENSION_DEACTIVATED:
  2277. default:
  2278. state = AST_DEVICE_INVALID;
  2279. break;
  2280. }
  2281. return state;
  2282. }
  2283. static int extension_state_cb(char *context, char *exten, struct ast_state_cb_info *info, void *data)
  2284. {
  2285. struct ao2_iterator miter, qiter;
  2286. struct member *m;
  2287. struct call_queue *q;
  2288. int state = info->exten_state;
  2289. int found = 0, device_state = extensionstate2devicestate(state);
  2290. /* only interested in extension state updates involving device states */
  2291. if (info->reason != AST_HINT_UPDATE_DEVICE) {
  2292. return 0;
  2293. }
  2294. qiter = ao2_iterator_init(queues, 0);
  2295. while ((q = ao2_t_iterator_next(&qiter, "Iterate through queues"))) {
  2296. ao2_lock(q);
  2297. miter = ao2_iterator_init(q->members, 0);
  2298. for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
  2299. if (!strcmp(m->state_context, context) && !strcmp(m->state_exten, exten)) {
  2300. update_status(q, m, device_state);
  2301. ao2_ref(m, -1);
  2302. found = 1;
  2303. break;
  2304. }
  2305. }
  2306. ao2_iterator_destroy(&miter);
  2307. ao2_unlock(q);
  2308. queue_t_unref(q, "Done with iterator");
  2309. }
  2310. ao2_iterator_destroy(&qiter);
  2311. if (found) {
  2312. ast_debug(1, "Extension '%s@%s' changed to state '%d' (%s)\n", exten, context, device_state, ast_devstate2str(device_state));
  2313. } else {
  2314. ast_debug(3, "Extension '%s@%s' changed to state '%d' (%s) but we don't care because they're not a member of any queue.\n",
  2315. exten, context, device_state, ast_devstate2str(device_state));
  2316. }
  2317. return 0;
  2318. }
  2319. /*! \brief Return the current state of a member */
  2320. static int get_queue_member_status(struct member *cur)
  2321. {
  2322. return ast_strlen_zero(cur->state_exten) ? ast_device_state(cur->state_interface) : extensionstate2devicestate(ast_extension_state(NULL, cur->state_context, cur->state_exten));
  2323. }
  2324. /*! \brief allocate space for new queue member and set fields based on parameters passed */
  2325. static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused, const char *state_interface, int ringinuse)
  2326. {
  2327. struct member *cur;
  2328. if ((cur = ao2_alloc(sizeof(*cur), NULL))) {
  2329. cur->ringinuse = ringinuse;
  2330. cur->penalty = penalty;
  2331. cur->paused = paused;
  2332. ast_copy_string(cur->interface, interface, sizeof(cur->interface));
  2333. if (!ast_strlen_zero(state_interface)) {
  2334. ast_copy_string(cur->state_interface, state_interface, sizeof(cur->state_interface));
  2335. } else {
  2336. ast_copy_string(cur->state_interface, interface, sizeof(cur->state_interface));
  2337. }
  2338. if (!ast_strlen_zero(membername)) {
  2339. ast_copy_string(cur->membername, membername, sizeof(cur->membername));
  2340. } else {
  2341. ast_copy_string(cur->membername, interface, sizeof(cur->membername));
  2342. }
  2343. if (!strchr(cur->interface, '/')) {
  2344. ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
  2345. }
  2346. if (!strncmp(cur->state_interface, "hint:", 5)) {
  2347. char *tmp = ast_strdupa(cur->state_interface), *context = tmp;
  2348. char *exten = strsep(&context, "@") + 5;
  2349. ast_copy_string(cur->state_exten, exten, sizeof(cur->state_exten));
  2350. ast_copy_string(cur->state_context, S_OR(context, "default"), sizeof(cur->state_context));
  2351. }
  2352. cur->status = get_queue_member_status(cur);
  2353. }
  2354. return cur;
  2355. }
  2356. static int compress_char(const char c)
  2357. {
  2358. if (c < 32) {
  2359. return 0;
  2360. } else if (c > 96) {
  2361. return c - 64;
  2362. }
  2363. return c - 32;
  2364. }
  2365. static int member_hash_fn(const void *obj, const int flags)
  2366. {
  2367. const struct member *mem = obj;
  2368. const char *interface = (flags & OBJ_KEY) ? obj : mem->interface;
  2369. const char *chname = strchr(interface, '/');
  2370. int ret = 0, i;
  2371. if (!chname) {
  2372. chname = interface;
  2373. }
  2374. for (i = 0; i < 5 && chname[i]; i++) {
  2375. ret += compress_char(chname[i]) << (i * 6);
  2376. }
  2377. return ret;
  2378. }
  2379. static int member_cmp_fn(void *obj1, void *obj2, int flags)
  2380. {
  2381. struct member *mem1 = obj1;
  2382. struct member *mem2 = obj2;
  2383. const char *interface = (flags & OBJ_KEY) ? obj2 : mem2->interface;
  2384. return strcasecmp(mem1->interface, interface) ? 0 : CMP_MATCH | CMP_STOP;
  2385. }
  2386. /*!
  2387. * \brief Initialize Queue default values.
  2388. * \note the queue's lock must be held before executing this function
  2389. */
  2390. static void init_queue(struct call_queue *q)
  2391. {
  2392. int i;
  2393. struct penalty_rule *pr_iter;
  2394. q->dead = 0;
  2395. q->retry = DEFAULT_RETRY;
  2396. q->timeout = DEFAULT_TIMEOUT;
  2397. q->maxlen = 0;
  2398. q->announcefrequency = 0;
  2399. q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
  2400. q->announceholdtime = 1;
  2401. q->announcepositionlimit = 10; /* Default 10 positions */
  2402. q->announceposition = ANNOUNCEPOSITION_YES; /* Default yes */
  2403. q->roundingseconds = 0; /* Default - don't announce seconds */
  2404. q->servicelevel = 0;
  2405. q->ringinuse = 1;
  2406. q->announce_to_first_user = 0;
  2407. q->setinterfacevar = 0;
  2408. q->setqueuevar = 0;
  2409. q->setqueueentryvar = 0;
  2410. q->autofill = autofill_default;
  2411. q->montype = montype_default;
  2412. q->monfmt[0] = '\0';
  2413. q->reportholdtime = 0;
  2414. q->wrapuptime = 0;
  2415. q->penaltymemberslimit = 0;
  2416. q->joinempty = 0;
  2417. q->leavewhenempty = 0;
  2418. q->memberdelay = 0;
  2419. q->weight = 0;
  2420. q->timeoutrestart = 0;
  2421. q->periodicannouncefrequency = 0;
  2422. q->randomperiodicannounce = 0;
  2423. q->numperiodicannounce = 0;
  2424. q->autopause = QUEUE_AUTOPAUSE_OFF;
  2425. q->timeoutpriority = TIMEOUT_PRIORITY_APP;
  2426. q->autopausedelay = 0;
  2427. if (!q->members) {
  2428. if (q->strategy == QUEUE_STRATEGY_LINEAR || q->strategy == QUEUE_STRATEGY_RRORDERED) {
  2429. /* linear strategy depends on order, so we have to place all members in a single bucket */
  2430. q->members = ao2_container_alloc(1, member_hash_fn, member_cmp_fn);
  2431. } else {
  2432. q->members = ao2_container_alloc(37, member_hash_fn, member_cmp_fn);
  2433. }
  2434. }
  2435. q->found = 1;
  2436. ast_string_field_set(q, sound_next, "queue-youarenext");
  2437. ast_string_field_set(q, sound_thereare, "queue-thereare");
  2438. ast_string_field_set(q, sound_calls, "queue-callswaiting");
  2439. ast_string_field_set(q, queue_quantity1, "queue-quantity1");
  2440. ast_string_field_set(q, queue_quantity2, "queue-quantity2");
  2441. ast_string_field_set(q, sound_holdtime, "queue-holdtime");
  2442. ast_string_field_set(q, sound_minutes, "queue-minutes");
  2443. ast_string_field_set(q, sound_minute, "queue-minute");
  2444. ast_string_field_set(q, sound_seconds, "queue-seconds");
  2445. ast_string_field_set(q, sound_thanks, "queue-thankyou");
  2446. ast_string_field_set(q, sound_reporthold, "queue-reporthold");
  2447. if (!q->sound_periodicannounce[0]) {
  2448. q->sound_periodicannounce[0] = ast_str_create(32);
  2449. }
  2450. if (q->sound_periodicannounce[0]) {
  2451. ast_str_set(&q->sound_periodicannounce[0], 0, "queue-periodic-announce");
  2452. }
  2453. for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
  2454. if (q->sound_periodicannounce[i]) {
  2455. ast_str_set(&q->sound_periodicannounce[i], 0, "%s", "");
  2456. }
  2457. }
  2458. while ((pr_iter = AST_LIST_REMOVE_HEAD(&q->rules,list))) {
  2459. ast_free(pr_iter);
  2460. }
  2461. /* On restart assume no members are available.
  2462. * The queue_avail hint is a boolean state to indicate whether a member is available or not.
  2463. *
  2464. * This seems counter intuitive, but is required to light a BLF
  2465. * AST_DEVICE_INUSE indicates no members are available.
  2466. * AST_DEVICE_NOT_INUSE indicates a member is available.
  2467. */
  2468. ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
  2469. }
  2470. static void clear_queue(struct call_queue *q)
  2471. {
  2472. q->holdtime = 0;
  2473. q->callscompleted = 0;
  2474. q->callsabandoned = 0;
  2475. q->callscompletedinsl = 0;
  2476. q->talktime = 0;
  2477. if (q->members) {
  2478. struct member *mem;
  2479. struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
  2480. while ((mem = ao2_iterator_next(&mem_iter))) {
  2481. mem->calls = 0;
  2482. mem->lastcall = 0;
  2483. ao2_ref(mem, -1);
  2484. }
  2485. ao2_iterator_destroy(&mem_iter);
  2486. }
  2487. }
  2488. /*!
  2489. * \brief Change queue penalty by adding rule.
  2490. *
  2491. * Check rule for errors with time or fomatting, see if rule is relative to rest
  2492. * of queue, iterate list of rules to find correct insertion point, insert and return.
  2493. * \retval -1 on failure
  2494. * \retval 0 on success
  2495. * \note Call this with the rule_lists locked
  2496. */
  2497. static int insert_penaltychange(const char *list_name, const char *content, const int linenum)
  2498. {
  2499. char *timestr, *maxstr, *minstr, *contentdup;
  2500. struct penalty_rule *rule = NULL, *rule_iter;
  2501. struct rule_list *rl_iter;
  2502. int penaltychangetime, inserted = 0;
  2503. if (!(rule = ast_calloc(1, sizeof(*rule)))) {
  2504. return -1;
  2505. }
  2506. contentdup = ast_strdupa(content);
  2507. if (!(maxstr = strchr(contentdup, ','))) {
  2508. ast_log(LOG_WARNING, "Improperly formatted penaltychange rule at line %d. Ignoring.\n", linenum);
  2509. ast_free(rule);
  2510. return -1;
  2511. }
  2512. *maxstr++ = '\0';
  2513. timestr = contentdup;
  2514. if ((penaltychangetime = atoi(timestr)) < 0) {
  2515. ast_log(LOG_WARNING, "Improper time parameter specified for penaltychange rule at line %d. Ignoring.\n", linenum);
  2516. ast_free(rule);
  2517. return -1;
  2518. }
  2519. rule->time = penaltychangetime;
  2520. if ((minstr = strchr(maxstr,','))) {
  2521. *minstr++ = '\0';
  2522. }
  2523. /* The last check will evaluate true if either no penalty change is indicated for a given rule
  2524. * OR if a min penalty change is indicated but no max penalty change is */
  2525. if (*maxstr == '+' || *maxstr == '-' || *maxstr == '\0') {
  2526. rule->max_relative = 1;
  2527. }
  2528. rule->max_value = atoi(maxstr);
  2529. if (!ast_strlen_zero(minstr)) {
  2530. if (*minstr == '+' || *minstr == '-') {
  2531. rule->min_relative = 1;
  2532. }
  2533. rule->min_value = atoi(minstr);
  2534. } else { /*there was no minimum specified, so assume this means no change*/
  2535. rule->min_relative = 1;
  2536. }
  2537. /*We have the rule made, now we need to insert it where it belongs*/
  2538. AST_LIST_TRAVERSE(&rule_lists, rl_iter, list){
  2539. if (strcasecmp(rl_iter->name, list_name)) {
  2540. continue;
  2541. }
  2542. AST_LIST_TRAVERSE_SAFE_BEGIN(&rl_iter->rules, rule_iter, list) {
  2543. if (rule->time < rule_iter->time) {
  2544. AST_LIST_INSERT_BEFORE_CURRENT(rule, list);
  2545. inserted = 1;
  2546. break;
  2547. }
  2548. }
  2549. AST_LIST_TRAVERSE_SAFE_END;
  2550. if (!inserted) {
  2551. AST_LIST_INSERT_TAIL(&rl_iter->rules, rule, list);
  2552. inserted = 1;
  2553. }
  2554. break;
  2555. }
  2556. if (!inserted) {
  2557. ast_log(LOG_WARNING, "Unknown rule list name %s; ignoring.\n", list_name);
  2558. ast_free(rule);
  2559. return -1;
  2560. }
  2561. return 0;
  2562. }
  2563. /*!
  2564. * \brief Load queue rules from realtime.
  2565. *
  2566. * Check rule for errors with time or fomatting, see if rule is relative to rest
  2567. * of queue, iterate list of rules to find correct insertion point, insert and return.
  2568. * \retval -1 on failure
  2569. * \retval 0 on success
  2570. * \note Call this with the rule_lists locked
  2571. */
  2572. static int load_realtime_rules(void)
  2573. {
  2574. struct ast_config *cfg;
  2575. struct rule_list *rl_iter, *new_rl;
  2576. struct penalty_rule *pr_iter;
  2577. char *rulecat = NULL;
  2578. if (!ast_check_realtime("queue_rules")) {
  2579. ast_log(LOG_WARNING, "Missing \"queue_rules\" in extconfig.conf\n");
  2580. return 0;
  2581. }
  2582. if (!(cfg = ast_load_realtime_multientry("queue_rules", "rule_name LIKE", "%", SENTINEL))) {
  2583. ast_log(LOG_WARNING, "Failed to load queue rules from realtime\n");
  2584. return 0;
  2585. }
  2586. while ((rulecat = ast_category_browse(cfg, rulecat)) && !ast_strlen_zero(rulecat)) {
  2587. const char *timestr, *maxstr, *minstr;
  2588. int penaltychangetime, rule_exists = 0, inserted = 0;
  2589. int max_penalty = 0, min_penalty = 0, min_relative = 0, max_relative = 0;
  2590. struct penalty_rule *new_penalty_rule = NULL;
  2591. AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
  2592. if (!(strcasecmp(rl_iter->name, rulecat))) {
  2593. rule_exists = 1;
  2594. new_rl = rl_iter;
  2595. break;
  2596. }
  2597. }
  2598. if (!rule_exists) {
  2599. if (!(new_rl = ast_calloc(1, sizeof(*new_rl)))) {
  2600. ast_config_destroy(cfg);
  2601. return -1;
  2602. }
  2603. ast_copy_string(new_rl->name, rulecat, sizeof(new_rl->name));
  2604. AST_LIST_INSERT_TAIL(&rule_lists, new_rl, list);
  2605. }
  2606. timestr = ast_variable_retrieve(cfg, rulecat, "time");
  2607. if (!(timestr) || sscanf(timestr, "%30d", &penaltychangetime) != 1) {
  2608. ast_log(LOG_NOTICE, "Failed to parse time (%s) for one of the %s rules, skipping it\n",
  2609. (ast_strlen_zero(timestr) ? "invalid value" : timestr), rulecat);
  2610. continue;
  2611. }
  2612. if (!(new_penalty_rule = ast_calloc(1, sizeof(*new_penalty_rule)))) {
  2613. ast_config_destroy(cfg);
  2614. return -1;
  2615. }
  2616. if (!(maxstr = ast_variable_retrieve(cfg, rulecat, "max_penalty")) ||
  2617. ast_strlen_zero(maxstr) || sscanf(maxstr, "%30d", &max_penalty) != 1) {
  2618. max_penalty = 0;
  2619. max_relative = 1;
  2620. } else {
  2621. if (*maxstr == '+' || *maxstr == '-') {
  2622. max_relative = 1;
  2623. }
  2624. }
  2625. if (!(minstr = ast_variable_retrieve(cfg, rulecat, "min_penalty")) ||
  2626. ast_strlen_zero(minstr) || sscanf(minstr, "%30d", &min_penalty) != 1) {
  2627. min_penalty = 0;
  2628. min_relative = 1;
  2629. } else {
  2630. if (*minstr == '+' || *minstr == '-') {
  2631. min_relative = 1;
  2632. }
  2633. }
  2634. new_penalty_rule->time = penaltychangetime;
  2635. new_penalty_rule->max_relative = max_relative;
  2636. new_penalty_rule->max_value = max_penalty;
  2637. new_penalty_rule->min_relative = min_relative;
  2638. new_penalty_rule->min_value = min_penalty;
  2639. AST_LIST_TRAVERSE_SAFE_BEGIN(&new_rl->rules, pr_iter, list) {
  2640. if (new_penalty_rule->time < pr_iter->time) {
  2641. AST_LIST_INSERT_BEFORE_CURRENT(new_penalty_rule, list);
  2642. inserted = 1;
  2643. }
  2644. }
  2645. AST_LIST_TRAVERSE_SAFE_END;
  2646. if (!inserted) {
  2647. AST_LIST_INSERT_TAIL(&new_rl->rules, new_penalty_rule, list);
  2648. }
  2649. }
  2650. ast_config_destroy(cfg);
  2651. return 0;
  2652. }
  2653. static void parse_empty_options(const char *value, enum empty_conditions *empty, int joinempty)
  2654. {
  2655. char *value_copy = ast_strdupa(value);
  2656. char *option = NULL;
  2657. while ((option = strsep(&value_copy, ","))) {
  2658. if (!strcasecmp(option, "paused")) {
  2659. *empty |= QUEUE_EMPTY_PAUSED;
  2660. } else if (!strcasecmp(option, "penalty")) {
  2661. *empty |= QUEUE_EMPTY_PENALTY;
  2662. } else if (!strcasecmp(option, "inuse")) {
  2663. *empty |= QUEUE_EMPTY_INUSE;
  2664. } else if (!strcasecmp(option, "ringing")) {
  2665. *empty |= QUEUE_EMPTY_RINGING;
  2666. } else if (!strcasecmp(option, "invalid")) {
  2667. *empty |= QUEUE_EMPTY_INVALID;
  2668. } else if (!strcasecmp(option, "wrapup")) {
  2669. *empty |= QUEUE_EMPTY_WRAPUP;
  2670. } else if (!strcasecmp(option, "unavailable")) {
  2671. *empty |= QUEUE_EMPTY_UNAVAILABLE;
  2672. } else if (!strcasecmp(option, "unknown")) {
  2673. *empty |= QUEUE_EMPTY_UNKNOWN;
  2674. } else if (!strcasecmp(option, "loose")) {
  2675. *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID);
  2676. } else if (!strcasecmp(option, "strict")) {
  2677. *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED | QUEUE_EMPTY_UNAVAILABLE);
  2678. } else if ((ast_false(option) && joinempty) || (ast_true(option) && !joinempty)) {
  2679. *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED);
  2680. } else if ((ast_false(option) && !joinempty) || (ast_true(option) && joinempty)) {
  2681. *empty = 0;
  2682. } else {
  2683. ast_log(LOG_WARNING, "Unknown option %s for '%s'\n", option, joinempty ? "joinempty" : "leavewhenempty");
  2684. }
  2685. }
  2686. }
  2687. /*! \brief Configure a queue parameter.
  2688. *
  2689. * The failunknown flag is set for config files (and static realtime) to show
  2690. * errors for unknown parameters. It is cleared for dynamic realtime to allow
  2691. * extra fields in the tables.
  2692. * \note For error reporting, line number is passed for .conf static configuration,
  2693. * for Realtime queues, linenum is -1.
  2694. */
  2695. static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
  2696. {
  2697. if (!strcasecmp(param, "musicclass") ||
  2698. !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
  2699. ast_string_field_set(q, moh, val);
  2700. } else if (!strcasecmp(param, "announce")) {
  2701. ast_string_field_set(q, announce, val);
  2702. } else if (!strcasecmp(param, "context")) {
  2703. ast_string_field_set(q, context, val);
  2704. } else if (!strcasecmp(param, "timeout")) {
  2705. q->timeout = atoi(val);
  2706. if (q->timeout < 0) {
  2707. q->timeout = DEFAULT_TIMEOUT;
  2708. }
  2709. } else if (!strcasecmp(param, "ringinuse")) {
  2710. q->ringinuse = ast_true(val);
  2711. } else if (!strcasecmp(param, "setinterfacevar")) {
  2712. q->setinterfacevar = ast_true(val);
  2713. } else if (!strcasecmp(param, "setqueuevar")) {
  2714. q->setqueuevar = ast_true(val);
  2715. } else if (!strcasecmp(param, "setqueueentryvar")) {
  2716. q->setqueueentryvar = ast_true(val);
  2717. } else if (!strcasecmp(param, "monitor-format")) {
  2718. ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
  2719. } else if (!strcasecmp(param, "membermacro")) {
  2720. ast_string_field_set(q, membermacro, val);
  2721. } else if (!strcasecmp(param, "membergosub")) {
  2722. ast_string_field_set(q, membergosub, val);
  2723. } else if (!strcasecmp(param, "queue-youarenext")) {
  2724. ast_string_field_set(q, sound_next, val);
  2725. } else if (!strcasecmp(param, "queue-thereare")) {
  2726. ast_string_field_set(q, sound_thereare, val);
  2727. } else if (!strcasecmp(param, "queue-callswaiting")) {
  2728. ast_string_field_set(q, sound_calls, val);
  2729. } else if (!strcasecmp(param, "queue-quantity1")) {
  2730. ast_string_field_set(q, queue_quantity1, val);
  2731. } else if (!strcasecmp(param, "queue-quantity2")) {
  2732. ast_string_field_set(q, queue_quantity2, val);
  2733. } else if (!strcasecmp(param, "queue-holdtime")) {
  2734. ast_string_field_set(q, sound_holdtime, val);
  2735. } else if (!strcasecmp(param, "queue-minutes")) {
  2736. ast_string_field_set(q, sound_minutes, val);
  2737. } else if (!strcasecmp(param, "queue-minute")) {
  2738. ast_string_field_set(q, sound_minute, val);
  2739. } else if (!strcasecmp(param, "queue-seconds")) {
  2740. ast_string_field_set(q, sound_seconds, val);
  2741. } else if (!strcasecmp(param, "queue-thankyou")) {
  2742. ast_string_field_set(q, sound_thanks, val);
  2743. } else if (!strcasecmp(param, "queue-callerannounce")) {
  2744. ast_string_field_set(q, sound_callerannounce, val);
  2745. } else if (!strcasecmp(param, "queue-reporthold")) {
  2746. ast_string_field_set(q, sound_reporthold, val);
  2747. } else if (!strcasecmp(param, "announce-frequency")) {
  2748. q->announcefrequency = atoi(val);
  2749. } else if (!strcasecmp(param, "announce-to-first-user")) {
  2750. q->announce_to_first_user = ast_true(val);
  2751. } else if (!strcasecmp(param, "min-announce-frequency")) {
  2752. q->minannouncefrequency = atoi(val);
  2753. ast_debug(1, "%s=%s for queue '%s'\n", param, val, q->name);
  2754. } else if (!strcasecmp(param, "announce-round-seconds")) {
  2755. q->roundingseconds = atoi(val);
  2756. /* Rounding to any other values just doesn't make sense... */
  2757. if (!(q->roundingseconds == 0 || q->roundingseconds == 5 || q->roundingseconds == 10
  2758. || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
  2759. if (linenum >= 0) {
  2760. ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
  2761. "using 0 instead for queue '%s' at line %d of queues.conf\n",
  2762. val, param, q->name, linenum);
  2763. } else {
  2764. ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
  2765. "using 0 instead for queue '%s'\n", val, param, q->name);
  2766. }
  2767. q->roundingseconds=0;
  2768. }
  2769. } else if (!strcasecmp(param, "announce-holdtime")) {
  2770. if (!strcasecmp(val, "once")) {
  2771. q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
  2772. } else if (ast_true(val)) {
  2773. q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
  2774. } else {
  2775. q->announceholdtime = 0;
  2776. }
  2777. } else if (!strcasecmp(param, "announce-position")) {
  2778. if (!strcasecmp(val, "limit")) {
  2779. q->announceposition = ANNOUNCEPOSITION_LIMIT;
  2780. } else if (!strcasecmp(val, "more")) {
  2781. q->announceposition = ANNOUNCEPOSITION_MORE_THAN;
  2782. } else if (ast_true(val)) {
  2783. q->announceposition = ANNOUNCEPOSITION_YES;
  2784. } else {
  2785. q->announceposition = ANNOUNCEPOSITION_NO;
  2786. }
  2787. } else if (!strcasecmp(param, "announce-position-limit")) {
  2788. q->announcepositionlimit = atoi(val);
  2789. } else if (!strcasecmp(param, "periodic-announce")) {
  2790. if (strchr(val, ',')) {
  2791. char *s, *buf = ast_strdupa(val);
  2792. unsigned int i = 0;
  2793. while ((s = strsep(&buf, ",|"))) {
  2794. if (!q->sound_periodicannounce[i]) {
  2795. q->sound_periodicannounce[i] = ast_str_create(16);
  2796. }
  2797. ast_str_set(&q->sound_periodicannounce[i], 0, "%s", s);
  2798. i++;
  2799. if (i == MAX_PERIODIC_ANNOUNCEMENTS) {
  2800. break;
  2801. }
  2802. }
  2803. q->numperiodicannounce = i;
  2804. } else {
  2805. ast_str_set(&q->sound_periodicannounce[0], 0, "%s", val);
  2806. q->numperiodicannounce = 1;
  2807. }
  2808. } else if (!strcasecmp(param, "periodic-announce-frequency")) {
  2809. q->periodicannouncefrequency = atoi(val);
  2810. } else if (!strcasecmp(param, "relative-periodic-announce")) {
  2811. q->relativeperiodicannounce = ast_true(val);
  2812. } else if (!strcasecmp(param, "random-periodic-announce")) {
  2813. q->randomperiodicannounce = ast_true(val);
  2814. } else if (!strcasecmp(param, "retry")) {
  2815. q->retry = atoi(val);
  2816. if (q->retry <= 0) {
  2817. q->retry = DEFAULT_RETRY;
  2818. }
  2819. } else if (!strcasecmp(param, "wrapuptime")) {
  2820. q->wrapuptime = atoi(val);
  2821. } else if (!strcasecmp(param, "penaltymemberslimit")) {
  2822. if ((sscanf(val, "%10d", &q->penaltymemberslimit) != 1)) {
  2823. q->penaltymemberslimit = 0;
  2824. }
  2825. } else if (!strcasecmp(param, "autofill")) {
  2826. q->autofill = ast_true(val);
  2827. } else if (!strcasecmp(param, "monitor-type")) {
  2828. if (!strcasecmp(val, "mixmonitor")) {
  2829. q->montype = 1;
  2830. }
  2831. } else if (!strcasecmp(param, "autopause")) {
  2832. q->autopause = autopause2int(val);
  2833. } else if (!strcasecmp(param, "autopausedelay")) {
  2834. q->autopausedelay = atoi(val);
  2835. } else if (!strcasecmp(param, "autopausebusy")) {
  2836. q->autopausebusy = ast_true(val);
  2837. } else if (!strcasecmp(param, "autopauseunavail")) {
  2838. q->autopauseunavail = ast_true(val);
  2839. } else if (!strcasecmp(param, "maxlen")) {
  2840. q->maxlen = atoi(val);
  2841. if (q->maxlen < 0) {
  2842. q->maxlen = 0;
  2843. }
  2844. } else if (!strcasecmp(param, "servicelevel")) {
  2845. q->servicelevel= atoi(val);
  2846. } else if (!strcasecmp(param, "strategy")) {
  2847. int strategy;
  2848. /* We are a static queue and already have set this, no need to do it again */
  2849. if (failunknown) {
  2850. return;
  2851. }
  2852. strategy = strat2int(val);
  2853. if (strategy < 0) {
  2854. ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
  2855. val, q->name);
  2856. q->strategy = QUEUE_STRATEGY_RINGALL;
  2857. }
  2858. if (strategy == q->strategy) {
  2859. return;
  2860. }
  2861. if (strategy == QUEUE_STRATEGY_LINEAR) {
  2862. ast_log(LOG_WARNING, "Changing to the linear strategy currently requires asterisk to be restarted.\n");
  2863. return;
  2864. }
  2865. q->strategy = strategy;
  2866. } else if (!strcasecmp(param, "joinempty")) {
  2867. parse_empty_options(val, &q->joinempty, 1);
  2868. } else if (!strcasecmp(param, "leavewhenempty")) {
  2869. parse_empty_options(val, &q->leavewhenempty, 0);
  2870. } else if (!strcasecmp(param, "reportholdtime")) {
  2871. q->reportholdtime = ast_true(val);
  2872. } else if (!strcasecmp(param, "memberdelay")) {
  2873. q->memberdelay = atoi(val);
  2874. } else if (!strcasecmp(param, "weight")) {
  2875. q->weight = atoi(val);
  2876. } else if (!strcasecmp(param, "timeoutrestart")) {
  2877. q->timeoutrestart = ast_true(val);
  2878. } else if (!strcasecmp(param, "defaultrule")) {
  2879. ast_string_field_set(q, defaultrule, val);
  2880. } else if (!strcasecmp(param, "timeoutpriority")) {
  2881. if (!strcasecmp(val, "conf")) {
  2882. q->timeoutpriority = TIMEOUT_PRIORITY_CONF;
  2883. } else {
  2884. q->timeoutpriority = TIMEOUT_PRIORITY_APP;
  2885. }
  2886. } else if (failunknown) {
  2887. if (linenum >= 0) {
  2888. ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
  2889. q->name, param, linenum);
  2890. } else {
  2891. ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
  2892. }
  2893. }
  2894. }
  2895. #define QUEUE_PAUSED_DEVSTATE AST_DEVICE_INUSE
  2896. #define QUEUE_UNPAUSED_DEVSTATE AST_DEVICE_NOT_INUSE
  2897. #define QUEUE_UNKNOWN_PAUSED_DEVSTATE AST_DEVICE_NOT_INUSE
  2898. /*! \internal
  2899. * \brief If adding a single new member to a queue, use this function instead of ao2_linking.
  2900. * This adds round robin queue position data for a fresh member as well as links it.
  2901. * \param queue Which queue the member is being added to
  2902. * \param mem Which member is being added to the queue
  2903. */
  2904. static void member_add_to_queue(struct call_queue *queue, struct member *mem)
  2905. {
  2906. ao2_lock(queue->members);
  2907. mem->queuepos = ao2_container_count(queue->members);
  2908. ao2_link(queue->members, mem);
  2909. ast_devstate_changed(mem->paused ? QUEUE_PAUSED_DEVSTATE : QUEUE_UNPAUSED_DEVSTATE,
  2910. AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", queue->name, mem->interface);
  2911. ao2_unlock(queue->members);
  2912. }
  2913. /*! \internal
  2914. * \brief If removing a single member from a queue, use this function instead of ao2_unlinking.
  2915. * This will perform round robin queue position reordering for the remaining members.
  2916. * \param queue Which queue the member is being removed from
  2917. * \param member Which member is being removed from the queue
  2918. */
  2919. static void member_remove_from_queue(struct call_queue *queue, struct member *mem)
  2920. {
  2921. ao2_lock(queue->members);
  2922. ast_devstate_changed(QUEUE_UNKNOWN_PAUSED_DEVSTATE, AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", queue->name, mem->interface);
  2923. queue_member_follower_removal(queue, mem);
  2924. ao2_unlink(queue->members, mem);
  2925. ao2_unlock(queue->members);
  2926. }
  2927. /*!
  2928. * \brief Find rt member record to update otherwise create one.
  2929. *
  2930. * Search for member in queue, if found update penalty/paused state,
  2931. * if no member exists create one flag it as a RT member and add to queue member list.
  2932. */
  2933. static void rt_handle_member_record(struct call_queue *q, char *interface, struct ast_config *member_config)
  2934. {
  2935. struct member *m;
  2936. struct ao2_iterator mem_iter;
  2937. int penalty = 0;
  2938. int paused = 0;
  2939. int found = 0;
  2940. int ringinuse = q->ringinuse;
  2941. const char *config_val;
  2942. const char *rt_uniqueid = ast_variable_retrieve(member_config, interface, "uniqueid");
  2943. const char *membername = S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface);
  2944. const char *state_interface = S_OR(ast_variable_retrieve(member_config, interface, "state_interface"), interface);
  2945. const char *penalty_str = ast_variable_retrieve(member_config, interface, "penalty");
  2946. const char *paused_str = ast_variable_retrieve(member_config, interface, "paused");
  2947. if (ast_strlen_zero(rt_uniqueid)) {
  2948. ast_log(LOG_WARNING, "Realtime field uniqueid is empty for member %s\n", S_OR(membername, "NULL"));
  2949. return;
  2950. }
  2951. if (penalty_str) {
  2952. penalty = atoi(penalty_str);
  2953. if ((penalty < 0) && negative_penalty_invalid) {
  2954. return;
  2955. } else if (penalty < 0) {
  2956. penalty = 0;
  2957. }
  2958. }
  2959. if (paused_str) {
  2960. paused = atoi(paused_str);
  2961. if (paused < 0) {
  2962. paused = 0;
  2963. }
  2964. }
  2965. if ((config_val = ast_variable_retrieve(member_config, interface, realtime_ringinuse_field))) {
  2966. if (ast_true(config_val)) {
  2967. ringinuse = 1;
  2968. } else if (ast_false(config_val)) {
  2969. ringinuse = 0;
  2970. } else {
  2971. ast_log(LOG_WARNING, "Invalid value of '%s' field for %s in queue '%s'\n", realtime_ringinuse_field, interface, q->name);
  2972. }
  2973. }
  2974. /* Find member by realtime uniqueid and update */
  2975. mem_iter = ao2_iterator_init(q->members, 0);
  2976. while ((m = ao2_iterator_next(&mem_iter))) {
  2977. if (!strcasecmp(m->rt_uniqueid, rt_uniqueid)) {
  2978. m->dead = 0; /* Do not delete this one. */
  2979. ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
  2980. if (paused_str) {
  2981. m->paused = paused;
  2982. ast_devstate_changed(m->paused ? QUEUE_PAUSED_DEVSTATE : QUEUE_UNPAUSED_DEVSTATE,
  2983. AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", q->name, m->interface);
  2984. }
  2985. if (strcasecmp(state_interface, m->state_interface)) {
  2986. ast_copy_string(m->state_interface, state_interface, sizeof(m->state_interface));
  2987. }
  2988. m->penalty = penalty;
  2989. m->ringinuse = ringinuse;
  2990. found = 1;
  2991. ao2_ref(m, -1);
  2992. break;
  2993. }
  2994. ao2_ref(m, -1);
  2995. }
  2996. ao2_iterator_destroy(&mem_iter);
  2997. /* Create a new member */
  2998. if (!found) {
  2999. if ((m = create_queue_member(interface, membername, penalty, paused, state_interface, ringinuse))) {
  3000. m->dead = 0;
  3001. m->realtime = 1;
  3002. ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
  3003. if (!log_membername_as_agent) {
  3004. ast_queue_log(q->name, "REALTIME", m->interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
  3005. } else {
  3006. ast_queue_log(q->name, "REALTIME", m->membername, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
  3007. }
  3008. member_add_to_queue(q, m);
  3009. ao2_ref(m, -1);
  3010. m = NULL;
  3011. }
  3012. }
  3013. }
  3014. /*! \brief Iterate through queue's member list and delete them */
  3015. static void free_members(struct call_queue *q, int all)
  3016. {
  3017. /* Free non-dynamic members */
  3018. struct member *cur;
  3019. struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
  3020. while ((cur = ao2_iterator_next(&mem_iter))) {
  3021. if (all || !cur->dynamic) {
  3022. member_remove_from_queue(q, cur);
  3023. }
  3024. ao2_ref(cur, -1);
  3025. }
  3026. ao2_iterator_destroy(&mem_iter);
  3027. }
  3028. /*! \brief Free queue's member list then its string fields */
  3029. static void destroy_queue(void *obj)
  3030. {
  3031. struct call_queue *q = obj;
  3032. int i;
  3033. free_members(q, 1);
  3034. ast_string_field_free_memory(q);
  3035. for (i = 0; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
  3036. if (q->sound_periodicannounce[i]) {
  3037. ast_free(q->sound_periodicannounce[i]);
  3038. }
  3039. }
  3040. ao2_ref(q->members, -1);
  3041. }
  3042. static struct call_queue *alloc_queue(const char *queuename)
  3043. {
  3044. struct call_queue *q;
  3045. if ((q = ao2_t_alloc(sizeof(*q), destroy_queue, "Allocate queue"))) {
  3046. if (ast_string_field_init(q, 64)) {
  3047. queue_t_unref(q, "String field allocation failed");
  3048. return NULL;
  3049. }
  3050. ast_string_field_set(q, name, queuename);
  3051. }
  3052. return q;
  3053. }
  3054. /*!
  3055. * \brief Reload a single queue via realtime.
  3056. *
  3057. * Check for statically defined queue first, check if deleted RT queue,
  3058. * check for new RT queue, if queue vars are not defined init them with defaults.
  3059. * reload RT queue vars, set RT queue members dead and reload them, return finished queue.
  3060. * \retval the queue,
  3061. * \retval NULL if it doesn't exist.
  3062. * \note Should be called with the "queues" container locked.
  3063. */
  3064. static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
  3065. {
  3066. struct ast_variable *v;
  3067. struct call_queue *q, tmpq = {
  3068. .name = queuename,
  3069. };
  3070. struct member *m;
  3071. struct ao2_iterator mem_iter;
  3072. char *interface = NULL;
  3073. const char *tmp_name;
  3074. char *tmp;
  3075. char tmpbuf[64]; /* Must be longer than the longest queue param name. */
  3076. /* Static queues override realtime. */
  3077. if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Check if static queue exists"))) {
  3078. ao2_lock(q);
  3079. if (!q->realtime) {
  3080. if (q->dead) {
  3081. ao2_unlock(q);
  3082. queue_t_unref(q, "Queue is dead; can't return it");
  3083. return NULL;
  3084. }
  3085. ast_log(LOG_WARNING, "Static queue '%s' already exists. Not loading from realtime\n", q->name);
  3086. ao2_unlock(q);
  3087. return q;
  3088. }
  3089. } else if (!member_config) {
  3090. /* Not found in the list, and it's not realtime ... */
  3091. return NULL;
  3092. }
  3093. /* Check if queue is defined in realtime. */
  3094. if (!queue_vars) {
  3095. /* Delete queue from in-core list if it has been deleted in realtime. */
  3096. if (q) {
  3097. /*! \note Hmm, can't seem to distinguish a DB failure from a not
  3098. found condition... So we might delete an in-core queue
  3099. in case of DB failure. */
  3100. ast_debug(1, "Queue %s not found in realtime.\n", queuename);
  3101. q->dead = 1;
  3102. /* Delete if unused (else will be deleted when last caller leaves). */
  3103. queues_t_unlink(queues, q, "Unused; removing from container");
  3104. ao2_unlock(q);
  3105. queue_t_unref(q, "Queue is dead; can't return it");
  3106. }
  3107. return NULL;
  3108. }
  3109. /* Create a new queue if an in-core entry does not exist yet. */
  3110. if (!q) {
  3111. struct ast_variable *tmpvar = NULL;
  3112. if (!(q = alloc_queue(queuename))) {
  3113. return NULL;
  3114. }
  3115. ao2_lock(q);
  3116. clear_queue(q);
  3117. q->realtime = 1;
  3118. /*Before we initialize the queue, we need to set the strategy, so that linear strategy
  3119. * will allocate the members properly
  3120. */
  3121. for (tmpvar = queue_vars; tmpvar; tmpvar = tmpvar->next) {
  3122. if (!strcasecmp(tmpvar->name, "strategy")) {
  3123. q->strategy = strat2int(tmpvar->value);
  3124. if (q->strategy < 0) {
  3125. ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
  3126. tmpvar->value, q->name);
  3127. q->strategy = QUEUE_STRATEGY_RINGALL;
  3128. }
  3129. break;
  3130. }
  3131. }
  3132. /* We traversed all variables and didn't find a strategy */
  3133. if (!tmpvar) {
  3134. q->strategy = QUEUE_STRATEGY_RINGALL;
  3135. }
  3136. queues_t_link(queues, q, "Add queue to container");
  3137. }
  3138. init_queue(q); /* Ensure defaults for all parameters not set explicitly. */
  3139. memset(tmpbuf, 0, sizeof(tmpbuf));
  3140. for (v = queue_vars; v; v = v->next) {
  3141. /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
  3142. if (strchr(v->name, '_')) {
  3143. ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
  3144. tmp_name = tmpbuf;
  3145. tmp = tmpbuf;
  3146. while ((tmp = strchr(tmp, '_'))) {
  3147. *tmp++ = '-';
  3148. }
  3149. } else {
  3150. tmp_name = v->name;
  3151. }
  3152. /* NULL values don't get returned from realtime; blank values should
  3153. * still get set. If someone doesn't want a value to be set, they
  3154. * should set the realtime column to NULL, not blank. */
  3155. queue_set_param(q, tmp_name, v->value, -1, 0);
  3156. }
  3157. /* Temporarily set realtime members dead so we can detect deleted ones. */
  3158. mem_iter = ao2_iterator_init(q->members, 0);
  3159. while ((m = ao2_iterator_next(&mem_iter))) {
  3160. if (m->realtime) {
  3161. m->dead = 1;
  3162. }
  3163. ao2_ref(m, -1);
  3164. }
  3165. ao2_iterator_destroy(&mem_iter);
  3166. while ((interface = ast_category_browse(member_config, interface))) {
  3167. rt_handle_member_record(q, interface, member_config);
  3168. }
  3169. /* Delete all realtime members that have been deleted in DB. */
  3170. mem_iter = ao2_iterator_init(q->members, 0);
  3171. while ((m = ao2_iterator_next(&mem_iter))) {
  3172. if (m->dead) {
  3173. if (ast_strlen_zero(m->membername) || !log_membername_as_agent) {
  3174. ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
  3175. } else {
  3176. ast_queue_log(q->name, "REALTIME", m->membername, "REMOVEMEMBER", "%s", "");
  3177. }
  3178. member_remove_from_queue(q, m);
  3179. }
  3180. ao2_ref(m, -1);
  3181. }
  3182. ao2_iterator_destroy(&mem_iter);
  3183. ao2_unlock(q);
  3184. return q;
  3185. }
  3186. /*!
  3187. * note */
  3188. /*!
  3189. * \internal
  3190. * \brief Returns reference to the named queue. If the queue is realtime, it will load the queue as well.
  3191. * \param queuename - name of the desired queue
  3192. *
  3193. * \retval the queue
  3194. * \retval NULL if it doesn't exist
  3195. */
  3196. static struct call_queue *find_load_queue_rt_friendly(const char *queuename)
  3197. {
  3198. struct ast_variable *queue_vars;
  3199. struct ast_config *member_config = NULL;
  3200. struct call_queue *q = NULL, tmpq = {
  3201. .name = queuename,
  3202. };
  3203. int prev_weight = 0;
  3204. /* Find the queue in the in-core list first. */
  3205. q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Look for queue in memory first");
  3206. if (!q || q->realtime) {
  3207. /*! \note Load from realtime before taking the "queues" container lock, to avoid blocking all
  3208. queue operations while waiting for the DB.
  3209. This will be two separate database transactions, so we might
  3210. see queue parameters as they were before another process
  3211. changed the queue and member list as it was after the change.
  3212. Thus we might see an empty member list when a queue is
  3213. deleted. In practise, this is unlikely to cause a problem. */
  3214. queue_vars = ast_load_realtime("queues", "name", queuename, SENTINEL);
  3215. if (queue_vars) {
  3216. member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, SENTINEL);
  3217. if (!member_config) {
  3218. ast_debug(1, "No queue_members defined in config extconfig.conf\n");
  3219. member_config = ast_config_new();
  3220. }
  3221. }
  3222. if (q) {
  3223. prev_weight = q->weight ? 1 : 0;
  3224. queue_t_unref(q, "Need to find realtime queue");
  3225. }
  3226. q = find_queue_by_name_rt(queuename, queue_vars, member_config);
  3227. ast_config_destroy(member_config);
  3228. ast_variables_destroy(queue_vars);
  3229. /* update the use_weight value if the queue's has gained or lost a weight */
  3230. if (q) {
  3231. if (!q->weight && prev_weight) {
  3232. ast_atomic_fetchadd_int(&use_weight, -1);
  3233. }
  3234. if (q->weight && !prev_weight) {
  3235. ast_atomic_fetchadd_int(&use_weight, +1);
  3236. }
  3237. }
  3238. /* Other cases will end up with the proper value for use_weight */
  3239. } else {
  3240. update_realtime_members(q);
  3241. }
  3242. return q;
  3243. }
  3244. static int update_realtime_member_field(struct member *mem, const char *queue_name, const char *field, const char *value)
  3245. {
  3246. int ret = -1;
  3247. if (ast_strlen_zero(mem->rt_uniqueid)) {
  3248. return ret;
  3249. }
  3250. if ((ast_update_realtime("queue_members", "uniqueid", mem->rt_uniqueid, field, value, SENTINEL)) > 0) {
  3251. ret = 0;
  3252. }
  3253. return ret;
  3254. }
  3255. static void update_realtime_members(struct call_queue *q)
  3256. {
  3257. struct ast_config *member_config = NULL;
  3258. struct member *m;
  3259. char *interface = NULL;
  3260. struct ao2_iterator mem_iter;
  3261. if (!(member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", q->name , SENTINEL))) {
  3262. /* This queue doesn't have realtime members. If the queue still has any realtime
  3263. * members in memory, they need to be removed.
  3264. */
  3265. ao2_lock(q);
  3266. mem_iter = ao2_iterator_init(q->members, 0);
  3267. while ((m = ao2_iterator_next(&mem_iter))) {
  3268. if (m->realtime) {
  3269. member_remove_from_queue(q, m);
  3270. }
  3271. ao2_ref(m, -1);
  3272. }
  3273. ao2_iterator_destroy(&mem_iter);
  3274. ast_debug(3, "Queue %s has no realtime members defined. No need for update\n", q->name);
  3275. ao2_unlock(q);
  3276. return;
  3277. }
  3278. ao2_lock(q);
  3279. /* Temporarily set realtime members dead so we can detect deleted ones.*/
  3280. mem_iter = ao2_iterator_init(q->members, 0);
  3281. while ((m = ao2_iterator_next(&mem_iter))) {
  3282. if (m->realtime) {
  3283. m->dead = 1;
  3284. }
  3285. ao2_ref(m, -1);
  3286. }
  3287. ao2_iterator_destroy(&mem_iter);
  3288. while ((interface = ast_category_browse(member_config, interface))) {
  3289. rt_handle_member_record(q, interface, member_config);
  3290. }
  3291. /* Delete all realtime members that have been deleted in DB. */
  3292. mem_iter = ao2_iterator_init(q->members, 0);
  3293. while ((m = ao2_iterator_next(&mem_iter))) {
  3294. if (m->dead) {
  3295. if (ast_strlen_zero(m->membername) || !log_membername_as_agent) {
  3296. ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
  3297. } else {
  3298. ast_queue_log(q->name, "REALTIME", m->membername, "REMOVEMEMBER", "%s", "");
  3299. }
  3300. member_remove_from_queue(q, m);
  3301. }
  3302. ao2_ref(m, -1);
  3303. }
  3304. ao2_iterator_destroy(&mem_iter);
  3305. ao2_unlock(q);
  3306. ast_config_destroy(member_config);
  3307. }
  3308. static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason, int position)
  3309. {
  3310. struct call_queue *q;
  3311. struct queue_ent *cur, *prev = NULL;
  3312. int res = -1;
  3313. int pos = 0;
  3314. int inserted = 0;
  3315. if (!(q = find_load_queue_rt_friendly(queuename))) {
  3316. return res;
  3317. }
  3318. ao2_lock(q);
  3319. /* This is our one */
  3320. if (q->joinempty) {
  3321. int status = 0;
  3322. if ((status = get_member_status(q, qe->max_penalty, qe->min_penalty, q->joinempty, 0))) {
  3323. *reason = QUEUE_JOINEMPTY;
  3324. ao2_unlock(q);
  3325. queue_t_unref(q, "Done with realtime queue");
  3326. return res;
  3327. }
  3328. }
  3329. if (*reason == QUEUE_UNKNOWN && q->maxlen && (q->count >= q->maxlen)) {
  3330. *reason = QUEUE_FULL;
  3331. } else if (*reason == QUEUE_UNKNOWN) {
  3332. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  3333. /* There's space for us, put us at the right position inside
  3334. * the queue.
  3335. * Take into account the priority of the calling user */
  3336. inserted = 0;
  3337. prev = NULL;
  3338. cur = q->head;
  3339. while (cur) {
  3340. /* We have higher priority than the current user, enter
  3341. * before him, after all the other users with priority
  3342. * higher or equal to our priority. */
  3343. if ((!inserted) && (qe->prio > cur->prio)) {
  3344. insert_entry(q, prev, qe, &pos);
  3345. inserted = 1;
  3346. }
  3347. /* <= is necessary for the position comparison because it may not be possible to enter
  3348. * at our desired position since higher-priority callers may have taken the position we want
  3349. */
  3350. if (!inserted && (qe->prio >= cur->prio) && position && (position <= pos + 1)) {
  3351. insert_entry(q, prev, qe, &pos);
  3352. inserted = 1;
  3353. /*pos is incremented inside insert_entry, so don't need to add 1 here*/
  3354. if (position < pos) {
  3355. ast_log(LOG_NOTICE, "Asked to be inserted at position %d but forced into position %d due to higher priority callers\n", position, pos);
  3356. }
  3357. }
  3358. cur->pos = ++pos;
  3359. prev = cur;
  3360. cur = cur->next;
  3361. }
  3362. /* No luck, join at the end of the queue */
  3363. if (!inserted) {
  3364. insert_entry(q, prev, qe, &pos);
  3365. }
  3366. ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
  3367. ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
  3368. ast_copy_string(qe->context, q->context, sizeof(qe->context));
  3369. q->count++;
  3370. if (q->count == 1) {
  3371. ast_devstate_changed(AST_DEVICE_RINGING, AST_DEVSTATE_CACHABLE, "Queue:%s", q->name);
  3372. }
  3373. res = 0;
  3374. blob = ast_json_pack("{s: s, s: i, s: i}",
  3375. "Queue", q->name,
  3376. "Position", qe->pos,
  3377. "Count", q->count);
  3378. ast_channel_publish_cached_blob(qe->chan, queue_caller_join_type(), blob);
  3379. ast_debug(1, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, ast_channel_name(qe->chan), qe->pos );
  3380. }
  3381. ao2_unlock(q);
  3382. queue_t_unref(q, "Done with realtime queue");
  3383. return res;
  3384. }
  3385. static int play_file(struct ast_channel *chan, const char *filename)
  3386. {
  3387. int res;
  3388. if (ast_strlen_zero(filename)) {
  3389. return 0;
  3390. }
  3391. if (!ast_fileexists(filename, NULL, ast_channel_language(chan))) {
  3392. return 0;
  3393. }
  3394. ast_stopstream(chan);
  3395. res = ast_streamfile(chan, filename, ast_channel_language(chan));
  3396. if (!res) {
  3397. res = ast_waitstream(chan, AST_DIGIT_ANY);
  3398. }
  3399. ast_stopstream(chan);
  3400. return res;
  3401. }
  3402. /*!
  3403. * \brief Check for valid exit from queue via goto
  3404. * \retval 0 if failure
  3405. * \retval 1 if successful
  3406. */
  3407. static int valid_exit(struct queue_ent *qe, char digit)
  3408. {
  3409. int digitlen = strlen(qe->digits);
  3410. /* Prevent possible buffer overflow */
  3411. if (digitlen < sizeof(qe->digits) - 2) {
  3412. qe->digits[digitlen] = digit;
  3413. qe->digits[digitlen + 1] = '\0';
  3414. } else {
  3415. qe->digits[0] = '\0';
  3416. return 0;
  3417. }
  3418. /* If there's no context to goto, short-circuit */
  3419. if (ast_strlen_zero(qe->context)) {
  3420. return 0;
  3421. }
  3422. /* If the extension is bad, then reset the digits to blank */
  3423. if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1,
  3424. S_COR(ast_channel_caller(qe->chan)->id.number.valid, ast_channel_caller(qe->chan)->id.number.str, NULL))) {
  3425. qe->digits[0] = '\0';
  3426. return 0;
  3427. }
  3428. /* We have an exact match */
  3429. if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
  3430. qe->valid_digits = 1;
  3431. /* Return 1 on a successful goto */
  3432. return 1;
  3433. }
  3434. return 0;
  3435. }
  3436. static int say_position(struct queue_ent *qe, int ringing)
  3437. {
  3438. int res = 0, announceposition = 0;
  3439. long avgholdmins, avgholdsecs;
  3440. int say_thanks = 1;
  3441. time_t now;
  3442. /* Let minannouncefrequency seconds pass between the start of each position announcement */
  3443. time(&now);
  3444. if ((now - qe->last_pos) < qe->parent->minannouncefrequency) {
  3445. return 0;
  3446. }
  3447. /* If either our position has changed, or we are over the freq timer, say position */
  3448. if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency)) {
  3449. return 0;
  3450. }
  3451. if (ringing) {
  3452. ast_indicate(qe->chan,-1);
  3453. } else {
  3454. ast_moh_stop(qe->chan);
  3455. }
  3456. if (qe->parent->announceposition == ANNOUNCEPOSITION_YES ||
  3457. qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN ||
  3458. (qe->parent->announceposition == ANNOUNCEPOSITION_LIMIT &&
  3459. qe->pos <= qe->parent->announcepositionlimit)) {
  3460. announceposition = 1;
  3461. }
  3462. if (announceposition == 1) {
  3463. /* Say we're next, if we are */
  3464. if (qe->pos == 1) {
  3465. res = play_file(qe->chan, qe->parent->sound_next);
  3466. if (res) {
  3467. goto playout;
  3468. }
  3469. goto posout;
  3470. } else {
  3471. if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit){
  3472. /* More than Case*/
  3473. res = play_file(qe->chan, qe->parent->queue_quantity1);
  3474. if (res) {
  3475. goto playout;
  3476. }
  3477. res = ast_say_number(qe->chan, qe->parent->announcepositionlimit, AST_DIGIT_ANY, ast_channel_language(qe->chan), NULL); /* Needs gender */
  3478. if (res) {
  3479. goto playout;
  3480. }
  3481. } else {
  3482. /* Normal Case */
  3483. res = play_file(qe->chan, qe->parent->sound_thereare);
  3484. if (res) {
  3485. goto playout;
  3486. }
  3487. res = ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, ast_channel_language(qe->chan), NULL); /* Needs gender */
  3488. if (res) {
  3489. goto playout;
  3490. }
  3491. }
  3492. if (qe->parent->announceposition == ANNOUNCEPOSITION_MORE_THAN && qe->pos > qe->parent->announcepositionlimit){
  3493. /* More than Case*/
  3494. res = play_file(qe->chan, qe->parent->queue_quantity2);
  3495. if (res) {
  3496. goto playout;
  3497. }
  3498. } else {
  3499. res = play_file(qe->chan, qe->parent->sound_calls);
  3500. if (res) {
  3501. goto playout;
  3502. }
  3503. }
  3504. }
  3505. }
  3506. /* Round hold time to nearest minute */
  3507. avgholdmins = labs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
  3508. /* If they have specified a rounding then round the seconds as well */
  3509. if (qe->parent->roundingseconds) {
  3510. avgholdsecs = (labs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
  3511. avgholdsecs *= qe->parent->roundingseconds;
  3512. } else {
  3513. avgholdsecs = 0;
  3514. }
  3515. ast_verb(3, "Hold time for %s is %ld minute(s) %ld seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
  3516. /* If the hold time is >1 min, if it's enabled, and if it's not
  3517. supposed to be only once and we have already said it, say it */
  3518. if ((avgholdmins+avgholdsecs) > 0 && qe->parent->announceholdtime &&
  3519. ((qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE && !qe->last_pos) ||
  3520. !(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE))) {
  3521. res = play_file(qe->chan, qe->parent->sound_holdtime);
  3522. if (res) {
  3523. goto playout;
  3524. }
  3525. if (avgholdmins >= 1) {
  3526. res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, ast_channel_language(qe->chan), NULL);
  3527. if (res) {
  3528. goto playout;
  3529. }
  3530. if (avgholdmins == 1) {
  3531. res = play_file(qe->chan, qe->parent->sound_minute);
  3532. if (res) {
  3533. goto playout;
  3534. }
  3535. } else {
  3536. res = play_file(qe->chan, qe->parent->sound_minutes);
  3537. if (res) {
  3538. goto playout;
  3539. }
  3540. }
  3541. }
  3542. if (avgholdsecs >= 1) {
  3543. res = ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, ast_channel_language(qe->chan), NULL);
  3544. if (res) {
  3545. goto playout;
  3546. }
  3547. res = play_file(qe->chan, qe->parent->sound_seconds);
  3548. if (res) {
  3549. goto playout;
  3550. }
  3551. }
  3552. } else if (qe->parent->announceholdtime && !qe->parent->announceposition) {
  3553. say_thanks = 0;
  3554. }
  3555. posout:
  3556. if (qe->parent->announceposition) {
  3557. ast_verb(3, "Told %s in %s their queue position (which was %d)\n",
  3558. ast_channel_name(qe->chan), qe->parent->name, qe->pos);
  3559. }
  3560. if (say_thanks) {
  3561. res = play_file(qe->chan, qe->parent->sound_thanks);
  3562. }
  3563. playout:
  3564. if ((res > 0 && !valid_exit(qe, res))) {
  3565. res = 0;
  3566. }
  3567. /* Set our last_pos indicators */
  3568. qe->last_pos = now;
  3569. qe->last_pos_said = qe->pos;
  3570. /* Don't restart music on hold if we're about to exit the caller from the queue */
  3571. if (!res) {
  3572. if (ringing) {
  3573. ast_indicate(qe->chan, AST_CONTROL_RINGING);
  3574. } else {
  3575. ast_moh_start(qe->chan, qe->moh, NULL);
  3576. }
  3577. }
  3578. return res;
  3579. }
  3580. static void recalc_holdtime(struct queue_ent *qe, int newholdtime)
  3581. {
  3582. int oldvalue;
  3583. /* Calculate holdtime using an exponential average */
  3584. /* Thanks to SRT for this contribution */
  3585. /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
  3586. ao2_lock(qe->parent);
  3587. oldvalue = qe->parent->holdtime;
  3588. qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newholdtime) >> 2;
  3589. ao2_unlock(qe->parent);
  3590. }
  3591. /*! \brief Caller leaving queue.
  3592. *
  3593. * Search the queue to find the leaving client, if found remove from queue
  3594. * create manager event, move others up the queue.
  3595. */
  3596. static void leave_queue(struct queue_ent *qe)
  3597. {
  3598. struct call_queue *q;
  3599. struct queue_ent *current, *prev = NULL;
  3600. struct penalty_rule *pr_iter;
  3601. int pos = 0;
  3602. if (!(q = qe->parent)) {
  3603. return;
  3604. }
  3605. queue_t_ref(q, "Copy queue pointer from queue entry");
  3606. ao2_lock(q);
  3607. prev = NULL;
  3608. for (current = q->head; current; current = current->next) {
  3609. if (current == qe) {
  3610. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  3611. char posstr[20];
  3612. q->count--;
  3613. if (!q->count) {
  3614. ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s", q->name);
  3615. }
  3616. blob = ast_json_pack("{s: s, s: i, s: i}",
  3617. "Queue", q->name,
  3618. "Position", qe->pos,
  3619. "Count", q->count);
  3620. ast_channel_publish_cached_blob(qe->chan, queue_caller_leave_type(), blob);
  3621. ast_debug(1, "Queue '%s' Leave, Channel '%s'\n", q->name, ast_channel_name(qe->chan));
  3622. /* Take us out of the queue */
  3623. if (prev) {
  3624. prev->next = current->next;
  3625. } else {
  3626. q->head = current->next;
  3627. }
  3628. /* Free penalty rules */
  3629. while ((pr_iter = AST_LIST_REMOVE_HEAD(&qe->qe_rules, list))) {
  3630. ast_free(pr_iter);
  3631. }
  3632. qe->pr = NULL;
  3633. snprintf(posstr, sizeof(posstr), "%d", qe->pos);
  3634. pbx_builtin_setvar_helper(qe->chan, "QUEUEPOSITION", posstr);
  3635. } else {
  3636. /* Renumber the people after us in the queue based on a new count */
  3637. current->pos = ++pos;
  3638. prev = current;
  3639. }
  3640. }
  3641. ao2_unlock(q);
  3642. /*If the queue is a realtime queue, check to see if it's still defined in real time*/
  3643. if (q->realtime) {
  3644. struct ast_variable *var;
  3645. if (!(var = ast_load_realtime("queues", "name", q->name, SENTINEL))) {
  3646. q->dead = 1;
  3647. } else {
  3648. ast_variables_destroy(var);
  3649. }
  3650. }
  3651. if (q->dead) {
  3652. /* It's dead and nobody is in it, so kill it */
  3653. queues_t_unlink(queues, q, "Queue is now dead; remove it from the container");
  3654. }
  3655. /* unref the explicit ref earlier in the function */
  3656. queue_t_unref(q, "Expire copied reference");
  3657. }
  3658. /*!
  3659. * \internal
  3660. * \brief Destroy the given callattempt structure and free it.
  3661. * \since 1.8
  3662. *
  3663. * \param doomed callattempt structure to destroy.
  3664. *
  3665. * \return Nothing
  3666. */
  3667. static void callattempt_free(struct callattempt *doomed)
  3668. {
  3669. if (doomed->member) {
  3670. ao2_ref(doomed->member, -1);
  3671. }
  3672. ast_party_connected_line_free(&doomed->connected);
  3673. ast_free(doomed);
  3674. }
  3675. static void publish_dial_end_event(struct ast_channel *in, struct callattempt *outgoing, struct ast_channel *exception, const char *status)
  3676. {
  3677. struct callattempt *cur;
  3678. for (cur = outgoing; cur; cur = cur->q_next) {
  3679. if (cur->chan && cur->chan != exception) {
  3680. ast_channel_publish_dial(in, cur->chan, NULL, status);
  3681. }
  3682. }
  3683. }
  3684. /*! \brief Hang up a list of outgoing calls */
  3685. static void hangupcalls(struct queue_ent *qe, struct callattempt *outgoing, struct ast_channel *exception, int cancel_answered_elsewhere)
  3686. {
  3687. struct callattempt *oo;
  3688. while (outgoing) {
  3689. /* If someone else answered the call we should indicate this in the CANCEL */
  3690. /* Hangup any existing lines we have open */
  3691. if (outgoing->chan && (outgoing->chan != exception)) {
  3692. if (exception || cancel_answered_elsewhere) {
  3693. ast_channel_hangupcause_set(outgoing->chan, AST_CAUSE_ANSWERED_ELSEWHERE);
  3694. }
  3695. ast_channel_publish_dial(qe->chan, outgoing->chan, outgoing->interface, "CANCEL");
  3696. ast_hangup(outgoing->chan);
  3697. }
  3698. oo = outgoing;
  3699. outgoing = outgoing->q_next;
  3700. ast_aoc_destroy_decoded(oo->aoc_s_rate_list);
  3701. callattempt_free(oo);
  3702. }
  3703. }
  3704. /*!
  3705. * \brief Get the number of members available to accept a call.
  3706. *
  3707. * \note The queue passed in should be locked prior to this function call
  3708. *
  3709. * \param[in] q The queue for which we are couting the number of available members
  3710. * \return Return the number of available members in queue q
  3711. */
  3712. static int num_available_members(struct call_queue *q)
  3713. {
  3714. struct member *mem;
  3715. int avl = 0;
  3716. struct ao2_iterator mem_iter;
  3717. mem_iter = ao2_iterator_init(q->members, 0);
  3718. while ((mem = ao2_iterator_next(&mem_iter))) {
  3719. avl += is_member_available(q, mem);
  3720. ao2_ref(mem, -1);
  3721. /* If autofill is not enabled or if the queue's strategy is ringall, then
  3722. * we really don't care about the number of available members so much as we
  3723. * do that there is at least one available.
  3724. *
  3725. * In fact, we purposely will return from this function stating that only
  3726. * one member is available if either of those conditions hold. That way,
  3727. * functions which determine what action to take based on the number of available
  3728. * members will operate properly. The reasoning is that even if multiple
  3729. * members are available, only the head caller can actually be serviced.
  3730. */
  3731. if ((!q->autofill || q->strategy == QUEUE_STRATEGY_RINGALL) && avl) {
  3732. break;
  3733. }
  3734. }
  3735. ao2_iterator_destroy(&mem_iter);
  3736. return avl;
  3737. }
  3738. /* traverse all defined queues which have calls waiting and contain this member
  3739. return 0 if no other queue has precedence (higher weight) or 1 if found */
  3740. static int compare_weight(struct call_queue *rq, struct member *member)
  3741. {
  3742. struct call_queue *q;
  3743. struct member *mem;
  3744. int found = 0;
  3745. struct ao2_iterator queue_iter;
  3746. queue_iter = ao2_iterator_init(queues, 0);
  3747. while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
  3748. if (q == rq) { /* don't check myself, could deadlock */
  3749. queue_t_unref(q, "Done with iterator");
  3750. continue;
  3751. }
  3752. ao2_lock(q);
  3753. if (q->count && q->members) {
  3754. if ((mem = ao2_find(q->members, member, OBJ_POINTER))) {
  3755. ast_debug(1, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
  3756. if (q->weight > rq->weight && q->count >= num_available_members(q)) {
  3757. ast_debug(1, "Queue '%s' (weight %d, calls %d) is preferred over '%s' (weight %d, calls %d)\n", q->name, q->weight, q->count, rq->name, rq->weight, rq->count);
  3758. found = 1;
  3759. }
  3760. ao2_ref(mem, -1);
  3761. }
  3762. }
  3763. ao2_unlock(q);
  3764. queue_t_unref(q, "Done with iterator");
  3765. if (found) {
  3766. break;
  3767. }
  3768. }
  3769. ao2_iterator_destroy(&queue_iter);
  3770. return found;
  3771. }
  3772. /*! \brief common hangup actions */
  3773. static void do_hang(struct callattempt *o)
  3774. {
  3775. o->stillgoing = 0;
  3776. ast_hangup(o->chan);
  3777. o->chan = NULL;
  3778. }
  3779. /*!
  3780. * \internal
  3781. * \brief Check if the member status is available.
  3782. *
  3783. * \param status Member status to check if available.
  3784. *
  3785. * \retval non-zero if the member status is available.
  3786. */
  3787. static int member_status_available(int status)
  3788. {
  3789. return status == AST_DEVICE_NOT_INUSE || status == AST_DEVICE_UNKNOWN;
  3790. }
  3791. /*!
  3792. * \internal
  3793. * \brief Clear the member call pending flag.
  3794. *
  3795. * \param mem Queue member.
  3796. *
  3797. * \return Nothing
  3798. */
  3799. static void member_call_pending_clear(struct member *mem)
  3800. {
  3801. ao2_lock(mem);
  3802. mem->call_pending = 0;
  3803. ao2_unlock(mem);
  3804. }
  3805. /*!
  3806. * \internal
  3807. * \brief Set the member call pending flag.
  3808. *
  3809. * \param mem Queue member.
  3810. *
  3811. * \retval non-zero if call pending flag was already set.
  3812. */
  3813. static int member_call_pending_set(struct member *mem)
  3814. {
  3815. int old_pending;
  3816. ao2_lock(mem);
  3817. old_pending = mem->call_pending;
  3818. mem->call_pending = 1;
  3819. ao2_unlock(mem);
  3820. return old_pending;
  3821. }
  3822. /*!
  3823. * \internal
  3824. * \brief Determine if can ring a queue entry.
  3825. *
  3826. * \param qe Queue entry to check.
  3827. * \param call Member call attempt.
  3828. *
  3829. * \retval non-zero if an entry can be called.
  3830. */
  3831. static int can_ring_entry(struct queue_ent *qe, struct callattempt *call)
  3832. {
  3833. if (call->member->paused) {
  3834. ast_debug(1, "%s paused, can't receive call\n", call->interface);
  3835. return 0;
  3836. }
  3837. if (!call->member->ringinuse && !member_status_available(call->member->status)) {
  3838. ast_debug(1, "%s not available, can't receive call\n", call->interface);
  3839. return 0;
  3840. }
  3841. if ((call->lastqueue && call->lastqueue->wrapuptime && (time(NULL) - call->lastcall < call->lastqueue->wrapuptime))
  3842. || (!call->lastqueue && qe->parent->wrapuptime && (time(NULL) - call->lastcall < qe->parent->wrapuptime))) {
  3843. ast_debug(1, "Wrapuptime not yet expired on queue %s for %s\n",
  3844. (call->lastqueue ? call->lastqueue->name : qe->parent->name),
  3845. call->interface);
  3846. return 0;
  3847. }
  3848. if (use_weight && compare_weight(qe->parent, call->member)) {
  3849. ast_debug(1, "Priority queue delaying call to %s:%s\n",
  3850. qe->parent->name, call->interface);
  3851. return 0;
  3852. }
  3853. if (!call->member->ringinuse) {
  3854. if (member_call_pending_set(call->member)) {
  3855. ast_debug(1, "%s has another call pending, can't receive call\n",
  3856. call->interface);
  3857. return 0;
  3858. }
  3859. /*
  3860. * The queue member is available. Get current status to be sure
  3861. * because the device state and extension state callbacks may
  3862. * not have updated the status yet.
  3863. */
  3864. if (!member_status_available(get_queue_member_status(call->member))) {
  3865. ast_debug(1, "%s actually not available, can't receive call\n",
  3866. call->interface);
  3867. member_call_pending_clear(call->member);
  3868. return 0;
  3869. }
  3870. }
  3871. return 1;
  3872. }
  3873. /*!
  3874. * \brief Part 2 of ring_one
  3875. *
  3876. * Does error checking before attempting to request a channel and call a member.
  3877. * This function is only called from ring_one().
  3878. * Failure can occur if:
  3879. * - Agent on call
  3880. * - Agent is paused
  3881. * - Wrapup time not expired
  3882. * - Priority by another queue
  3883. *
  3884. * \retval 1 on success to reach a free agent
  3885. * \retval 0 on failure to get agent.
  3886. */
  3887. static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
  3888. {
  3889. int res;
  3890. int status;
  3891. char tech[256];
  3892. char *location;
  3893. const char *macrocontext, *macroexten;
  3894. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  3895. /* on entry here, we know that tmp->chan == NULL */
  3896. if (!can_ring_entry(qe, tmp)) {
  3897. tmp->stillgoing = 0;
  3898. ++*busies;
  3899. return 0;
  3900. }
  3901. ast_assert(tmp->member->ringinuse || tmp->member->call_pending);
  3902. ast_copy_string(tech, tmp->interface, sizeof(tech));
  3903. if ((location = strchr(tech, '/'))) {
  3904. *location++ = '\0';
  3905. } else {
  3906. location = "";
  3907. }
  3908. /* Request the peer */
  3909. tmp->chan = ast_request(tech, ast_channel_nativeformats(qe->chan), NULL, qe->chan, location, &status);
  3910. if (!tmp->chan) { /* If we can't, just go on to the next call */
  3911. ao2_lock(qe->parent);
  3912. qe->parent->rrpos++;
  3913. qe->linpos++;
  3914. ao2_unlock(qe->parent);
  3915. member_call_pending_clear(tmp->member);
  3916. publish_dial_end_event(qe->chan, tmp, NULL, "BUSY");
  3917. tmp->stillgoing = 0;
  3918. ++*busies;
  3919. return 0;
  3920. }
  3921. ast_channel_lock_both(tmp->chan, qe->chan);
  3922. ast_channel_req_accountcodes_precious(tmp->chan, qe->chan,
  3923. AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
  3924. if (qe->cancel_answered_elsewhere) {
  3925. ast_channel_hangupcause_set(tmp->chan, AST_CAUSE_ANSWERED_ELSEWHERE);
  3926. }
  3927. ast_channel_appl_set(tmp->chan, "AppQueue");
  3928. ast_channel_data_set(tmp->chan, "(Outgoing Line)");
  3929. memset(ast_channel_whentohangup(tmp->chan), 0, sizeof(*ast_channel_whentohangup(tmp->chan)));
  3930. /* If the new channel has no callerid, try to guess what it should be */
  3931. if (!ast_channel_caller(tmp->chan)->id.number.valid) {
  3932. if (ast_channel_connected(qe->chan)->id.number.valid) {
  3933. struct ast_party_caller caller;
  3934. ast_party_caller_set_init(&caller, ast_channel_caller(tmp->chan));
  3935. caller.id = ast_channel_connected(qe->chan)->id;
  3936. caller.ani = ast_channel_connected(qe->chan)->ani;
  3937. ast_channel_set_caller_event(tmp->chan, &caller, NULL);
  3938. } else if (!ast_strlen_zero(ast_channel_dialed(qe->chan)->number.str)) {
  3939. ast_set_callerid(tmp->chan, ast_channel_dialed(qe->chan)->number.str, NULL, NULL);
  3940. } else if (!ast_strlen_zero(S_OR(ast_channel_macroexten(qe->chan), ast_channel_exten(qe->chan)))) {
  3941. ast_set_callerid(tmp->chan, S_OR(ast_channel_macroexten(qe->chan), ast_channel_exten(qe->chan)), NULL, NULL);
  3942. }
  3943. tmp->dial_callerid_absent = 1;
  3944. }
  3945. ast_party_redirecting_copy(ast_channel_redirecting(tmp->chan), ast_channel_redirecting(qe->chan));
  3946. ast_channel_dialed(tmp->chan)->transit_network_select = ast_channel_dialed(qe->chan)->transit_network_select;
  3947. ast_connected_line_copy_from_caller(ast_channel_connected(tmp->chan), ast_channel_caller(qe->chan));
  3948. /* Inherit specially named variables from parent channel */
  3949. ast_channel_inherit_variables(qe->chan, tmp->chan);
  3950. ast_channel_datastore_inherit(qe->chan, tmp->chan);
  3951. /* Presense of ADSI CPE on outgoing channel follows ours */
  3952. ast_channel_adsicpe_set(tmp->chan, ast_channel_adsicpe(qe->chan));
  3953. /* Inherit context and extension */
  3954. macrocontext = pbx_builtin_getvar_helper(qe->chan, "MACRO_CONTEXT");
  3955. ast_channel_dialcontext_set(tmp->chan, ast_strlen_zero(macrocontext) ? ast_channel_context(qe->chan) : macrocontext);
  3956. macroexten = pbx_builtin_getvar_helper(qe->chan, "MACRO_EXTEN");
  3957. if (!ast_strlen_zero(macroexten)) {
  3958. ast_channel_exten_set(tmp->chan, macroexten);
  3959. } else {
  3960. ast_channel_exten_set(tmp->chan, ast_channel_exten(qe->chan));
  3961. }
  3962. ast_channel_unlock(tmp->chan);
  3963. ast_channel_unlock(qe->chan);
  3964. /* Place the call, but don't wait on the answer */
  3965. if ((res = ast_call(tmp->chan, location, 0))) {
  3966. /* Again, keep going even if there's an error */
  3967. ast_verb(3, "Couldn't call %s\n", tmp->interface);
  3968. do_hang(tmp);
  3969. member_call_pending_clear(tmp->member);
  3970. ++*busies;
  3971. return 0;
  3972. }
  3973. ast_channel_lock_both(tmp->chan, qe->chan);
  3974. blob = ast_json_pack("{s: s, s: s, s: s}",
  3975. "Queue", qe->parent->name,
  3976. "Interface", tmp->interface,
  3977. "MemberName", tmp->member->membername);
  3978. queue_publish_multi_channel_blob(qe->chan, tmp->chan, queue_agent_called_type(), blob);
  3979. ast_channel_publish_dial(qe->chan, tmp->chan, tmp->interface, NULL);
  3980. ast_channel_unlock(tmp->chan);
  3981. ast_channel_unlock(qe->chan);
  3982. ast_verb(3, "Called %s\n", tmp->interface);
  3983. member_call_pending_clear(tmp->member);
  3984. return 1;
  3985. }
  3986. /*! \brief find the entry with the best metric, or NULL */
  3987. static struct callattempt *find_best(struct callattempt *outgoing)
  3988. {
  3989. struct callattempt *best = NULL, *cur;
  3990. for (cur = outgoing; cur; cur = cur->q_next) {
  3991. if (cur->stillgoing && /* Not already done */
  3992. !cur->chan && /* Isn't already going */
  3993. (!best || cur->metric < best->metric)) { /* We haven't found one yet, or it's better */
  3994. best = cur;
  3995. }
  3996. }
  3997. return best;
  3998. }
  3999. /*!
  4000. * \brief Place a call to a queue member.
  4001. *
  4002. * Once metrics have been calculated for each member, this function is used
  4003. * to place a call to the appropriate member (or members). The low-level
  4004. * channel-handling and error detection is handled in ring_entry
  4005. *
  4006. * \retval 1 if a member was called successfully
  4007. * \retval 0 otherwise
  4008. */
  4009. static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
  4010. {
  4011. int ret = 0;
  4012. while (ret == 0) {
  4013. struct callattempt *best = find_best(outgoing);
  4014. if (!best) {
  4015. ast_debug(1, "Nobody left to try ringing in queue\n");
  4016. break;
  4017. }
  4018. if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
  4019. struct callattempt *cur;
  4020. /* Ring everyone who shares this best metric (for ringall) */
  4021. for (cur = outgoing; cur; cur = cur->q_next) {
  4022. if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
  4023. ast_debug(1, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
  4024. ret |= ring_entry(qe, cur, busies);
  4025. }
  4026. }
  4027. } else {
  4028. /* Ring just the best channel */
  4029. ast_debug(1, "Trying '%s' with metric %d\n", best->interface, best->metric);
  4030. ret = ring_entry(qe, best, busies);
  4031. }
  4032. /* If we have timed out, break out */
  4033. if (qe->expire && (time(NULL) >= qe->expire)) {
  4034. ast_debug(1, "Queue timed out while ringing members.\n");
  4035. ret = 0;
  4036. break;
  4037. }
  4038. }
  4039. return ret;
  4040. }
  4041. /*! \brief Search for best metric and add to Round Robbin queue */
  4042. static int store_next_rr(struct queue_ent *qe, struct callattempt *outgoing)
  4043. {
  4044. struct callattempt *best = find_best(outgoing);
  4045. if (best) {
  4046. /* Ring just the best channel */
  4047. ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
  4048. qe->parent->rrpos = best->metric % 1000;
  4049. } else {
  4050. /* Just increment rrpos */
  4051. if (qe->parent->wrapped) {
  4052. /* No more channels, start over */
  4053. qe->parent->rrpos = 0;
  4054. } else {
  4055. /* Prioritize next entry */
  4056. qe->parent->rrpos++;
  4057. }
  4058. }
  4059. qe->parent->wrapped = 0;
  4060. return 0;
  4061. }
  4062. /*! \brief Search for best metric and add to Linear queue */
  4063. static int store_next_lin(struct queue_ent *qe, struct callattempt *outgoing)
  4064. {
  4065. struct callattempt *best = find_best(outgoing);
  4066. if (best) {
  4067. /* Ring just the best channel */
  4068. ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
  4069. qe->linpos = best->metric % 1000;
  4070. } else {
  4071. /* Just increment rrpos */
  4072. if (qe->linwrapped) {
  4073. /* No more channels, start over */
  4074. qe->linpos = 0;
  4075. } else {
  4076. /* Prioritize next entry */
  4077. qe->linpos++;
  4078. }
  4079. }
  4080. qe->linwrapped = 0;
  4081. return 0;
  4082. }
  4083. /*! \brief Playback announcement to queued members if period has elapsed */
  4084. static int say_periodic_announcement(struct queue_ent *qe, int ringing)
  4085. {
  4086. int res = 0;
  4087. time_t now;
  4088. /* Get the current time */
  4089. time(&now);
  4090. /* Check to see if it is time to announce */
  4091. if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency) {
  4092. return 0;
  4093. }
  4094. /* Stop the music on hold so we can play our own file */
  4095. if (ringing) {
  4096. ast_indicate(qe->chan,-1);
  4097. } else {
  4098. ast_moh_stop(qe->chan);
  4099. }
  4100. ast_verb(3, "Playing periodic announcement\n");
  4101. if (qe->parent->randomperiodicannounce && qe->parent->numperiodicannounce) {
  4102. qe->last_periodic_announce_sound = ((unsigned long) ast_random()) % qe->parent->numperiodicannounce;
  4103. } else if (qe->last_periodic_announce_sound >= qe->parent->numperiodicannounce ||
  4104. ast_str_strlen(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]) == 0) {
  4105. qe->last_periodic_announce_sound = 0;
  4106. }
  4107. /* play the announcement */
  4108. res = play_file(qe->chan, ast_str_buffer(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]));
  4109. if (res > 0 && !valid_exit(qe, res)) {
  4110. res = 0;
  4111. }
  4112. /* Resume Music on Hold if the caller is going to stay in the queue */
  4113. if (!res) {
  4114. if (ringing) {
  4115. ast_indicate(qe->chan, AST_CONTROL_RINGING);
  4116. } else {
  4117. ast_moh_start(qe->chan, qe->moh, NULL);
  4118. }
  4119. }
  4120. /* update last_periodic_announce_time */
  4121. if (qe->parent->relativeperiodicannounce) {
  4122. time(&qe->last_periodic_announce_time);
  4123. } else {
  4124. qe->last_periodic_announce_time = now;
  4125. }
  4126. /* Update the current periodic announcement to the next announcement */
  4127. if (!qe->parent->randomperiodicannounce) {
  4128. qe->last_periodic_announce_sound++;
  4129. }
  4130. return res;
  4131. }
  4132. /*! \brief Record that a caller gave up on waiting in queue */
  4133. static void record_abandoned(struct queue_ent *qe)
  4134. {
  4135. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  4136. set_queue_variables(qe->parent, qe->chan);
  4137. ao2_lock(qe->parent);
  4138. blob = ast_json_pack("{s: s, s: i, s: i, s: i}",
  4139. "Queue", qe->parent->name,
  4140. "Position", qe->pos,
  4141. "OriginalPosition", qe->opos,
  4142. "HoldTime", (int)(time(NULL) - qe->start));
  4143. qe->parent->callsabandoned++;
  4144. ao2_unlock(qe->parent);
  4145. ast_channel_publish_cached_blob(qe->chan, queue_caller_abandon_type(), blob);
  4146. }
  4147. /*! \brief RNA == Ring No Answer. Common code that is executed when we try a queue member and they don't answer. */
  4148. static void rna(int rnatime, struct queue_ent *qe, struct ast_channel *peer, char *interface, char *membername, int autopause)
  4149. {
  4150. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  4151. ast_verb(3, "Nobody picked up in %d ms\n", rnatime);
  4152. /* Stop ringing, and resume MOH if specified */
  4153. if (qe->ring_when_ringing) {
  4154. ast_indicate(qe->chan, -1);
  4155. ast_moh_start(qe->chan, qe->moh, NULL);
  4156. }
  4157. blob = ast_json_pack("{s: s, s: s, s: s, s: i}",
  4158. "Queue", qe->parent->name,
  4159. "Interface", interface,
  4160. "MemberName", membername,
  4161. "RingTime", rnatime);
  4162. queue_publish_multi_channel_blob(qe->chan, peer, queue_agent_ringnoanswer_type(), blob);
  4163. ast_queue_log(qe->parent->name, ast_channel_uniqueid(qe->chan), membername, "RINGNOANSWER", "%d", rnatime);
  4164. if (qe->parent->autopause != QUEUE_AUTOPAUSE_OFF && autopause) {
  4165. if (qe->parent->autopausedelay > 0) {
  4166. struct member *mem;
  4167. ao2_lock(qe->parent);
  4168. if ((mem = interface_exists(qe->parent, interface))) {
  4169. time_t idletime = time(&idletime)-mem->lastcall;
  4170. if ((mem->lastcall != 0) && (qe->parent->autopausedelay > idletime)) {
  4171. ao2_unlock(qe->parent);
  4172. ao2_ref(mem, -1);
  4173. return;
  4174. }
  4175. ao2_ref(mem, -1);
  4176. }
  4177. ao2_unlock(qe->parent);
  4178. }
  4179. if (qe->parent->autopause == QUEUE_AUTOPAUSE_ON) {
  4180. if (!set_member_paused(qe->parent->name, interface, "Auto-Pause", 1)) {
  4181. ast_verb(3, "Auto-Pausing Queue Member %s in queue %s since they failed to answer.\n",
  4182. interface, qe->parent->name);
  4183. } else {
  4184. ast_verb(3, "Failed to pause Queue Member %s in queue %s!\n", interface, qe->parent->name);
  4185. }
  4186. } else {
  4187. /* If queue autopause is mode all, just don't send any queue to stop.
  4188. * the function will stop in all queues */
  4189. if (!set_member_paused("", interface, "Auto-Pause", 1)) {
  4190. ast_verb(3, "Auto-Pausing Queue Member %s in all queues since they failed to answer on queue %s.\n",
  4191. interface, qe->parent->name);
  4192. } else {
  4193. ast_verb(3, "Failed to pause Queue Member %s in all queues!\n", interface);
  4194. }
  4195. }
  4196. }
  4197. return;
  4198. }
  4199. #define AST_MAX_WATCHERS 256
  4200. /*!
  4201. * \brief Wait for a member to answer the call
  4202. *
  4203. * \param[in] qe the queue_ent corresponding to the caller in the queue
  4204. * \param[in] outgoing the list of callattempts. Relevant ones will have their chan and stillgoing parameters non-zero
  4205. * \param[in] to the amount of time (in milliseconds) to wait for a response
  4206. * \param[out] digit if a user presses a digit to exit the queue, this is the digit the caller pressed
  4207. * \param[in] prebusies number of busy members calculated prior to calling wait_for_answer
  4208. * \param[in] caller_disconnect if the 'H' option is used when calling Queue(), this is used to detect if the caller pressed * to disconnect the call
  4209. * \param[in] forwardsallowed used to detect if we should allow call forwarding, based on the 'i' option to Queue()
  4210. *
  4211. * \todo eventually all call forward logic should be intergerated into and replaced by ast_call_forward()
  4212. */
  4213. static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callattempt *outgoing, int *to, char *digit, int prebusies, int caller_disconnect, int forwardsallowed, int ringing)
  4214. {
  4215. const char *queue = qe->parent->name;
  4216. struct callattempt *o, *start = NULL, *prev = NULL;
  4217. int status;
  4218. int numbusies = prebusies;
  4219. int numnochan = 0;
  4220. int stillgoing = 0;
  4221. int orig = *to;
  4222. struct ast_frame *f;
  4223. struct callattempt *peer = NULL;
  4224. struct ast_channel *winner;
  4225. struct ast_channel *in = qe->chan;
  4226. char on[80] = "";
  4227. char membername[80] = "";
  4228. long starttime = 0;
  4229. long endtime = 0;
  4230. #ifdef HAVE_EPOLL
  4231. struct callattempt *epollo;
  4232. #endif
  4233. struct ast_party_connected_line connected_caller;
  4234. char *inchan_name;
  4235. struct timeval start_time_tv = ast_tvnow();
  4236. ast_party_connected_line_init(&connected_caller);
  4237. ast_channel_lock(qe->chan);
  4238. inchan_name = ast_strdupa(ast_channel_name(qe->chan));
  4239. ast_channel_unlock(qe->chan);
  4240. starttime = (long) time(NULL);
  4241. #ifdef HAVE_EPOLL
  4242. for (epollo = outgoing; epollo; epollo = epollo->q_next) {
  4243. if (epollo->chan) {
  4244. ast_poll_channel_add(in, epollo->chan);
  4245. }
  4246. }
  4247. #endif
  4248. while ((*to = ast_remaining_ms(start_time_tv, orig)) && !peer) {
  4249. int numlines, retry, pos = 1;
  4250. struct ast_channel *watchers[AST_MAX_WATCHERS];
  4251. watchers[0] = in;
  4252. start = NULL;
  4253. for (retry = 0; retry < 2; retry++) {
  4254. numlines = 0;
  4255. for (o = outgoing; o; o = o->q_next) { /* Keep track of important channels */
  4256. if (o->stillgoing) { /* Keep track of important channels */
  4257. stillgoing = 1;
  4258. if (o->chan) {
  4259. if (pos < AST_MAX_WATCHERS) {
  4260. watchers[pos++] = o->chan;
  4261. }
  4262. if (!start) {
  4263. start = o;
  4264. } else {
  4265. prev->call_next = o;
  4266. }
  4267. prev = o;
  4268. }
  4269. } else if (prev) {
  4270. prev->call_next = NULL;
  4271. }
  4272. numlines++;
  4273. }
  4274. if (pos > 1 /* found */ || !stillgoing /* nobody listening */ ||
  4275. (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) /* ring would not be delivered */) {
  4276. break;
  4277. }
  4278. /* On "ringall" strategy we only move to the next penalty level
  4279. when *all* ringing phones are done in the current penalty level */
  4280. ring_one(qe, outgoing, &numbusies);
  4281. /* and retry... */
  4282. }
  4283. if (pos == 1 /* not found */) {
  4284. if (numlines == (numbusies + numnochan)) {
  4285. ast_debug(1, "Everyone is busy at this time\n");
  4286. } else {
  4287. ast_debug(3, "No one is answering queue '%s' (%d numlines / %d busies / %d failed channels)\n", queue, numlines, numbusies, numnochan);
  4288. }
  4289. *to = 0;
  4290. return NULL;
  4291. }
  4292. /* Poll for events from both the incoming channel as well as any outgoing channels */
  4293. winner = ast_waitfor_n(watchers, pos, to);
  4294. /* Service all of the outgoing channels */
  4295. for (o = start; o; o = o->call_next) {
  4296. /* We go with a fixed buffer here instead of using ast_strdupa. Using
  4297. * ast_strdupa in a loop like this one can cause a stack overflow
  4298. */
  4299. char ochan_name[AST_CHANNEL_NAME];
  4300. if (o->chan) {
  4301. ast_channel_lock(o->chan);
  4302. ast_copy_string(ochan_name, ast_channel_name(o->chan), sizeof(ochan_name));
  4303. ast_channel_unlock(o->chan);
  4304. }
  4305. if (o->stillgoing && (o->chan) && (ast_channel_state(o->chan) == AST_STATE_UP)) {
  4306. if (!peer) {
  4307. ast_verb(3, "%s answered %s\n", ochan_name, inchan_name);
  4308. if (!o->block_connected_update) {
  4309. if (o->pending_connected_update) {
  4310. if (ast_channel_connected_line_sub(o->chan, in, &o->connected, 0) &&
  4311. ast_channel_connected_line_macro(o->chan, in, &o->connected, 1, 0)) {
  4312. ast_channel_update_connected_line(in, &o->connected, NULL);
  4313. }
  4314. } else if (!o->dial_callerid_absent) {
  4315. ast_channel_lock(o->chan);
  4316. ast_connected_line_copy_from_caller(&connected_caller, ast_channel_caller(o->chan));
  4317. ast_channel_unlock(o->chan);
  4318. connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  4319. if (ast_channel_connected_line_sub(o->chan, in, &connected_caller, 0) &&
  4320. ast_channel_connected_line_macro(o->chan, in, &connected_caller, 1, 0)) {
  4321. ast_channel_update_connected_line(in, &connected_caller, NULL);
  4322. }
  4323. ast_party_connected_line_free(&connected_caller);
  4324. }
  4325. }
  4326. if (o->aoc_s_rate_list) {
  4327. size_t encoded_size;
  4328. struct ast_aoc_encoded *encoded;
  4329. if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
  4330. ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
  4331. ast_aoc_destroy_encoded(encoded);
  4332. }
  4333. }
  4334. peer = o;
  4335. }
  4336. } else if (o->chan && (o->chan == winner)) {
  4337. ast_copy_string(on, o->member->interface, sizeof(on));
  4338. ast_copy_string(membername, o->member->membername, sizeof(membername));
  4339. /* Before processing channel, go ahead and check for forwarding */
  4340. if (!ast_strlen_zero(ast_channel_call_forward(o->chan)) && !forwardsallowed) {
  4341. ast_verb(3, "Forwarding %s to '%s' prevented.\n", inchan_name, ast_channel_call_forward(o->chan));
  4342. numnochan++;
  4343. do_hang(o);
  4344. winner = NULL;
  4345. continue;
  4346. } else if (!ast_strlen_zero(ast_channel_call_forward(o->chan))) {
  4347. struct ast_channel *original = o->chan;
  4348. char tmpchan[256];
  4349. char *stuff;
  4350. char *tech;
  4351. ast_copy_string(tmpchan, ast_channel_call_forward(o->chan), sizeof(tmpchan));
  4352. if ((stuff = strchr(tmpchan, '/'))) {
  4353. *stuff++ = '\0';
  4354. tech = tmpchan;
  4355. } else {
  4356. snprintf(tmpchan, sizeof(tmpchan), "%s@%s", ast_channel_call_forward(o->chan), ast_channel_context(o->chan));
  4357. stuff = tmpchan;
  4358. tech = "Local";
  4359. }
  4360. if (!strcasecmp(tech, "Local")) {
  4361. /*
  4362. * Drop the connected line update block for local channels since
  4363. * this is going to run dialplan and the user can change his
  4364. * mind about what connected line information he wants to send.
  4365. */
  4366. o->block_connected_update = 0;
  4367. }
  4368. ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", inchan_name, tech, stuff, ochan_name);
  4369. /* Setup parameters */
  4370. o->chan = ast_request(tech, ast_channel_nativeformats(in), NULL, in, stuff, &status);
  4371. if (!o->chan) {
  4372. ast_log(LOG_NOTICE,
  4373. "Forwarding failed to create channel to dial '%s/%s'\n",
  4374. tech, stuff);
  4375. o->stillgoing = 0;
  4376. numnochan++;
  4377. } else {
  4378. ast_channel_lock_both(o->chan, original);
  4379. ast_party_redirecting_copy(ast_channel_redirecting(o->chan),
  4380. ast_channel_redirecting(original));
  4381. ast_channel_unlock(o->chan);
  4382. ast_channel_unlock(original);
  4383. ast_channel_lock_both(o->chan, in);
  4384. ast_channel_inherit_variables(in, o->chan);
  4385. ast_channel_datastore_inherit(in, o->chan);
  4386. if (o->pending_connected_update) {
  4387. /*
  4388. * Re-seed the callattempt's connected line information with
  4389. * previously acquired connected line info from the queued
  4390. * channel. The previously acquired connected line info could
  4391. * have been set through the CONNECTED_LINE dialplan function.
  4392. */
  4393. o->pending_connected_update = 0;
  4394. ast_party_connected_line_copy(&o->connected, ast_channel_connected(in));
  4395. }
  4396. ast_channel_req_accountcodes(o->chan, in, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
  4397. if (!ast_channel_redirecting(o->chan)->from.number.valid
  4398. || ast_strlen_zero(ast_channel_redirecting(o->chan)->from.number.str)) {
  4399. /*
  4400. * The call was not previously redirected so it is
  4401. * now redirected from this number.
  4402. */
  4403. ast_party_number_free(&ast_channel_redirecting(o->chan)->from.number);
  4404. ast_party_number_init(&ast_channel_redirecting(o->chan)->from.number);
  4405. ast_channel_redirecting(o->chan)->from.number.valid = 1;
  4406. ast_channel_redirecting(o->chan)->from.number.str =
  4407. ast_strdup(S_OR(ast_channel_macroexten(in), ast_channel_exten(in)));
  4408. }
  4409. ast_channel_dialed(o->chan)->transit_network_select = ast_channel_dialed(in)->transit_network_select;
  4410. o->dial_callerid_absent = !ast_channel_caller(o->chan)->id.number.valid
  4411. || ast_strlen_zero(ast_channel_caller(o->chan)->id.number.str);
  4412. ast_connected_line_copy_from_caller(ast_channel_connected(o->chan),
  4413. ast_channel_caller(in));
  4414. ast_channel_unlock(in);
  4415. if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL
  4416. && !o->block_connected_update) {
  4417. struct ast_party_redirecting redirecting;
  4418. /*
  4419. * Redirecting updates to the caller make sense only on single
  4420. * call at a time strategies.
  4421. *
  4422. * We must unlock o->chan before calling
  4423. * ast_channel_redirecting_macro, because we put o->chan into
  4424. * autoservice there. That is pretty much a guaranteed
  4425. * deadlock. This is why the handling of o->chan's lock may
  4426. * seem a bit unusual here.
  4427. */
  4428. ast_party_redirecting_init(&redirecting);
  4429. ast_party_redirecting_copy(&redirecting, ast_channel_redirecting(o->chan));
  4430. ast_channel_unlock(o->chan);
  4431. if (ast_channel_redirecting_sub(o->chan, in, &redirecting, 0) &&
  4432. ast_channel_redirecting_macro(o->chan, in, &redirecting, 1, 0)) {
  4433. ast_channel_update_redirecting(in, &redirecting, NULL);
  4434. }
  4435. ast_party_redirecting_free(&redirecting);
  4436. } else {
  4437. ast_channel_unlock(o->chan);
  4438. }
  4439. if (ast_call(o->chan, stuff, 0)) {
  4440. ast_log(LOG_NOTICE, "Forwarding failed to dial '%s/%s'\n",
  4441. tech, stuff);
  4442. do_hang(o);
  4443. numnochan++;
  4444. }
  4445. }
  4446. ast_channel_publish_dial(qe->chan, o->chan, stuff, NULL);
  4447. ast_channel_publish_dial_forward(qe->chan, original, o->chan, NULL,
  4448. "CANCEL", ast_channel_call_forward(original));
  4449. /* Hangup the original channel now, in case we needed it */
  4450. ast_hangup(winner);
  4451. continue;
  4452. }
  4453. f = ast_read(winner);
  4454. if (f) {
  4455. if (f->frametype == AST_FRAME_CONTROL) {
  4456. switch (f->subclass.integer) {
  4457. case AST_CONTROL_ANSWER:
  4458. /* This is our guy if someone answered. */
  4459. if (!peer) {
  4460. ast_verb(3, "%s answered %s\n", ochan_name, inchan_name);
  4461. ast_channel_publish_dial(qe->chan, o->chan, on, "ANSWER");
  4462. publish_dial_end_event(qe->chan, outgoing, o->chan, "CANCEL");
  4463. if (!o->block_connected_update) {
  4464. if (o->pending_connected_update) {
  4465. if (ast_channel_connected_line_sub(o->chan, in, &o->connected, 0) &&
  4466. ast_channel_connected_line_macro(o->chan, in, &o->connected, 1, 0)) {
  4467. ast_channel_update_connected_line(in, &o->connected, NULL);
  4468. }
  4469. } else if (!o->dial_callerid_absent) {
  4470. ast_channel_lock(o->chan);
  4471. ast_connected_line_copy_from_caller(&connected_caller, ast_channel_caller(o->chan));
  4472. ast_channel_unlock(o->chan);
  4473. connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
  4474. if (ast_channel_connected_line_sub(o->chan, in, &connected_caller, 0) &&
  4475. ast_channel_connected_line_macro(o->chan, in, &connected_caller, 1, 0)) {
  4476. ast_channel_update_connected_line(in, &connected_caller, NULL);
  4477. }
  4478. ast_party_connected_line_free(&connected_caller);
  4479. }
  4480. }
  4481. if (o->aoc_s_rate_list) {
  4482. size_t encoded_size;
  4483. struct ast_aoc_encoded *encoded;
  4484. if ((encoded = ast_aoc_encode(o->aoc_s_rate_list, &encoded_size, o->chan))) {
  4485. ast_indicate_data(in, AST_CONTROL_AOC, encoded, encoded_size);
  4486. ast_aoc_destroy_encoded(encoded);
  4487. }
  4488. }
  4489. peer = o;
  4490. }
  4491. break;
  4492. case AST_CONTROL_BUSY:
  4493. ast_verb(3, "%s is busy\n", ochan_name);
  4494. ast_channel_publish_dial(qe->chan, o->chan, on, "BUSY");
  4495. endtime = (long) time(NULL);
  4496. endtime -= starttime;
  4497. rna(endtime * 1000, qe, o->chan, on, membername, qe->parent->autopausebusy);
  4498. do_hang(o);
  4499. if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
  4500. if (qe->parent->timeoutrestart) {
  4501. start_time_tv = ast_tvnow();
  4502. }
  4503. /* Have enough time for a queue member to answer? */
  4504. if (ast_remaining_ms(start_time_tv, orig) > 500) {
  4505. ring_one(qe, outgoing, &numbusies);
  4506. starttime = (long) time(NULL);
  4507. }
  4508. }
  4509. numbusies++;
  4510. break;
  4511. case AST_CONTROL_CONGESTION:
  4512. ast_verb(3, "%s is circuit-busy\n", ochan_name);
  4513. ast_channel_publish_dial(qe->chan, o->chan, on, "CONGESTION");
  4514. endtime = (long) time(NULL);
  4515. endtime -= starttime;
  4516. rna(endtime * 1000, qe, o->chan, on, membername, qe->parent->autopauseunavail);
  4517. do_hang(o);
  4518. if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
  4519. if (qe->parent->timeoutrestart) {
  4520. start_time_tv = ast_tvnow();
  4521. }
  4522. if (ast_remaining_ms(start_time_tv, orig) > 500) {
  4523. ring_one(qe, outgoing, &numbusies);
  4524. starttime = (long) time(NULL);
  4525. }
  4526. }
  4527. numbusies++;
  4528. break;
  4529. case AST_CONTROL_RINGING:
  4530. ast_verb(3, "%s is ringing\n", ochan_name);
  4531. /* Start ring indication when the channel is ringing, if specified */
  4532. if (qe->ring_when_ringing) {
  4533. ast_moh_stop(qe->chan);
  4534. ast_indicate(qe->chan, AST_CONTROL_RINGING);
  4535. }
  4536. break;
  4537. case AST_CONTROL_OFFHOOK:
  4538. /* Ignore going off hook */
  4539. break;
  4540. case AST_CONTROL_CONNECTED_LINE:
  4541. if (o->block_connected_update) {
  4542. ast_verb(3, "Connected line update to %s prevented.\n", inchan_name);
  4543. break;
  4544. }
  4545. if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
  4546. struct ast_party_connected_line connected;
  4547. ast_verb(3, "%s connected line has changed. Saving it until answer for %s\n", ochan_name, inchan_name);
  4548. ast_party_connected_line_set_init(&connected, &o->connected);
  4549. ast_connected_line_parse_data(f->data.ptr, f->datalen, &connected);
  4550. ast_party_connected_line_set(&o->connected, &connected, NULL);
  4551. ast_party_connected_line_free(&connected);
  4552. o->pending_connected_update = 1;
  4553. break;
  4554. }
  4555. /*
  4556. * Prevent using the CallerID from the outgoing channel since we
  4557. * got a connected line update from it.
  4558. */
  4559. o->dial_callerid_absent = 1;
  4560. if (ast_channel_connected_line_sub(o->chan, in, f, 1) &&
  4561. ast_channel_connected_line_macro(o->chan, in, f, 1, 1)) {
  4562. ast_indicate_data(in, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
  4563. }
  4564. break;
  4565. case AST_CONTROL_AOC:
  4566. {
  4567. struct ast_aoc_decoded *decoded = ast_aoc_decode(f->data.ptr, f->datalen, o->chan);
  4568. if (decoded && (ast_aoc_get_msg_type(decoded) == AST_AOC_S)) {
  4569. ast_aoc_destroy_decoded(o->aoc_s_rate_list);
  4570. o->aoc_s_rate_list = decoded;
  4571. } else {
  4572. ast_aoc_destroy_decoded(decoded);
  4573. }
  4574. }
  4575. break;
  4576. case AST_CONTROL_REDIRECTING:
  4577. if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
  4578. /*
  4579. * Redirecting updates to the caller make sense only on single
  4580. * call at a time strategies.
  4581. */
  4582. break;
  4583. }
  4584. if (o->block_connected_update) {
  4585. ast_verb(3, "Redirecting update to %s prevented\n",
  4586. inchan_name);
  4587. break;
  4588. }
  4589. ast_verb(3, "%s redirecting info has changed, passing it to %s\n",
  4590. ochan_name, inchan_name);
  4591. if (ast_channel_redirecting_sub(o->chan, in, f, 1) &&
  4592. ast_channel_redirecting_macro(o->chan, in, f, 1, 1)) {
  4593. ast_indicate_data(in, AST_CONTROL_REDIRECTING, f->data.ptr, f->datalen);
  4594. }
  4595. break;
  4596. case AST_CONTROL_PVT_CAUSE_CODE:
  4597. ast_indicate_data(in, AST_CONTROL_PVT_CAUSE_CODE, f->data.ptr, f->datalen);
  4598. break;
  4599. default:
  4600. ast_debug(1, "Dunno what to do with control type %d\n", f->subclass.integer);
  4601. break;
  4602. }
  4603. }
  4604. ast_frfree(f);
  4605. } else { /* ast_read() returned NULL */
  4606. endtime = (long) time(NULL) - starttime;
  4607. ast_channel_publish_dial(qe->chan, o->chan, on, "NOANSWER");
  4608. rna(endtime * 1000, qe, o->chan, on, membername, 1);
  4609. do_hang(o);
  4610. if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
  4611. if (qe->parent->timeoutrestart) {
  4612. start_time_tv = ast_tvnow();
  4613. }
  4614. if (ast_remaining_ms(start_time_tv, orig) > 500) {
  4615. ring_one(qe, outgoing, &numbusies);
  4616. starttime = (long) time(NULL);
  4617. }
  4618. }
  4619. }
  4620. }
  4621. }
  4622. /* If we received an event from the caller, deal with it. */
  4623. if (winner == in) {
  4624. f = ast_read(in);
  4625. if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_HANGUP))) {
  4626. /* Got hung up */
  4627. *to = -1;
  4628. publish_dial_end_event(in, outgoing, NULL, "CANCEL");
  4629. if (f) {
  4630. if (f->data.uint32) {
  4631. ast_channel_hangupcause_set(in, f->data.uint32);
  4632. }
  4633. ast_frfree(f);
  4634. }
  4635. return NULL;
  4636. }
  4637. if ((f->frametype == AST_FRAME_DTMF) && caller_disconnect && (f->subclass.integer == '*')) {
  4638. ast_verb(3, "User hit %c to disconnect call.\n", f->subclass.integer);
  4639. *to = 0;
  4640. publish_dial_end_event(in, outgoing, NULL, "CANCEL");
  4641. ast_frfree(f);
  4642. return NULL;
  4643. }
  4644. if ((f->frametype == AST_FRAME_DTMF) && valid_exit(qe, f->subclass.integer)) {
  4645. ast_verb(3, "User pressed digit: %c\n", f->subclass.integer);
  4646. *to = 0;
  4647. publish_dial_end_event(in, outgoing, NULL, "CANCEL");
  4648. *digit = f->subclass.integer;
  4649. ast_frfree(f);
  4650. return NULL;
  4651. }
  4652. /* Send the frame from the in channel to all outgoing channels. */
  4653. for (o = start; o; o = o->call_next) {
  4654. if (!o->stillgoing || !o->chan) {
  4655. /* This outgoing channel has died so don't send the frame to it. */
  4656. continue;
  4657. }
  4658. switch (f->frametype) {
  4659. case AST_FRAME_CONTROL:
  4660. switch (f->subclass.integer) {
  4661. case AST_CONTROL_CONNECTED_LINE:
  4662. if (ast_channel_connected_line_sub(in, o->chan, f, 1) &&
  4663. ast_channel_connected_line_macro(in, o->chan, f, 0, 1)) {
  4664. ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
  4665. }
  4666. break;
  4667. case AST_CONTROL_REDIRECTING:
  4668. if (ast_channel_redirecting_sub(in, o->chan, f, 1) &&
  4669. ast_channel_redirecting_macro(in, o->chan, f, 0, 1)) {
  4670. ast_indicate_data(o->chan, f->subclass.integer, f->data.ptr, f->datalen);
  4671. }
  4672. break;
  4673. default:
  4674. /* We are not going to do anything with this frame. */
  4675. goto skip_frame;
  4676. }
  4677. break;
  4678. default:
  4679. /* We are not going to do anything with this frame. */
  4680. goto skip_frame;
  4681. }
  4682. }
  4683. skip_frame:;
  4684. ast_frfree(f);
  4685. }
  4686. }
  4687. /* Make a position announcement, if enabled */
  4688. if (qe->parent->announcefrequency && qe->parent->announce_to_first_user) {
  4689. say_position(qe, ringing);
  4690. }
  4691. /* Make a periodic announcement, if enabled */
  4692. if (qe->parent->periodicannouncefrequency && qe->parent->announce_to_first_user) {
  4693. say_periodic_announcement(qe, ringing);
  4694. }
  4695. if (!*to) {
  4696. for (o = start; o; o = o->call_next) {
  4697. if (o->chan) {
  4698. rna(orig, qe, o->chan, o->interface, o->member->membername, 1);
  4699. }
  4700. }
  4701. publish_dial_end_event(qe->chan, outgoing, NULL, "NOANSWER");
  4702. }
  4703. #ifdef HAVE_EPOLL
  4704. for (epollo = outgoing; epollo; epollo = epollo->q_next) {
  4705. if (epollo->chan) {
  4706. ast_poll_channel_del(in, epollo->chan);
  4707. }
  4708. }
  4709. #endif
  4710. return peer;
  4711. }
  4712. /*!
  4713. * \brief Check if we should start attempting to call queue members.
  4714. *
  4715. * A simple process, really. Count the number of members who are available
  4716. * to take our call and then see if we are in a position in the queue at
  4717. * which a member could accept our call.
  4718. *
  4719. * \param[in] qe The caller who wants to know if it is his turn
  4720. * \retval 0 It is not our turn
  4721. * \retval 1 It is our turn
  4722. */
  4723. static int is_our_turn(struct queue_ent *qe)
  4724. {
  4725. struct queue_ent *ch;
  4726. int res;
  4727. int avl;
  4728. int idx = 0;
  4729. /* This needs a lock. How many members are available to be served? */
  4730. ao2_lock(qe->parent);
  4731. avl = num_available_members(qe->parent);
  4732. ch = qe->parent->head;
  4733. ast_debug(1, "There %s %d available %s.\n", avl != 1 ? "are" : "is", avl, avl != 1 ? "members" : "member");
  4734. while ((idx < avl) && (ch) && (ch != qe)) {
  4735. if (!ch->pending) {
  4736. idx++;
  4737. }
  4738. ch = ch->next;
  4739. }
  4740. ao2_unlock(qe->parent);
  4741. /* If the queue entry is within avl [the number of available members] calls from the top ...
  4742. * Autofill and position check added to support autofill=no (as only calls
  4743. * from the front of the queue are valid when autofill is disabled)
  4744. */
  4745. if (ch && idx < avl && (qe->parent->autofill || qe->pos == 1)) {
  4746. ast_debug(1, "It's our turn (%s).\n", ast_channel_name(qe->chan));
  4747. res = 1;
  4748. } else {
  4749. ast_debug(1, "It's not our turn (%s).\n", ast_channel_name(qe->chan));
  4750. res = 0;
  4751. }
  4752. return res;
  4753. }
  4754. /*!
  4755. * \brief update rules for queues
  4756. *
  4757. * Calculate min/max penalties making sure if relative they stay within bounds.
  4758. * Update queues penalty and set dialplan vars, goto next list entry.
  4759. */
  4760. static void update_qe_rule(struct queue_ent *qe)
  4761. {
  4762. int max_penalty = INT_MAX;
  4763. if (qe->max_penalty != INT_MAX) {
  4764. char max_penalty_str[20];
  4765. if (qe->pr->max_relative) {
  4766. max_penalty = qe->max_penalty + qe->pr->max_value;
  4767. } else {
  4768. max_penalty = qe->pr->max_value;
  4769. }
  4770. /* a relative change to the penalty could put it below 0 */
  4771. if (max_penalty < 0) {
  4772. max_penalty = 0;
  4773. }
  4774. snprintf(max_penalty_str, sizeof(max_penalty_str), "%d", max_penalty);
  4775. pbx_builtin_setvar_helper(qe->chan, "QUEUE_MAX_PENALTY", max_penalty_str);
  4776. qe->max_penalty = max_penalty;
  4777. ast_debug(3, "Setting max penalty to %d for caller %s since %d seconds have elapsed\n",
  4778. qe->max_penalty, ast_channel_name(qe->chan), qe->pr->time);
  4779. }
  4780. if (qe->min_penalty != INT_MAX) {
  4781. char min_penalty_str[20];
  4782. int min_penalty;
  4783. if (qe->pr->min_relative) {
  4784. min_penalty = qe->min_penalty + qe->pr->min_value;
  4785. } else {
  4786. min_penalty = qe->pr->min_value;
  4787. }
  4788. /* a relative change to the penalty could put it below 0 */
  4789. if (min_penalty < 0) {
  4790. min_penalty = 0;
  4791. }
  4792. if (max_penalty != INT_MAX && min_penalty > max_penalty) {
  4793. min_penalty = max_penalty;
  4794. }
  4795. snprintf(min_penalty_str, sizeof(min_penalty_str), "%d", min_penalty);
  4796. pbx_builtin_setvar_helper(qe->chan, "QUEUE_MIN_PENALTY", min_penalty_str);
  4797. qe->min_penalty = min_penalty;
  4798. ast_debug(3, "Setting min penalty to %d for caller %s since %d seconds have elapsed\n",
  4799. qe->min_penalty, ast_channel_name(qe->chan), qe->pr->time);
  4800. }
  4801. qe->pr = AST_LIST_NEXT(qe->pr, list);
  4802. }
  4803. /*! \brief The waiting areas for callers who are not actively calling members
  4804. *
  4805. * This function is one large loop. This function will return if a caller
  4806. * either exits the queue or it becomes that caller's turn to attempt calling
  4807. * queue members. Inside the loop, we service the caller with periodic announcements,
  4808. * holdtime announcements, etc. as configured in queues.conf
  4809. *
  4810. * \retval 0 if the caller's turn has arrived
  4811. * \retval -1 if the caller should exit the queue.
  4812. */
  4813. static int wait_our_turn(struct queue_ent *qe, int ringing, enum queue_result *reason)
  4814. {
  4815. int res = 0;
  4816. /* This is the holding pen for callers 2 through maxlen */
  4817. for (;;) {
  4818. if (is_our_turn(qe)) {
  4819. break;
  4820. }
  4821. /* If we have timed out, break out */
  4822. if (qe->expire && (time(NULL) >= qe->expire)) {
  4823. *reason = QUEUE_TIMEOUT;
  4824. break;
  4825. }
  4826. if (qe->parent->leavewhenempty) {
  4827. int status = 0;
  4828. if ((status = get_member_status(qe->parent, qe->max_penalty, qe->min_penalty, qe->parent->leavewhenempty, 0))) {
  4829. *reason = QUEUE_LEAVEEMPTY;
  4830. ast_queue_log(qe->parent->name, ast_channel_uniqueid(qe->chan), "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) (time(NULL) - qe->start));
  4831. leave_queue(qe);
  4832. break;
  4833. }
  4834. }
  4835. /* Make a position announcement, if enabled */
  4836. if (qe->parent->announcefrequency &&
  4837. (res = say_position(qe,ringing))) {
  4838. break;
  4839. }
  4840. /* If we have timed out, break out */
  4841. if (qe->expire && (time(NULL) >= qe->expire)) {
  4842. *reason = QUEUE_TIMEOUT;
  4843. break;
  4844. }
  4845. /* Make a periodic announcement, if enabled */
  4846. if (qe->parent->periodicannouncefrequency &&
  4847. (res = say_periodic_announcement(qe,ringing)))
  4848. break;
  4849. /* see if we need to move to the next penalty level for this queue */
  4850. while (qe->pr && ((time(NULL) - qe->start) >= qe->pr->time)) {
  4851. update_qe_rule(qe);
  4852. }
  4853. /* If we have timed out, break out */
  4854. if (qe->expire && (time(NULL) >= qe->expire)) {
  4855. *reason = QUEUE_TIMEOUT;
  4856. break;
  4857. }
  4858. /* Wait a second before checking again */
  4859. if ((res = ast_waitfordigit(qe->chan, RECHECK * 1000))) {
  4860. if (res > 0 && !valid_exit(qe, res)) {
  4861. res = 0;
  4862. } else {
  4863. break;
  4864. }
  4865. }
  4866. /* If we have timed out, break out */
  4867. if (qe->expire && (time(NULL) >= qe->expire)) {
  4868. *reason = QUEUE_TIMEOUT;
  4869. break;
  4870. }
  4871. }
  4872. return res;
  4873. }
  4874. /*!
  4875. * \brief update the queue status
  4876. * \retval Always 0
  4877. */
  4878. static int update_queue(struct call_queue *q, struct member *member, int callcompletedinsl, int newtalktime)
  4879. {
  4880. int oldtalktime;
  4881. struct member *mem;
  4882. struct call_queue *qtmp;
  4883. struct ao2_iterator queue_iter;
  4884. if (shared_lastcall) {
  4885. queue_iter = ao2_iterator_init(queues, 0);
  4886. while ((qtmp = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
  4887. ao2_lock(qtmp);
  4888. if ((mem = ao2_find(qtmp->members, member, OBJ_POINTER))) {
  4889. time(&mem->lastcall);
  4890. mem->calls++;
  4891. mem->lastqueue = q;
  4892. ao2_ref(mem, -1);
  4893. }
  4894. ao2_unlock(qtmp);
  4895. queue_t_unref(qtmp, "Done with iterator");
  4896. }
  4897. ao2_iterator_destroy(&queue_iter);
  4898. } else {
  4899. ao2_lock(q);
  4900. time(&member->lastcall);
  4901. member->calls++;
  4902. member->lastqueue = q;
  4903. ao2_unlock(q);
  4904. }
  4905. ao2_lock(q);
  4906. q->callscompleted++;
  4907. if (callcompletedinsl) {
  4908. q->callscompletedinsl++;
  4909. }
  4910. /* Calculate talktime using the same exponential average as holdtime code*/
  4911. oldtalktime = q->talktime;
  4912. q->talktime = (((oldtalktime << 2) - oldtalktime) + newtalktime) >> 2;
  4913. ao2_unlock(q);
  4914. return 0;
  4915. }
  4916. /*! \brief Calculate the metric of each member in the outgoing callattempts
  4917. *
  4918. * A numeric metric is given to each member depending on the ring strategy used
  4919. * by the queue. Members with lower metrics will be called before members with
  4920. * higher metrics
  4921. * \retval -1 if penalties are exceeded
  4922. * \retval 0 otherwise
  4923. */
  4924. static int calc_metric(struct call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct callattempt *tmp)
  4925. {
  4926. /* disregarding penalty on too few members? */
  4927. int membercount = ao2_container_count(q->members);
  4928. unsigned char usepenalty = (membercount <= q->penaltymemberslimit) ? 0 : 1;
  4929. if (usepenalty) {
  4930. if ((qe->max_penalty != INT_MAX && mem->penalty > qe->max_penalty) ||
  4931. (qe->min_penalty != INT_MAX && mem->penalty < qe->min_penalty)) {
  4932. return -1;
  4933. }
  4934. } else {
  4935. ast_debug(1, "Disregarding penalty, %d members and %d in penaltymemberslimit.\n",
  4936. membercount, q->penaltymemberslimit);
  4937. }
  4938. switch (q->strategy) {
  4939. case QUEUE_STRATEGY_RINGALL:
  4940. /* Everyone equal, except for penalty */
  4941. tmp->metric = mem->penalty * 1000000 * usepenalty;
  4942. break;
  4943. case QUEUE_STRATEGY_LINEAR:
  4944. if (pos < qe->linpos) {
  4945. tmp->metric = 1000 + pos;
  4946. } else {
  4947. if (pos > qe->linpos) {
  4948. /* Indicate there is another priority */
  4949. qe->linwrapped = 1;
  4950. }
  4951. tmp->metric = pos;
  4952. }
  4953. tmp->metric += mem->penalty * 1000000 * usepenalty;
  4954. break;
  4955. case QUEUE_STRATEGY_RRORDERED:
  4956. case QUEUE_STRATEGY_RRMEMORY:
  4957. pos = mem->queuepos;
  4958. if (pos < q->rrpos) {
  4959. tmp->metric = 1000 + pos;
  4960. } else {
  4961. if (pos > q->rrpos) {
  4962. /* Indicate there is another priority */
  4963. q->wrapped = 1;
  4964. }
  4965. tmp->metric = pos;
  4966. }
  4967. tmp->metric += mem->penalty * 1000000 * usepenalty;
  4968. break;
  4969. case QUEUE_STRATEGY_RANDOM:
  4970. tmp->metric = ast_random() % 1000;
  4971. tmp->metric += mem->penalty * 1000000 * usepenalty;
  4972. break;
  4973. case QUEUE_STRATEGY_WRANDOM:
  4974. tmp->metric = ast_random() % ((1 + mem->penalty) * 1000);
  4975. break;
  4976. case QUEUE_STRATEGY_FEWESTCALLS:
  4977. tmp->metric = mem->calls;
  4978. tmp->metric += mem->penalty * 1000000 * usepenalty;
  4979. break;
  4980. case QUEUE_STRATEGY_LEASTRECENT:
  4981. if (!mem->lastcall) {
  4982. tmp->metric = 0;
  4983. } else {
  4984. tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
  4985. }
  4986. tmp->metric += mem->penalty * 1000000 * usepenalty;
  4987. break;
  4988. default:
  4989. ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
  4990. break;
  4991. }
  4992. return 0;
  4993. }
  4994. enum agent_complete_reason {
  4995. CALLER,
  4996. AGENT,
  4997. TRANSFER
  4998. };
  4999. /*! \brief Send out AMI message with member call completion status information */
  5000. static void send_agent_complete(const char *queuename, struct ast_channel_snapshot *caller,
  5001. struct ast_channel_snapshot *peer, const struct member *member, time_t holdstart,
  5002. time_t callstart, enum agent_complete_reason rsn)
  5003. {
  5004. const char *reason = NULL; /* silence dumb compilers */
  5005. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  5006. switch (rsn) {
  5007. case CALLER:
  5008. reason = "caller";
  5009. break;
  5010. case AGENT:
  5011. reason = "agent";
  5012. break;
  5013. case TRANSFER:
  5014. reason = "transfer";
  5015. break;
  5016. }
  5017. blob = ast_json_pack("{s: s, s: s, s: s, s: i, s: i, s: s}",
  5018. "Queue", queuename,
  5019. "Interface", member->interface,
  5020. "MemberName", member->membername,
  5021. "HoldTime", (long)(callstart - holdstart),
  5022. "TalkTime", (long)(time(NULL) - callstart),
  5023. "Reason", reason);
  5024. queue_publish_multi_channel_snapshot_blob(ast_queue_topic(queuename), caller, peer,
  5025. queue_agent_complete_type(), blob);
  5026. }
  5027. static void queue_agent_cb(void *userdata, struct stasis_subscription *sub,
  5028. struct stasis_message *msg)
  5029. {
  5030. struct ast_channel_blob *agent_blob;
  5031. agent_blob = stasis_message_data(msg);
  5032. if (ast_channel_agent_login_type() == stasis_message_type(msg)) {
  5033. ast_queue_log("NONE", agent_blob->snapshot->uniqueid,
  5034. ast_json_string_get(ast_json_object_get(agent_blob->blob, "agent")),
  5035. "AGENTLOGIN", "%s", agent_blob->snapshot->name);
  5036. } else if (ast_channel_agent_logoff_type() == stasis_message_type(msg)) {
  5037. ast_queue_log("NONE", agent_blob->snapshot->uniqueid,
  5038. ast_json_string_get(ast_json_object_get(agent_blob->blob, "agent")),
  5039. "AGENTLOGOFF", "%s|%ld", agent_blob->snapshot->name,
  5040. (long) ast_json_integer_get(ast_json_object_get(agent_blob->blob, "logintime")));
  5041. }
  5042. }
  5043. /*!
  5044. * \brief Structure representing relevant data during a local channel optimization
  5045. *
  5046. * The reason we care about local channel optimizations is that we want to be able
  5047. * to accurately report when the caller and queue member have stopped talking to
  5048. * each other. A local channel optimization can cause it to appear that the conversation
  5049. * has stopped immediately after it has begun. By tracking that the relevant channels
  5050. * to monitor have changed due to a local channel optimization, we can give accurate
  5051. * reports.
  5052. *
  5053. * Local channel optimizations for queues are restricted from their normal operation.
  5054. * Bridges created by queues can only be the destination of local channel optimizations,
  5055. * not the source. In addition, move-swap local channel optimizations are the only
  5056. * permitted types of local channel optimization.
  5057. *
  5058. * This data is populated when we are told that a local channel optimization begin
  5059. * is occurring. When we get told the optimization has ended successfully, we then
  5060. * apply the data here into the queue_stasis_data.
  5061. */
  5062. struct local_optimization {
  5063. /*! The uniqueid of the channel that will be taking the place of the caller or member */
  5064. const char *source_chan_uniqueid;
  5065. /*! Indication of whether we think there is a local channel optimization in progress */
  5066. int in_progress;
  5067. /*! The identifier for this local channel optimization */
  5068. unsigned int id;
  5069. };
  5070. /*!
  5071. * \brief User data for stasis subscriptions used for queue calls.
  5072. *
  5073. * app_queue subscribes to channel and bridge events for all bridged calls.
  5074. * app_queue cares about the following events:
  5075. *
  5076. * \li bridge enter: To determine the unique ID of the bridge created for the call.
  5077. * \li blind transfer: To send an appropriate agent complete event.
  5078. * \li attended transfer: To send an appropriate agent complete event.
  5079. * \li local optimization: To update caller and member unique IDs for the call.
  5080. * \li hangup: To send an appropriate agent complete event.
  5081. *
  5082. * The stasis subscriptions last until we determine that the caller and the member
  5083. * are no longer bridged with each other.
  5084. */
  5085. struct queue_stasis_data {
  5086. AST_DECLARE_STRING_FIELDS(
  5087. /*! The unique ID of the caller's channel. */
  5088. AST_STRING_FIELD(caller_uniqueid);
  5089. /*! The unique ID of the queue member's channel */
  5090. AST_STRING_FIELD(member_uniqueid);
  5091. /*! The unique ID of the bridge created by the queue */
  5092. AST_STRING_FIELD(bridge_uniqueid);
  5093. );
  5094. /*! The relevant queue */
  5095. struct call_queue *queue;
  5096. /*! The queue member that has answered the call */
  5097. struct member *member;
  5098. /*! The time at which the caller entered the queue. Start of the caller's hold time */
  5099. time_t holdstart;
  5100. /*! The time at which the member answered the call. */
  5101. time_t starttime;
  5102. /*! The original position of the caller when he entered the queue */
  5103. int caller_pos;
  5104. /*! Indication if the call was answered within the configured service level of the queue */
  5105. int callcompletedinsl;
  5106. /*! Indicates if the stasis subscriptions are shutting down */
  5107. int dying;
  5108. /*! The stasis message router for bridge events */
  5109. struct stasis_message_router *bridge_router;
  5110. /*! The stasis message router for channel events */
  5111. struct stasis_message_router *channel_router;
  5112. /*! Local channel optimization details for the caller */
  5113. struct local_optimization caller_optimize;
  5114. /*! Local channel optimization details for the member */
  5115. struct local_optimization member_optimize;
  5116. };
  5117. /*!
  5118. * \internal
  5119. * \brief Free memory for a queue_stasis_data
  5120. */
  5121. static void queue_stasis_data_destructor(void *obj)
  5122. {
  5123. struct queue_stasis_data *queue_data = obj;
  5124. /* This can only happen if refcounts for this object have got severely messed up */
  5125. ast_assert(queue_data->bridge_router == NULL);
  5126. ast_assert(queue_data->channel_router == NULL);
  5127. ao2_cleanup(queue_data->member);
  5128. queue_unref(queue_data->queue);
  5129. ast_string_field_free_memory(queue_data);
  5130. }
  5131. /*!
  5132. * \internal
  5133. * \brief End all stasis subscriptions on a queue_stasis_data
  5134. */
  5135. static void remove_stasis_subscriptions(struct queue_stasis_data *queue_data)
  5136. {
  5137. SCOPED_AO2LOCK(lock, queue_data);
  5138. queue_data->dying = 1;
  5139. stasis_message_router_unsubscribe(queue_data->bridge_router);
  5140. queue_data->bridge_router = NULL;
  5141. stasis_message_router_unsubscribe(queue_data->channel_router);
  5142. queue_data->channel_router = NULL;
  5143. }
  5144. /*!
  5145. * \internal
  5146. * \brief Allocate a queue_stasis_data and initialize its data.
  5147. */
  5148. static struct queue_stasis_data *queue_stasis_data_alloc(struct queue_ent *qe,
  5149. struct ast_channel *peer, struct member *mem, time_t holdstart,
  5150. time_t starttime, int callcompletedinsl)
  5151. {
  5152. struct queue_stasis_data *queue_data;
  5153. queue_data = ao2_alloc(sizeof(*queue_data), queue_stasis_data_destructor);
  5154. if (!queue_data) {
  5155. return NULL;
  5156. }
  5157. if (ast_string_field_init(queue_data, 64)) {
  5158. ao2_cleanup(queue_data);
  5159. return NULL;
  5160. }
  5161. ast_string_field_set(queue_data, caller_uniqueid, ast_channel_uniqueid(qe->chan));
  5162. ast_string_field_set(queue_data, member_uniqueid, ast_channel_uniqueid(peer));
  5163. queue_data->queue = queue_ref(qe->parent);
  5164. queue_data->starttime = starttime;
  5165. queue_data->holdstart = holdstart;
  5166. queue_data->callcompletedinsl = callcompletedinsl;
  5167. queue_data->caller_pos = qe->opos;
  5168. ao2_ref(mem, +1);
  5169. queue_data->member = mem;
  5170. return queue_data;
  5171. }
  5172. /*!
  5173. * \internal
  5174. * \brief Log an attended transfer in the queue log.
  5175. *
  5176. * Attended transfer queue log messages vary based on the method by which the
  5177. * attended transfer was completed.
  5178. *
  5179. * \param queue_data Data pertaining to the particular call in the queue.
  5180. * \param caller The channel snapshot for the caller channel in the queue.
  5181. * \param atxfer_msg The stasis attended transfer message data.
  5182. */
  5183. static void log_attended_transfer(struct queue_stasis_data *queue_data, struct ast_channel_snapshot *caller,
  5184. struct ast_attended_transfer_message *atxfer_msg)
  5185. {
  5186. RAII_VAR(struct ast_str *, transfer_str, ast_str_create(32), ast_free);
  5187. if (!transfer_str) {
  5188. ast_log(LOG_WARNING, "Unable to log attended transfer to queue log\n");
  5189. return;
  5190. }
  5191. switch (atxfer_msg->dest_type) {
  5192. case AST_ATTENDED_TRANSFER_DEST_BRIDGE_MERGE:
  5193. ast_str_set(&transfer_str, 0, "BRIDGE|%s", atxfer_msg->dest.bridge);
  5194. break;
  5195. case AST_ATTENDED_TRANSFER_DEST_APP:
  5196. case AST_ATTENDED_TRANSFER_DEST_LOCAL_APP:
  5197. ast_str_set(&transfer_str, 0, "APP|%s", atxfer_msg->dest.app);
  5198. break;
  5199. case AST_ATTENDED_TRANSFER_DEST_LINK:
  5200. ast_str_set(&transfer_str, 0, "LINK|%s|%s", atxfer_msg->dest.links[0]->name,
  5201. atxfer_msg->dest.links[1]->name);
  5202. break;
  5203. case AST_ATTENDED_TRANSFER_DEST_THREEWAY:
  5204. case AST_ATTENDED_TRANSFER_DEST_FAIL:
  5205. /* Threeways are headed off and should not be logged here */
  5206. ast_assert(0);
  5207. return;
  5208. }
  5209. ast_queue_log(queue_data->queue->name, caller->uniqueid, queue_data->member->membername, "ATTENDEDTRANSFER", "%s|%ld|%ld|%d",
  5210. ast_str_buffer(transfer_str),
  5211. (long) (queue_data->starttime - queue_data->holdstart),
  5212. (long) (time(NULL) - queue_data->starttime), queue_data->caller_pos);
  5213. }
  5214. /*!
  5215. * \internal
  5216. * \brief Handle a stasis bridge enter event.
  5217. *
  5218. * We track this particular event in order to learn what bridge
  5219. * was created for the queue call.
  5220. *
  5221. * \param userdata Data pertaining to the particular call in the queue.
  5222. * \param sub The stasis subscription on which the message occurred.
  5223. * \param topic The topic for this event.
  5224. * \param msg The stasis message for the bridge enter event
  5225. */
  5226. static void handle_bridge_enter(void *userdata, struct stasis_subscription *sub,
  5227. struct stasis_message *msg)
  5228. {
  5229. struct queue_stasis_data *queue_data = userdata;
  5230. struct ast_bridge_blob *enter_blob = stasis_message_data(msg);
  5231. if (queue_data->dying) {
  5232. return;
  5233. }
  5234. if (!ast_strlen_zero(queue_data->bridge_uniqueid)) {
  5235. return;
  5236. }
  5237. if (!strcmp(enter_blob->channel->uniqueid, queue_data->caller_uniqueid)) {
  5238. ast_string_field_set(queue_data, bridge_uniqueid,
  5239. enter_blob->bridge->uniqueid);
  5240. ast_debug(3, "Detected entry of caller channel %s into bridge %s\n",
  5241. enter_blob->channel->name, queue_data->bridge_uniqueid);
  5242. }
  5243. }
  5244. /*!
  5245. * \brief Handle a blind transfer event
  5246. *
  5247. * This event is important in order to be able to log the end of the
  5248. * call to the queue log and to stasis.
  5249. *
  5250. * \param userdata Data pertaining to the particular call in the queue.
  5251. * \param sub The stasis subscription on which the message occurred.
  5252. * \param topic The topic for this event.
  5253. * \param msg The stasis message for the blind transfer event
  5254. */
  5255. static void handle_blind_transfer(void *userdata, struct stasis_subscription *sub,
  5256. struct stasis_message *msg)
  5257. {
  5258. struct queue_stasis_data *queue_data = userdata;
  5259. struct ast_blind_transfer_message *transfer_msg = stasis_message_data(msg);
  5260. const char *exten;
  5261. const char *context;
  5262. RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
  5263. RAII_VAR(struct ast_channel_snapshot *, member_snapshot, NULL, ao2_cleanup);
  5264. if (queue_data->dying) {
  5265. return;
  5266. }
  5267. if (transfer_msg->result != AST_BRIDGE_TRANSFER_SUCCESS) {
  5268. return;
  5269. }
  5270. ao2_lock(queue_data);
  5271. if (ast_strlen_zero(queue_data->bridge_uniqueid) ||
  5272. strcmp(queue_data->bridge_uniqueid, transfer_msg->bridge->uniqueid)) {
  5273. ao2_unlock(queue_data);
  5274. return;
  5275. }
  5276. caller_snapshot = ast_channel_snapshot_get_latest(queue_data->caller_uniqueid);
  5277. member_snapshot = ast_channel_snapshot_get_latest(queue_data->member_uniqueid);
  5278. ao2_unlock(queue_data);
  5279. exten = transfer_msg->exten;
  5280. context = transfer_msg->context;
  5281. ast_debug(3, "Detected blind transfer in queue %s\n", queue_data->queue->name);
  5282. ast_queue_log(queue_data->queue->name, caller_snapshot->uniqueid, queue_data->member->membername,
  5283. "BLINDTRANSFER", "%s|%s|%ld|%ld|%d",
  5284. exten, context,
  5285. (long) (queue_data->starttime - queue_data->holdstart),
  5286. (long) (time(NULL) - queue_data->starttime), queue_data->caller_pos);
  5287. send_agent_complete(queue_data->queue->name, caller_snapshot, member_snapshot, queue_data->member,
  5288. queue_data->holdstart, queue_data->starttime, TRANSFER);
  5289. update_queue(queue_data->queue, queue_data->member, queue_data->callcompletedinsl,
  5290. time(NULL) - queue_data->starttime);
  5291. remove_stasis_subscriptions(queue_data);
  5292. }
  5293. /*!
  5294. * \brief Handle an attended transfer event
  5295. *
  5296. * This event is important in order to be able to log the end of the
  5297. * call to the queue log and to stasis.
  5298. *
  5299. * \param userdata Data pertaining to the particular call in the queue.
  5300. * \param sub The stasis subscription on which the message occurred.
  5301. * \param topic The topic for this event.
  5302. * \param msg The stasis message for the attended transfer event.
  5303. */
  5304. static void handle_attended_transfer(void *userdata, struct stasis_subscription *sub,
  5305. struct stasis_message *msg)
  5306. {
  5307. struct queue_stasis_data *queue_data = userdata;
  5308. struct ast_attended_transfer_message *atxfer_msg = stasis_message_data(msg);
  5309. RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
  5310. RAII_VAR(struct ast_channel_snapshot *, member_snapshot, NULL, ao2_cleanup);
  5311. if (queue_data->dying) {
  5312. return;
  5313. }
  5314. if (atxfer_msg->result != AST_BRIDGE_TRANSFER_SUCCESS ||
  5315. atxfer_msg->dest_type == AST_ATTENDED_TRANSFER_DEST_THREEWAY) {
  5316. return;
  5317. }
  5318. ao2_lock(queue_data);
  5319. if (ast_strlen_zero(queue_data->bridge_uniqueid)) {
  5320. ao2_unlock(queue_data);
  5321. return;
  5322. }
  5323. if ((!atxfer_msg->to_transferee.bridge_snapshot || strcmp(queue_data->bridge_uniqueid,
  5324. atxfer_msg->to_transferee.bridge_snapshot->uniqueid)) &&
  5325. (!atxfer_msg->to_transfer_target.bridge_snapshot || strcmp(queue_data->bridge_uniqueid,
  5326. atxfer_msg->to_transfer_target.bridge_snapshot->uniqueid))) {
  5327. ao2_unlock(queue_data);
  5328. return;
  5329. }
  5330. caller_snapshot = ast_channel_snapshot_get_latest(queue_data->caller_uniqueid);
  5331. member_snapshot = ast_channel_snapshot_get_latest(queue_data->member_uniqueid);
  5332. ao2_unlock(queue_data);
  5333. ast_debug(3, "Detected attended transfer in queue %s\n", queue_data->queue->name);
  5334. log_attended_transfer(queue_data, caller_snapshot, atxfer_msg);
  5335. send_agent_complete(queue_data->queue->name, caller_snapshot, member_snapshot, queue_data->member,
  5336. queue_data->holdstart, queue_data->starttime, TRANSFER);
  5337. update_queue(queue_data->queue, queue_data->member, queue_data->callcompletedinsl,
  5338. time(NULL) - queue_data->starttime);
  5339. remove_stasis_subscriptions(queue_data);
  5340. }
  5341. /*!
  5342. * \internal
  5343. * \brief Callback for all stasis bridge events
  5344. *
  5345. * Based on the event and what bridge it is on, the task is farmed out to relevant
  5346. * subroutines for further processing.
  5347. */
  5348. static void queue_bridge_cb(void *userdata, struct stasis_subscription *sub,
  5349. struct stasis_message *msg)
  5350. {
  5351. if (stasis_subscription_final_message(sub, msg)) {
  5352. ao2_cleanup(userdata);
  5353. }
  5354. }
  5355. /*!
  5356. * \internal
  5357. * \brief Handler for the beginning of a local channel optimization
  5358. *
  5359. * This method gathers data relevant to the local channel optimization and stores
  5360. * it to be used once the local optimization completes.
  5361. *
  5362. * \param userdata Data pertaining to the particular call in the queue.
  5363. * \param sub The stasis subscription on which the message occurred.
  5364. * \param topic The topic for this event.
  5365. * \param msg The stasis message for the local optimization begin event
  5366. */
  5367. static void handle_local_optimization_begin(void *userdata, struct stasis_subscription *sub,
  5368. struct stasis_message *msg)
  5369. {
  5370. struct queue_stasis_data *queue_data = userdata;
  5371. struct ast_multi_channel_blob *optimization_blob = stasis_message_data(msg);
  5372. struct ast_channel_snapshot *local_one = ast_multi_channel_blob_get_channel(optimization_blob, "1");
  5373. struct ast_channel_snapshot *local_two = ast_multi_channel_blob_get_channel(optimization_blob, "2");
  5374. struct ast_channel_snapshot *source = ast_multi_channel_blob_get_channel(optimization_blob, "source");
  5375. struct local_optimization *optimization;
  5376. unsigned int id;
  5377. SCOPED_AO2LOCK(lock, queue_data);
  5378. if (queue_data->dying) {
  5379. return;
  5380. }
  5381. if (!strcmp(local_one->uniqueid, queue_data->member_uniqueid)) {
  5382. optimization = &queue_data->member_optimize;
  5383. } else if (!strcmp(local_two->uniqueid, queue_data->caller_uniqueid)) {
  5384. optimization = &queue_data->caller_optimize;
  5385. } else {
  5386. return;
  5387. }
  5388. /* We only allow move-swap optimizations, so there had BETTER be a source */
  5389. ast_assert(source != NULL);
  5390. optimization->source_chan_uniqueid = ast_strdup(source->uniqueid);
  5391. if (!optimization->source_chan_uniqueid) {
  5392. ast_log(LOG_ERROR, "Unable to track local channel optimization for channel %s. Expect further errors\n", local_one->name);
  5393. return;
  5394. }
  5395. id = ast_json_integer_get(ast_json_object_get(ast_multi_channel_blob_get_json(optimization_blob), "id"));
  5396. optimization->id = id;
  5397. optimization->in_progress = 1;
  5398. }
  5399. /*!
  5400. * \internal
  5401. * \brief Handler for the end of a local channel optimization
  5402. *
  5403. * This method takes the data gathered during the local channel optimization begin
  5404. * event and applies it to the queue stasis data appropriately. This generally involves
  5405. * updating the caller or member unique ID with the channel that is taking the place of
  5406. * the previous caller or member.
  5407. *
  5408. * \param userdata Data pertaining to the particular call in the queue.
  5409. * \param sub The stasis subscription on which the message occurred.
  5410. * \param topic The topic for this event.
  5411. * \param msg The stasis message for the local optimization end event
  5412. */
  5413. static void handle_local_optimization_end(void *userdata, struct stasis_subscription *sub,
  5414. struct stasis_message *msg)
  5415. {
  5416. struct queue_stasis_data *queue_data = userdata;
  5417. struct ast_multi_channel_blob *optimization_blob = stasis_message_data(msg);
  5418. struct ast_channel_snapshot *local_one = ast_multi_channel_blob_get_channel(optimization_blob, "1");
  5419. struct ast_channel_snapshot *local_two = ast_multi_channel_blob_get_channel(optimization_blob, "2");
  5420. struct local_optimization *optimization;
  5421. int is_caller;
  5422. unsigned int id;
  5423. SCOPED_AO2LOCK(lock, queue_data);
  5424. if (queue_data->dying) {
  5425. return;
  5426. }
  5427. if (!strcmp(local_one->uniqueid, queue_data->member_uniqueid)) {
  5428. optimization = &queue_data->member_optimize;
  5429. is_caller = 0;
  5430. } else if (!strcmp(local_two->uniqueid, queue_data->caller_uniqueid)) {
  5431. optimization = &queue_data->caller_optimize;
  5432. is_caller = 1;
  5433. } else {
  5434. return;
  5435. }
  5436. id = ast_json_integer_get(ast_json_object_get(ast_multi_channel_blob_get_json(optimization_blob), "id"));
  5437. if (!optimization->in_progress) {
  5438. ast_log(LOG_WARNING, "Told of a local optimization end when we had no previous begin\n");
  5439. return;
  5440. }
  5441. if (id != optimization->id) {
  5442. ast_log(LOG_WARNING, "Local optimization end event ID does not match begin (%u != %u)\n",
  5443. id, optimization->id);
  5444. return;
  5445. }
  5446. if (is_caller) {
  5447. ast_debug(3, "Local optimization: Changing queue caller uniqueid from %s to %s\n",
  5448. queue_data->caller_uniqueid, optimization->source_chan_uniqueid);
  5449. ast_string_field_set(queue_data, caller_uniqueid, optimization->source_chan_uniqueid);
  5450. } else {
  5451. ast_debug(3, "Local optimization: Changing queue member uniqueid from %s to %s\n",
  5452. queue_data->member_uniqueid, optimization->source_chan_uniqueid);
  5453. ast_string_field_set(queue_data, member_uniqueid, optimization->source_chan_uniqueid);
  5454. }
  5455. optimization->in_progress = 0;
  5456. }
  5457. /*!
  5458. * \internal
  5459. * \brief Handler for hangup stasis event
  5460. *
  5461. * This is how we determine that the caller or member has hung up and the call
  5462. * has ended. An appropriate queue log and stasis message are raised in this
  5463. * callback.
  5464. *
  5465. * \param userdata Data pertaining to the particular call in the queue.
  5466. * \param sub The stasis subscription on which the message occurred.
  5467. * \param topic The topic for this event.
  5468. * \param msg The stasis message for the hangup event.
  5469. */
  5470. static void handle_hangup(void *userdata, struct stasis_subscription *sub,
  5471. struct stasis_message *msg)
  5472. {
  5473. struct queue_stasis_data *queue_data = userdata;
  5474. struct ast_channel_blob *channel_blob = stasis_message_data(msg);
  5475. RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
  5476. RAII_VAR(struct ast_channel_snapshot *, member_snapshot, NULL, ao2_cleanup);
  5477. RAII_VAR(struct ast_channel *, chan, NULL, ao2_cleanup);
  5478. enum agent_complete_reason reason;
  5479. if (queue_data->dying) {
  5480. return;
  5481. }
  5482. ao2_lock(queue_data);
  5483. if (!strcmp(channel_blob->snapshot->uniqueid, queue_data->caller_uniqueid)) {
  5484. reason = CALLER;
  5485. } else if (!strcmp(channel_blob->snapshot->uniqueid, queue_data->member_uniqueid)) {
  5486. reason = AGENT;
  5487. } else {
  5488. ao2_unlock(queue_data);
  5489. return;
  5490. }
  5491. chan = ast_channel_get_by_name(channel_blob->snapshot->name);
  5492. if (chan && ast_channel_has_role(chan, AST_TRANSFERER_ROLE_NAME)) {
  5493. /* Channel that is hanging up is doing it as part of a transfer.
  5494. * We'll get a transfer event later
  5495. */
  5496. ao2_unlock(queue_data);
  5497. return;
  5498. }
  5499. caller_snapshot = ast_channel_snapshot_get_latest(queue_data->caller_uniqueid);
  5500. member_snapshot = ast_channel_snapshot_get_latest(queue_data->member_uniqueid);
  5501. ao2_unlock(queue_data);
  5502. ast_debug(3, "Detected hangup of queue %s channel %s\n", reason == CALLER ? "caller" : "member",
  5503. channel_blob->snapshot->name);
  5504. ast_queue_log(queue_data->queue->name, queue_data->caller_uniqueid, queue_data->member->membername,
  5505. reason == CALLER ? "COMPLETECALLER" : "COMPLETEAGENT", "%ld|%ld|%d",
  5506. (long) (queue_data->starttime - queue_data->holdstart),
  5507. (long) (time(NULL) - queue_data->starttime), queue_data->caller_pos);
  5508. send_agent_complete(queue_data->queue->name, caller_snapshot, member_snapshot, queue_data->member,
  5509. queue_data->holdstart, queue_data->starttime, reason);
  5510. update_queue(queue_data->queue, queue_data->member, queue_data->callcompletedinsl,
  5511. time(NULL) - queue_data->starttime);
  5512. remove_stasis_subscriptions(queue_data);
  5513. }
  5514. /*!
  5515. * \internal
  5516. * \brief Callback for all stasis channel events
  5517. *
  5518. * Based on the event and the channels involved, the work is farmed out into
  5519. * subroutines for further processing.
  5520. */
  5521. static void queue_channel_cb(void *userdata, struct stasis_subscription *sub,
  5522. struct stasis_message *msg)
  5523. {
  5524. if (stasis_subscription_final_message(sub, msg)) {
  5525. ao2_cleanup(userdata);
  5526. }
  5527. }
  5528. /*!
  5529. * \internal
  5530. * \brief Create stasis subscriptions for a particular call in the queue.
  5531. *
  5532. * These subscriptions are created once the call has been answered. The subscriptions
  5533. * are put in place so that call progress may be tracked. Once the call can be determined
  5534. * to have ended, then messages are logged to the queue log and stasis events are emitted.
  5535. *
  5536. * \param qe The queue entry representing the caller
  5537. * \param peer The channel that has answered the call
  5538. * \param mem The queue member that answered the call
  5539. * \param holdstart The time at which the caller entered the queue
  5540. * \param starttime The time at which the call was answered
  5541. * \param callcompletedinsl Indicates if the call was answered within the configured service level of the queue.
  5542. * \retval 0 Success
  5543. * \retval non-zero Failure
  5544. */
  5545. static int setup_stasis_subs(struct queue_ent *qe, struct ast_channel *peer, struct member *mem,
  5546. time_t holdstart, time_t starttime, int callcompletedinsl)
  5547. {
  5548. struct queue_stasis_data *queue_data = queue_stasis_data_alloc(qe, peer, mem, holdstart, starttime, callcompletedinsl);
  5549. if (!queue_data) {
  5550. return -1;
  5551. }
  5552. queue_data->bridge_router = stasis_message_router_create_pool(ast_bridge_topic_all());
  5553. if (!queue_data->bridge_router) {
  5554. ao2_ref(queue_data, -1);
  5555. return -1;
  5556. }
  5557. stasis_message_router_add(queue_data->bridge_router, ast_channel_entered_bridge_type(),
  5558. handle_bridge_enter, queue_data);
  5559. stasis_message_router_add(queue_data->bridge_router, ast_blind_transfer_type(),
  5560. handle_blind_transfer, queue_data);
  5561. stasis_message_router_add(queue_data->bridge_router, ast_attended_transfer_type(),
  5562. handle_attended_transfer, queue_data);
  5563. stasis_message_router_set_default(queue_data->bridge_router,
  5564. queue_bridge_cb, queue_data);
  5565. queue_data->channel_router = stasis_message_router_create_pool(ast_channel_topic_all());
  5566. if (!queue_data->channel_router) {
  5567. /* Unsubscribing from the bridge router will remove the only ref of queue_data,
  5568. * thus beginning the destruction process
  5569. */
  5570. stasis_message_router_unsubscribe(queue_data->bridge_router);
  5571. queue_data->bridge_router = NULL;
  5572. return -1;
  5573. }
  5574. ao2_ref(queue_data, +1);
  5575. stasis_message_router_add(queue_data->channel_router, ast_local_optimization_begin_type(),
  5576. handle_local_optimization_begin, queue_data);
  5577. stasis_message_router_add(queue_data->channel_router, ast_local_optimization_end_type(),
  5578. handle_local_optimization_end, queue_data);
  5579. stasis_message_router_add(queue_data->channel_router, ast_channel_hangup_request_type(),
  5580. handle_hangup, queue_data);
  5581. stasis_message_router_set_default(queue_data->channel_router,
  5582. queue_channel_cb, queue_data);
  5583. return 0;
  5584. }
  5585. struct queue_end_bridge {
  5586. struct call_queue *q;
  5587. struct ast_channel *chan;
  5588. };
  5589. static void end_bridge_callback_data_fixup(struct ast_bridge_config *bconfig, struct ast_channel *originator, struct ast_channel *terminator)
  5590. {
  5591. struct queue_end_bridge *qeb = bconfig->end_bridge_callback_data;
  5592. ao2_ref(qeb, +1);
  5593. qeb->chan = originator;
  5594. }
  5595. static void end_bridge_callback(void *data)
  5596. {
  5597. struct queue_end_bridge *qeb = data;
  5598. struct call_queue *q = qeb->q;
  5599. struct ast_channel *chan = qeb->chan;
  5600. if (ao2_ref(qeb, -1) == 1) {
  5601. set_queue_variables(q, chan);
  5602. /* This unrefs the reference we made in try_calling when we allocated qeb */
  5603. queue_t_unref(q, "Expire bridge_config reference");
  5604. }
  5605. }
  5606. /*!
  5607. * \internal
  5608. * \brief Setup the after bridge goto location on the peer.
  5609. * \since 12.0.0
  5610. *
  5611. * \param chan Calling channel for bridge.
  5612. * \param peer Peer channel for bridge.
  5613. * \param opts Dialing option flags.
  5614. * \param opt_args Dialing option argument strings.
  5615. *
  5616. * \return Nothing
  5617. */
  5618. static void setup_peer_after_bridge_goto(struct ast_channel *chan, struct ast_channel *peer, struct ast_flags *opts, char *opt_args[])
  5619. {
  5620. const char *context;
  5621. const char *extension;
  5622. int priority;
  5623. if (ast_test_flag(opts, OPT_CALLEE_GO_ON)) {
  5624. ast_channel_lock(chan);
  5625. context = ast_strdupa(ast_channel_context(chan));
  5626. extension = ast_strdupa(ast_channel_exten(chan));
  5627. priority = ast_channel_priority(chan);
  5628. ast_channel_unlock(chan);
  5629. ast_bridge_set_after_go_on(peer, context, extension, priority,
  5630. opt_args[OPT_ARG_CALLEE_GO_ON]);
  5631. }
  5632. }
  5633. static void escape_and_substitute(struct ast_channel *chan, const char *input,
  5634. char *output, size_t size)
  5635. {
  5636. const char *m = input;
  5637. char escaped[size];
  5638. char *p;
  5639. for (p = escaped; p < escaped + size - 1; p++, m++) {
  5640. switch (*m) {
  5641. case '^':
  5642. if (*(m + 1) == '{') {
  5643. *p = '$';
  5644. }
  5645. break;
  5646. case ',':
  5647. *p++ = '\\';
  5648. /* Fall through */
  5649. default:
  5650. *p = *m;
  5651. }
  5652. if (*m == '\0')
  5653. break;
  5654. }
  5655. if (p == escaped + size) {
  5656. escaped[size - 1] = '\0';
  5657. }
  5658. pbx_substitute_variables_helper(chan, escaped, output, size - 1);
  5659. }
  5660. static void setup_mixmonitor(struct queue_ent *qe, const char *filename)
  5661. {
  5662. char escaped_filename[256];
  5663. char file_with_ext[256];
  5664. char mixmonargs[1512];
  5665. char escaped_monitor_exec[1024];
  5666. const char *monitor_options;
  5667. const char *monitor_exec;
  5668. escaped_monitor_exec[0] = '\0';
  5669. if (filename) {
  5670. escape_and_substitute(qe->chan, filename, escaped_filename, sizeof(escaped_filename));
  5671. } else {
  5672. ast_copy_string(escaped_filename, ast_channel_uniqueid(qe->chan), sizeof(escaped_filename));
  5673. }
  5674. ast_channel_lock(qe->chan);
  5675. if ((monitor_exec = pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC"))) {
  5676. monitor_exec = ast_strdupa(monitor_exec);
  5677. }
  5678. if ((monitor_options = pbx_builtin_getvar_helper(qe->chan, "MONITOR_OPTIONS"))) {
  5679. monitor_options = ast_strdupa(monitor_options);
  5680. } else {
  5681. monitor_options = "";
  5682. }
  5683. ast_channel_unlock(qe->chan);
  5684. if (monitor_exec) {
  5685. escape_and_substitute(qe->chan, monitor_exec, escaped_monitor_exec, sizeof(escaped_monitor_exec));
  5686. }
  5687. snprintf(file_with_ext, sizeof(file_with_ext), "%s.%s", escaped_filename, qe->parent->monfmt);
  5688. if (!ast_strlen_zero(escaped_monitor_exec)) {
  5689. snprintf(mixmonargs, sizeof(mixmonargs), "b%s,%s", monitor_options, escaped_monitor_exec);
  5690. } else {
  5691. snprintf(mixmonargs, sizeof(mixmonargs), "b%s", monitor_options);
  5692. }
  5693. ast_debug(1, "Arguments being passed to MixMonitor: %s,%s\n", file_with_ext, mixmonargs);
  5694. if (ast_start_mixmonitor(qe->chan, file_with_ext, mixmonargs)) {
  5695. ast_log(LOG_WARNING, "Unable to start mixmonitor. Is the MixMonitor app loaded?\n");
  5696. }
  5697. }
  5698. /*!
  5699. * \internal
  5700. * \brief A large function which calls members, updates statistics, and bridges the caller and a member
  5701. *
  5702. * Here is the process of this function
  5703. * 1. Process any options passed to the Queue() application. Options here mean the third argument to Queue()
  5704. * 2. Iterate trough the members of the queue, creating a callattempt corresponding to each member. During this
  5705. * iteration, we also check the dialed_interfaces datastore to see if we have already attempted calling this
  5706. * member. If we have, we do not create a callattempt. This is in place to prevent call forwarding loops. Also
  5707. * during each iteration, we call calc_metric to determine which members should be rung when.
  5708. * 3. Call ring_one to place a call to the appropriate member(s)
  5709. * 4. Call wait_for_answer to wait for an answer. If no one answers, return.
  5710. * 5. Take care of any holdtime announcements, member delays, or other options which occur after a call has been answered.
  5711. * 6. Start the monitor or mixmonitor if the option is set
  5712. * 7. Remove the caller from the queue to allow other callers to advance
  5713. * 8. Bridge the call.
  5714. * 9. Do any post processing after the call has disconnected.
  5715. *
  5716. * \param[in] qe the queue_ent structure which corresponds to the caller attempting to reach members
  5717. * \param[in] opts the options passed as the third parameter to the Queue() application
  5718. * \param[in] opt_args the options passed as the third parameter to the Queue() application
  5719. * \param[in] announceoverride filename to play to user when waiting
  5720. * \param[in] url the url passed as the fourth parameter to the Queue() application
  5721. * \param[in,out] tries the number of times we have tried calling queue members
  5722. * \param[out] noption set if the call to Queue() has the 'n' option set.
  5723. * \param[in] agi the agi passed as the fifth parameter to the Queue() application
  5724. * \param[in] macro the macro passed as the sixth parameter to the Queue() application
  5725. * \param[in] gosub the gosub passed as the seventh parameter to the Queue() application
  5726. * \param[in] ringing 1 if the 'r' option is set, otherwise 0
  5727. */
  5728. static int try_calling(struct queue_ent *qe, struct ast_flags opts, char **opt_args, char *announceoverride, const char *url, int *tries, int *noption, const char *agi, const char *macro, const char *gosub, int ringing)
  5729. {
  5730. struct member *cur;
  5731. struct callattempt *outgoing = NULL; /* the list of calls we are building */
  5732. int to, orig;
  5733. char oldexten[AST_MAX_EXTENSION]="";
  5734. char oldcontext[AST_MAX_CONTEXT]="";
  5735. char queuename[256]="";
  5736. char interfacevar[256]="";
  5737. struct ast_channel *peer;
  5738. struct ast_channel *which;
  5739. struct callattempt *lpeer;
  5740. struct member *member;
  5741. struct ast_app *application;
  5742. int res = 0, bridge = 0;
  5743. int numbusies = 0;
  5744. int x=0;
  5745. char *announce = NULL;
  5746. char digit = 0;
  5747. time_t callstart;
  5748. time_t now = time(NULL);
  5749. struct ast_bridge_config bridge_config;
  5750. char nondataquality = 1;
  5751. char *agiexec = NULL;
  5752. char *macroexec = NULL;
  5753. char *gosubexec = NULL;
  5754. const char *monitorfilename;
  5755. char tmpid[256];
  5756. int forwardsallowed = 1;
  5757. int block_connected_line = 0;
  5758. int callcompletedinsl;
  5759. struct ao2_iterator memi;
  5760. struct ast_datastore *datastore;
  5761. struct queue_end_bridge *queue_end_bridge = NULL;
  5762. ast_channel_lock(qe->chan);
  5763. datastore = ast_channel_datastore_find(qe->chan, &dialed_interface_info, NULL);
  5764. ast_channel_unlock(qe->chan);
  5765. memset(&bridge_config, 0, sizeof(bridge_config));
  5766. tmpid[0] = 0;
  5767. time(&now);
  5768. /* If we've already exceeded our timeout, then just stop
  5769. * This should be extremely rare. queue_exec will take care
  5770. * of removing the caller and reporting the timeout as the reason.
  5771. */
  5772. if (qe->expire && now >= qe->expire) {
  5773. res = 0;
  5774. goto out;
  5775. }
  5776. if (ast_test_flag(&opts, OPT_CALLEE_TRANSFER)) {
  5777. ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_REDIRECT);
  5778. }
  5779. if (ast_test_flag(&opts, OPT_CALLER_TRANSFER)) {
  5780. ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_REDIRECT);
  5781. }
  5782. if (ast_test_flag(&opts, OPT_CALLEE_AUTOMON)) {
  5783. ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMON);
  5784. }
  5785. if (ast_test_flag(&opts, OPT_CALLER_AUTOMON)) {
  5786. ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMON);
  5787. }
  5788. if (ast_test_flag(&opts, OPT_DATA_QUALITY)) {
  5789. nondataquality = 0;
  5790. }
  5791. if (ast_test_flag(&opts, OPT_CALLEE_HANGUP)) {
  5792. ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_DISCONNECT);
  5793. }
  5794. if (ast_test_flag(&opts, OPT_CALLER_HANGUP)) {
  5795. ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT);
  5796. }
  5797. if (ast_test_flag(&opts, OPT_CALLEE_PARK)) {
  5798. ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_PARKCALL);
  5799. }
  5800. if (ast_test_flag(&opts, OPT_CALLER_PARK)) {
  5801. ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_PARKCALL);
  5802. }
  5803. if (ast_test_flag(&opts, OPT_NO_RETRY)) {
  5804. if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY || qe->parent->strategy == QUEUE_STRATEGY_LINEAR
  5805. || qe->parent->strategy == QUEUE_STRATEGY_RRORDERED) {
  5806. (*tries)++;
  5807. } else {
  5808. *tries = ao2_container_count(qe->parent->members);
  5809. }
  5810. *noption = 1;
  5811. }
  5812. if (ast_test_flag(&opts, OPT_IGNORE_CALL_FW)) {
  5813. forwardsallowed = 0;
  5814. }
  5815. if (ast_test_flag(&opts, OPT_IGNORE_CONNECTEDLINE)) {
  5816. block_connected_line = 1;
  5817. }
  5818. if (ast_test_flag(&opts, OPT_CALLEE_AUTOMIXMON)) {
  5819. ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMIXMON);
  5820. }
  5821. if (ast_test_flag(&opts, OPT_CALLER_AUTOMIXMON)) {
  5822. ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMIXMON);
  5823. }
  5824. if (ast_test_flag(&opts, OPT_MARK_AS_ANSWERED)) {
  5825. qe->cancel_answered_elsewhere = 1;
  5826. }
  5827. /* if the calling channel has AST_CAUSE_ANSWERED_ELSEWHERE set, make sure this is inherited.
  5828. (this is mainly to support unreal/local channels)
  5829. */
  5830. if (ast_channel_hangupcause(qe->chan) == AST_CAUSE_ANSWERED_ELSEWHERE) {
  5831. qe->cancel_answered_elsewhere = 1;
  5832. }
  5833. ao2_lock(qe->parent);
  5834. ast_debug(1, "%s is trying to call a queue member.\n",
  5835. ast_channel_name(qe->chan));
  5836. ast_copy_string(queuename, qe->parent->name, sizeof(queuename));
  5837. if (!ast_strlen_zero(qe->announce)) {
  5838. announce = qe->announce;
  5839. }
  5840. if (!ast_strlen_zero(announceoverride)) {
  5841. announce = announceoverride;
  5842. }
  5843. memi = ao2_iterator_init(qe->parent->members, 0);
  5844. while ((cur = ao2_iterator_next(&memi))) {
  5845. struct callattempt *tmp = ast_calloc(1, sizeof(*tmp));
  5846. struct ast_dialed_interface *di;
  5847. AST_LIST_HEAD(,ast_dialed_interface) *dialed_interfaces;
  5848. if (!tmp) {
  5849. ao2_ref(cur, -1);
  5850. ao2_iterator_destroy(&memi);
  5851. ao2_unlock(qe->parent);
  5852. goto out;
  5853. }
  5854. if (!datastore) {
  5855. if (!(datastore = ast_datastore_alloc(&dialed_interface_info, NULL))) {
  5856. callattempt_free(tmp);
  5857. ao2_ref(cur, -1);
  5858. ao2_iterator_destroy(&memi);
  5859. ao2_unlock(qe->parent);
  5860. goto out;
  5861. }
  5862. datastore->inheritance = DATASTORE_INHERIT_FOREVER;
  5863. if (!(dialed_interfaces = ast_calloc(1, sizeof(*dialed_interfaces)))) {
  5864. callattempt_free(tmp);
  5865. ao2_ref(cur, -1);
  5866. ao2_iterator_destroy(&memi);
  5867. ao2_unlock(qe->parent);
  5868. goto out;
  5869. }
  5870. datastore->data = dialed_interfaces;
  5871. AST_LIST_HEAD_INIT(dialed_interfaces);
  5872. ast_channel_lock(qe->chan);
  5873. ast_channel_datastore_add(qe->chan, datastore);
  5874. ast_channel_unlock(qe->chan);
  5875. } else
  5876. dialed_interfaces = datastore->data;
  5877. AST_LIST_LOCK(dialed_interfaces);
  5878. AST_LIST_TRAVERSE(dialed_interfaces, di, list) {
  5879. if (!strcasecmp(cur->interface, di->interface)) {
  5880. ast_debug(1, "Skipping dialing interface '%s' since it has already been dialed\n",
  5881. di->interface);
  5882. break;
  5883. }
  5884. }
  5885. AST_LIST_UNLOCK(dialed_interfaces);
  5886. if (di) {
  5887. callattempt_free(tmp);
  5888. ao2_ref(cur, -1);
  5889. continue;
  5890. }
  5891. /* It is always ok to dial a Local interface. We only keep track of
  5892. * which "real" interfaces have been dialed. The Local channel will
  5893. * inherit this list so that if it ends up dialing a real interface,
  5894. * it won't call one that has already been called. */
  5895. if (strncasecmp(cur->interface, "Local/", 6)) {
  5896. if (!(di = ast_calloc(1, sizeof(*di) + strlen(cur->interface)))) {
  5897. callattempt_free(tmp);
  5898. ao2_ref(cur, -1);
  5899. ao2_iterator_destroy(&memi);
  5900. ao2_unlock(qe->parent);
  5901. goto out;
  5902. }
  5903. strcpy(di->interface, cur->interface);
  5904. AST_LIST_LOCK(dialed_interfaces);
  5905. AST_LIST_INSERT_TAIL(dialed_interfaces, di, list);
  5906. AST_LIST_UNLOCK(dialed_interfaces);
  5907. }
  5908. /*
  5909. * Seed the callattempt's connected line information with previously
  5910. * acquired connected line info from the queued channel. The
  5911. * previously acquired connected line info could have been set
  5912. * through the CONNECTED_LINE dialplan function.
  5913. */
  5914. ast_channel_lock(qe->chan);
  5915. ast_party_connected_line_copy(&tmp->connected, ast_channel_connected(qe->chan));
  5916. ast_channel_unlock(qe->chan);
  5917. tmp->block_connected_update = block_connected_line;
  5918. tmp->stillgoing = 1;
  5919. tmp->member = cur;/* Place the reference for cur into callattempt. */
  5920. tmp->lastcall = cur->lastcall;
  5921. tmp->lastqueue = cur->lastqueue;
  5922. ast_copy_string(tmp->interface, cur->interface, sizeof(tmp->interface));
  5923. /* Special case: If we ring everyone, go ahead and ring them, otherwise
  5924. just calculate their metric for the appropriate strategy */
  5925. if (!calc_metric(qe->parent, cur, x++, qe, tmp)) {
  5926. /* Put them in the list of outgoing thingies... We're ready now.
  5927. XXX If we're forcibly removed, these outgoing calls won't get
  5928. hung up XXX */
  5929. tmp->q_next = outgoing;
  5930. outgoing = tmp;
  5931. /* If this line is up, don't try anybody else */
  5932. if (outgoing->chan && (ast_channel_state(outgoing->chan) == AST_STATE_UP))
  5933. break;
  5934. } else {
  5935. callattempt_free(tmp);
  5936. }
  5937. }
  5938. ao2_iterator_destroy(&memi);
  5939. if (qe->parent->timeoutpriority == TIMEOUT_PRIORITY_APP) {
  5940. /* Application arguments have higher timeout priority (behaviour for <=1.6) */
  5941. if (qe->expire && (!qe->parent->timeout || (qe->expire - now) <= qe->parent->timeout)) {
  5942. to = (qe->expire - now) * 1000;
  5943. } else {
  5944. to = (qe->parent->timeout) ? qe->parent->timeout * 1000 : -1;
  5945. }
  5946. } else {
  5947. /* Config timeout is higher priority thatn application timeout */
  5948. if (qe->expire && qe->expire<=now) {
  5949. to = 0;
  5950. } else if (qe->parent->timeout) {
  5951. to = qe->parent->timeout * 1000;
  5952. } else {
  5953. to = -1;
  5954. }
  5955. }
  5956. orig = to;
  5957. ++qe->pending;
  5958. ao2_unlock(qe->parent);
  5959. ring_one(qe, outgoing, &numbusies);
  5960. lpeer = wait_for_answer(qe, outgoing, &to, &digit, numbusies,
  5961. ast_test_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT),
  5962. forwardsallowed, ringing);
  5963. /* The ast_channel_datastore_remove() function could fail here if the
  5964. * datastore was moved to another channel during a masquerade. If this is
  5965. * the case, don't free the datastore here because later, when the channel
  5966. * to which the datastore was moved hangs up, it will attempt to free this
  5967. * datastore again, causing a crash
  5968. */
  5969. ast_channel_lock(qe->chan);
  5970. if (datastore && !ast_channel_datastore_remove(qe->chan, datastore)) {
  5971. ast_datastore_free(datastore);
  5972. }
  5973. ast_channel_unlock(qe->chan);
  5974. ao2_lock(qe->parent);
  5975. if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY || qe->parent->strategy == QUEUE_STRATEGY_RRORDERED) {
  5976. store_next_rr(qe, outgoing);
  5977. }
  5978. if (qe->parent->strategy == QUEUE_STRATEGY_LINEAR) {
  5979. store_next_lin(qe, outgoing);
  5980. }
  5981. ao2_unlock(qe->parent);
  5982. peer = lpeer ? lpeer->chan : NULL;
  5983. if (!peer) {
  5984. qe->pending = 0;
  5985. if (to) {
  5986. /* Must gotten hung up */
  5987. res = -1;
  5988. } else {
  5989. /* User exited by pressing a digit */
  5990. res = digit;
  5991. }
  5992. if (res == -1) {
  5993. ast_debug(1, "%s: Nobody answered.\n", ast_channel_name(qe->chan));
  5994. }
  5995. } else { /* peer is valid */
  5996. RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
  5997. /* Ah ha! Someone answered within the desired timeframe. Of course after this
  5998. we will always return with -1 so that it is hung up properly after the
  5999. conversation. */
  6000. if (!strcmp(ast_channel_tech(qe->chan)->type, "DAHDI")) {
  6001. ast_channel_setoption(qe->chan, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
  6002. }
  6003. if (!strcmp(ast_channel_tech(peer)->type, "DAHDI")) {
  6004. ast_channel_setoption(peer, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
  6005. }
  6006. /* Update parameters for the queue */
  6007. time(&now);
  6008. recalc_holdtime(qe, (now - qe->start));
  6009. ao2_lock(qe->parent);
  6010. callcompletedinsl = ((now - qe->start) <= qe->parent->servicelevel);
  6011. ao2_unlock(qe->parent);
  6012. member = lpeer->member;
  6013. /* Increment the refcount for this member, since we're going to be using it for awhile in here. */
  6014. ao2_ref(member, 1);
  6015. hangupcalls(qe, outgoing, peer, qe->cancel_answered_elsewhere);
  6016. outgoing = NULL;
  6017. if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
  6018. int res2;
  6019. res2 = ast_autoservice_start(qe->chan);
  6020. if (!res2) {
  6021. if (qe->parent->memberdelay) {
  6022. ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
  6023. res2 = ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
  6024. }
  6025. if (!res2 && announce) {
  6026. if (play_file(peer, announce) < 0) {
  6027. ast_log(LOG_ERROR, "play_file failed for '%s' on %s\n", announce, ast_channel_name(peer));
  6028. }
  6029. }
  6030. if (!res2 && qe->parent->reportholdtime) {
  6031. if (!play_file(peer, qe->parent->sound_reporthold)) {
  6032. long holdtime, holdtimesecs;
  6033. time(&now);
  6034. holdtime = labs((now - qe->start) / 60);
  6035. holdtimesecs = labs((now - qe->start) % 60);
  6036. if (holdtime > 0) {
  6037. ast_say_number(peer, holdtime, AST_DIGIT_ANY, ast_channel_language(peer), NULL);
  6038. if (play_file(peer, qe->parent->sound_minutes) < 0) {
  6039. ast_log(LOG_ERROR, "play_file failed for '%s' on %s\n", qe->parent->sound_minutes, ast_channel_name(peer));
  6040. }
  6041. }
  6042. if (holdtimesecs > 1) {
  6043. ast_say_number(peer, holdtimesecs, AST_DIGIT_ANY, ast_channel_language(peer), NULL);
  6044. if (play_file(peer, qe->parent->sound_seconds) < 0) {
  6045. ast_log(LOG_ERROR, "play_file failed for '%s' on %s\n", qe->parent->sound_seconds, ast_channel_name(peer));
  6046. }
  6047. }
  6048. }
  6049. }
  6050. ast_autoservice_stop(qe->chan);
  6051. }
  6052. if (ast_check_hangup(peer)) {
  6053. /* Agent must have hung up */
  6054. ast_log(LOG_WARNING, "Agent on %s hungup on the customer.\n", ast_channel_name(peer));
  6055. ast_queue_log(queuename, ast_channel_uniqueid(qe->chan), member->membername, "AGENTDUMP", "%s", "");
  6056. blob = ast_json_pack("{s: s, s: s, s: s}",
  6057. "Queue", queuename,
  6058. "Interface", member->interface,
  6059. "MemberName", member->membername);
  6060. queue_publish_multi_channel_blob(qe->chan, peer, queue_agent_dump_type(), blob);
  6061. ast_channel_publish_dial(qe->chan, peer, member->interface, ast_hangup_cause_to_dial_status(ast_channel_hangupcause(peer)));
  6062. ast_autoservice_chan_hangup_peer(qe->chan, peer);
  6063. ao2_ref(member, -1);
  6064. goto out;
  6065. } else if (ast_check_hangup(qe->chan)) {
  6066. /* Caller must have hung up just before being connected */
  6067. ast_log(LOG_NOTICE, "Caller was about to talk to agent on %s but the caller hungup.\n", ast_channel_name(peer));
  6068. ast_queue_log(queuename, ast_channel_uniqueid(qe->chan), member->membername, "ABANDON", "%d|%d|%ld", qe->pos, qe->opos, (long) (time(NULL) - qe->start));
  6069. record_abandoned(qe);
  6070. ast_channel_publish_dial(qe->chan, peer, member->interface, ast_hangup_cause_to_dial_status(ast_channel_hangupcause(peer)));
  6071. ast_autoservice_chan_hangup_peer(qe->chan, peer);
  6072. ao2_ref(member, -1);
  6073. return -1;
  6074. }
  6075. }
  6076. /* Stop music on hold */
  6077. if (ringing) {
  6078. ast_indicate(qe->chan,-1);
  6079. } else {
  6080. ast_moh_stop(qe->chan);
  6081. }
  6082. /* Make sure channels are compatible */
  6083. res = ast_channel_make_compatible(qe->chan, peer);
  6084. if (res < 0) {
  6085. ast_queue_log(queuename, ast_channel_uniqueid(qe->chan), member->membername, "SYSCOMPAT", "%s", "");
  6086. ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", ast_channel_name(qe->chan), ast_channel_name(peer));
  6087. record_abandoned(qe);
  6088. ast_channel_publish_dial(qe->chan, peer, member->interface, ast_hangup_cause_to_dial_status(ast_channel_hangupcause(peer)));
  6089. ast_autoservice_chan_hangup_peer(qe->chan, peer);
  6090. ao2_ref(member, -1);
  6091. return -1;
  6092. }
  6093. /* Play announcement to the caller telling it's his turn if defined */
  6094. if (!ast_strlen_zero(qe->parent->sound_callerannounce)) {
  6095. if (play_file(qe->chan, qe->parent->sound_callerannounce)) {
  6096. ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", qe->parent->sound_callerannounce);
  6097. }
  6098. }
  6099. ao2_lock(qe->parent);
  6100. /* if setinterfacevar is defined, make member variables available to the channel */
  6101. /* use pbx_builtin_setvar to set a load of variables with one call */
  6102. if (qe->parent->setinterfacevar) {
  6103. snprintf(interfacevar, sizeof(interfacevar), "MEMBERINTERFACE=%s,MEMBERNAME=%s,MEMBERCALLS=%d,MEMBERLASTCALL=%ld,MEMBERPENALTY=%d,MEMBERDYNAMIC=%d,MEMBERREALTIME=%d",
  6104. member->interface, member->membername, member->calls, (long)member->lastcall, member->penalty, member->dynamic, member->realtime);
  6105. pbx_builtin_setvar_multiple(qe->chan, interfacevar);
  6106. pbx_builtin_setvar_multiple(peer, interfacevar);
  6107. }
  6108. /* if setqueueentryvar is defined, make queue entry (i.e. the caller) variables available to the channel */
  6109. /* use pbx_builtin_setvar to set a load of variables with one call */
  6110. if (qe->parent->setqueueentryvar) {
  6111. snprintf(interfacevar, sizeof(interfacevar), "QEHOLDTIME=%ld,QEORIGINALPOS=%d",
  6112. (long) (time(NULL) - qe->start), qe->opos);
  6113. pbx_builtin_setvar_multiple(qe->chan, interfacevar);
  6114. pbx_builtin_setvar_multiple(peer, interfacevar);
  6115. }
  6116. ao2_unlock(qe->parent);
  6117. /* try to set queue variables if configured to do so*/
  6118. set_queue_variables(qe->parent, qe->chan);
  6119. set_queue_variables(qe->parent, peer);
  6120. setup_peer_after_bridge_goto(qe->chan, peer, &opts, opt_args);
  6121. ast_channel_lock(qe->chan);
  6122. if ((monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME"))) {
  6123. monitorfilename = ast_strdupa(monitorfilename);
  6124. }
  6125. ast_channel_unlock(qe->chan);
  6126. /* Begin Monitoring */
  6127. if (*qe->parent->monfmt) {
  6128. if (!qe->parent->montype) {
  6129. const char *monexec;
  6130. ast_debug(1, "Starting Monitor as requested.\n");
  6131. ast_channel_lock(qe->chan);
  6132. if ((monexec = pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC")) || pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC_ARGS")) {
  6133. which = qe->chan;
  6134. monexec = monexec ? ast_strdupa(monexec) : NULL;
  6135. } else {
  6136. which = peer;
  6137. }
  6138. ast_channel_unlock(qe->chan);
  6139. if (monitorfilename) {
  6140. ast_monitor_start(which, qe->parent->monfmt, monitorfilename, 1, X_REC_IN | X_REC_OUT, NULL);
  6141. } else if (qe->chan) {
  6142. ast_monitor_start(which, qe->parent->monfmt, ast_channel_uniqueid(qe->chan), 1, X_REC_IN | X_REC_OUT, NULL);
  6143. } else {
  6144. /* Last ditch effort -- no channel, make up something */
  6145. snprintf(tmpid, sizeof(tmpid), "chan-%lx", (unsigned long)ast_random());
  6146. ast_monitor_start(which, qe->parent->monfmt, tmpid, 1, X_REC_IN | X_REC_OUT, NULL);
  6147. }
  6148. if (!ast_strlen_zero(monexec)) {
  6149. ast_monitor_setjoinfiles(which, 1);
  6150. }
  6151. } else {
  6152. setup_mixmonitor(qe, monitorfilename);
  6153. }
  6154. }
  6155. /* Drop out of the queue at this point, to prepare for next caller */
  6156. leave_queue(qe);
  6157. if (!ast_strlen_zero(url) && ast_channel_supports_html(peer)) {
  6158. ast_debug(1, "app_queue: sendurl=%s.\n", url);
  6159. ast_channel_sendurl(peer, url);
  6160. }
  6161. /* run a macro for this connection if defined. The macro simply returns, no action is taken on the result */
  6162. /* use macro from dialplan if passed as a option, otherwise use the default queue macro */
  6163. if (!ast_strlen_zero(macro)) {
  6164. macroexec = ast_strdupa(macro);
  6165. } else {
  6166. if (qe->parent->membermacro) {
  6167. macroexec = ast_strdupa(qe->parent->membermacro);
  6168. }
  6169. }
  6170. if (!ast_strlen_zero(macroexec)) {
  6171. ast_debug(1, "app_queue: macro=%s.\n", macroexec);
  6172. ast_app_exec_macro(qe->chan, peer, macroexec);
  6173. }
  6174. /* run a gosub for this connection if defined. The gosub simply returns, no action is taken on the result */
  6175. /* use gosub from dialplan if passed as a option, otherwise use the default queue gosub */
  6176. if (!ast_strlen_zero(gosub)) {
  6177. gosubexec = ast_strdupa(gosub);
  6178. } else {
  6179. if (qe->parent->membergosub) {
  6180. gosubexec = ast_strdupa(qe->parent->membergosub);
  6181. }
  6182. }
  6183. if (!ast_strlen_zero(gosubexec)) {
  6184. char *gosub_args = NULL;
  6185. char *gosub_argstart;
  6186. ast_debug(1, "app_queue: gosub=%s.\n", gosubexec);
  6187. gosub_argstart = strchr(gosubexec, ',');
  6188. if (gosub_argstart) {
  6189. const char *what_is_s = "s";
  6190. *gosub_argstart = 0;
  6191. if (!ast_exists_extension(peer, gosubexec, "s", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL)) &&
  6192. ast_exists_extension(peer, gosubexec, "~~s~~", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL))) {
  6193. what_is_s = "~~s~~";
  6194. }
  6195. if (ast_asprintf(&gosub_args, "%s,%s,1(%s)", gosubexec, what_is_s, gosub_argstart + 1) < 0) {
  6196. gosub_args = NULL;
  6197. }
  6198. *gosub_argstart = ',';
  6199. } else {
  6200. const char *what_is_s = "s";
  6201. if (!ast_exists_extension(peer, gosubexec, "s", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL)) &&
  6202. ast_exists_extension(peer, gosubexec, "~~s~~", 1, S_COR(ast_channel_caller(peer)->id.number.valid, ast_channel_caller(peer)->id.number.str, NULL))) {
  6203. what_is_s = "~~s~~";
  6204. }
  6205. if (ast_asprintf(&gosub_args, "%s,%s,1", gosubexec, what_is_s) < 0) {
  6206. gosub_args = NULL;
  6207. }
  6208. }
  6209. if (gosub_args) {
  6210. ast_app_exec_sub(qe->chan, peer, gosub_args, 0);
  6211. ast_free(gosub_args);
  6212. } else {
  6213. ast_log(LOG_ERROR, "Could not Allocate string for Gosub arguments -- Gosub Call Aborted!\n");
  6214. }
  6215. }
  6216. if (!ast_strlen_zero(agi)) {
  6217. ast_debug(1, "app_queue: agi=%s.\n", agi);
  6218. application = pbx_findapp("agi");
  6219. if (application) {
  6220. agiexec = ast_strdupa(agi);
  6221. pbx_exec(qe->chan, application, agiexec);
  6222. } else {
  6223. ast_log(LOG_WARNING, "Asked to execute an AGI on this channel, but could not find application (agi)!\n");
  6224. }
  6225. }
  6226. qe->handled++;
  6227. ast_queue_log(queuename, ast_channel_uniqueid(qe->chan), member->membername, "CONNECT", "%ld|%s|%ld", (long) (time(NULL) - qe->start), ast_channel_uniqueid(peer),
  6228. (long)(orig - to > 0 ? (orig - to) / 1000 : 0));
  6229. blob = ast_json_pack("{s: s, s: s, s: s, s: i, s: i}",
  6230. "Queue", queuename,
  6231. "Interface", member->interface,
  6232. "MemberName", member->membername,
  6233. "HoldTime", (long) (time(NULL) - qe->start),
  6234. "RingTime", (long)(orig - to > 0 ? (orig - to) / 1000 : 0));
  6235. queue_publish_multi_channel_blob(qe->chan, peer, queue_agent_connect_type(), blob);
  6236. ast_copy_string(oldcontext, ast_channel_context(qe->chan), sizeof(oldcontext));
  6237. ast_copy_string(oldexten, ast_channel_exten(qe->chan), sizeof(oldexten));
  6238. if ((queue_end_bridge = ao2_alloc(sizeof(*queue_end_bridge), NULL))) {
  6239. queue_end_bridge->q = qe->parent;
  6240. queue_end_bridge->chan = qe->chan;
  6241. bridge_config.end_bridge_callback = end_bridge_callback;
  6242. bridge_config.end_bridge_callback_data = queue_end_bridge;
  6243. bridge_config.end_bridge_callback_data_fixup = end_bridge_callback_data_fixup;
  6244. /* Since queue_end_bridge can survive beyond the life of this call to Queue, we need
  6245. * to make sure to increase the refcount of this queue so it cannot be freed until we
  6246. * are done with it. We remove this reference in end_bridge_callback.
  6247. */
  6248. queue_t_ref(qe->parent, "For bridge_config reference");
  6249. }
  6250. time(&callstart);
  6251. setup_stasis_subs(qe, peer, member, qe->start, callstart, callcompletedinsl);
  6252. bridge = ast_bridge_call_with_flags(qe->chan, peer, &bridge_config,
  6253. AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM | AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM);
  6254. res = bridge ? bridge : 1;
  6255. ao2_ref(member, -1);
  6256. }
  6257. out:
  6258. hangupcalls(qe, outgoing, NULL, qe->cancel_answered_elsewhere);
  6259. return res;
  6260. }
  6261. static int wait_a_bit(struct queue_ent *qe)
  6262. {
  6263. /* Don't need to hold the lock while we setup the outgoing calls */
  6264. int retrywait = qe->parent->retry * 1000;
  6265. int res = ast_waitfordigit(qe->chan, retrywait);
  6266. if (res > 0 && !valid_exit(qe, res)) {
  6267. res = 0;
  6268. }
  6269. return res;
  6270. }
  6271. static struct member *interface_exists(struct call_queue *q, const char *interface)
  6272. {
  6273. struct member *mem;
  6274. struct ao2_iterator mem_iter;
  6275. if (!q) {
  6276. return NULL;
  6277. }
  6278. mem_iter = ao2_iterator_init(q->members, 0);
  6279. while ((mem = ao2_iterator_next(&mem_iter))) {
  6280. if (!strcasecmp(interface, mem->interface)) {
  6281. ao2_iterator_destroy(&mem_iter);
  6282. return mem;
  6283. }
  6284. ao2_ref(mem, -1);
  6285. }
  6286. ao2_iterator_destroy(&mem_iter);
  6287. return NULL;
  6288. }
  6289. /*! \brief Dump all members in a specific queue to the database
  6290. * \code
  6291. * <pm_family>/<queuename> = <interface>;<penalty>;<paused>;<state_interface>[|...]
  6292. * \endcode
  6293. */
  6294. static void dump_queue_members(struct call_queue *pm_queue)
  6295. {
  6296. struct member *cur_member;
  6297. struct ast_str *value;
  6298. struct ao2_iterator mem_iter;
  6299. if (!pm_queue) {
  6300. return;
  6301. }
  6302. /* 4K is a reasonable default for most applications, but we grow to
  6303. * accommodate more if necessary. */
  6304. if (!(value = ast_str_create(4096))) {
  6305. return;
  6306. }
  6307. mem_iter = ao2_iterator_init(pm_queue->members, 0);
  6308. while ((cur_member = ao2_iterator_next(&mem_iter))) {
  6309. if (!cur_member->dynamic) {
  6310. ao2_ref(cur_member, -1);
  6311. continue;
  6312. }
  6313. ast_str_append(&value, 0, "%s%s;%d;%d;%s;%s",
  6314. ast_str_strlen(value) ? "|" : "",
  6315. cur_member->interface,
  6316. cur_member->penalty,
  6317. cur_member->paused,
  6318. cur_member->membername,
  6319. cur_member->state_interface);
  6320. ao2_ref(cur_member, -1);
  6321. }
  6322. ao2_iterator_destroy(&mem_iter);
  6323. if (ast_str_strlen(value) && !cur_member) {
  6324. if (ast_db_put(pm_family, pm_queue->name, ast_str_buffer(value))) {
  6325. ast_log(LOG_WARNING, "failed to create persistent dynamic entry!\n");
  6326. }
  6327. } else {
  6328. /* Delete the entry if the queue is empty or there is an error */
  6329. ast_db_del(pm_family, pm_queue->name);
  6330. }
  6331. ast_free(value);
  6332. }
  6333. /*! \brief Remove member from queue
  6334. * \retval RES_NOT_DYNAMIC when they aren't a RT member
  6335. * \retval RES_NOSUCHQUEUE queue does not exist
  6336. * \retval RES_OKAY removed member from queue
  6337. * \retval RES_EXISTS queue exists but no members
  6338. */
  6339. static int remove_from_queue(const char *queuename, const char *interface)
  6340. {
  6341. struct call_queue *q, tmpq = {
  6342. .name = queuename,
  6343. };
  6344. struct member *mem, tmpmem;
  6345. int res = RES_NOSUCHQUEUE;
  6346. ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
  6347. if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Temporary reference for interface removal"))) {
  6348. ao2_lock(q);
  6349. if ((mem = ao2_find(q->members, &tmpmem, OBJ_POINTER))) {
  6350. /* XXX future changes should beware of this assumption!! */
  6351. /*Change Penalty on realtime users*/
  6352. if (mem->realtime && !ast_strlen_zero(mem->rt_uniqueid) && negative_penalty_invalid) {
  6353. update_realtime_member_field(mem, q->name, "penalty", "-1");
  6354. } else if (!mem->dynamic) {
  6355. ao2_ref(mem, -1);
  6356. ao2_unlock(q);
  6357. queue_t_unref(q, "Interface wasn't dynamic, expiring temporary reference");
  6358. return RES_NOT_DYNAMIC;
  6359. }
  6360. queue_publish_member_blob(queue_member_removed_type(), queue_member_blob_create(q, mem));
  6361. member_remove_from_queue(q, mem);
  6362. ao2_ref(mem, -1);
  6363. if (queue_persistent_members) {
  6364. dump_queue_members(q);
  6365. }
  6366. if (!num_available_members(q)) {
  6367. ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
  6368. }
  6369. res = RES_OKAY;
  6370. } else {
  6371. res = RES_EXISTS;
  6372. }
  6373. ao2_unlock(q);
  6374. queue_t_unref(q, "Expiring temporary reference");
  6375. }
  6376. return res;
  6377. }
  6378. /*! \brief Add member to queue
  6379. * \retval RES_NOT_DYNAMIC when they aren't a RT member
  6380. * \retval RES_NOSUCHQUEUE queue does not exist
  6381. * \retval RES_OKAY added member from queue
  6382. * \retval RES_EXISTS queue exists but no members
  6383. * \retval RES_OUT_OF_MEMORY queue exists but not enough memory to create member
  6384. */
  6385. static int add_to_queue(const char *queuename, const char *interface, const char *membername, int penalty, int paused, int dump, const char *state_interface)
  6386. {
  6387. struct call_queue *q;
  6388. struct member *new_member, *old_member;
  6389. int res = RES_NOSUCHQUEUE;
  6390. /*! \note Ensure the appropriate realtime queue is loaded. Note that this
  6391. * short-circuits if the queue is already in memory. */
  6392. if (!(q = find_load_queue_rt_friendly(queuename))) {
  6393. return res;
  6394. }
  6395. ao2_lock(q);
  6396. if ((old_member = interface_exists(q, interface)) == NULL) {
  6397. if ((new_member = create_queue_member(interface, membername, penalty, paused, state_interface, q->ringinuse))) {
  6398. new_member->ringinuse = q->ringinuse;
  6399. new_member->dynamic = 1;
  6400. member_add_to_queue(q, new_member);
  6401. queue_publish_member_blob(queue_member_added_type(), queue_member_blob_create(q, new_member));
  6402. if (is_member_available(q, new_member)) {
  6403. ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
  6404. }
  6405. ao2_ref(new_member, -1);
  6406. new_member = NULL;
  6407. if (dump) {
  6408. dump_queue_members(q);
  6409. }
  6410. res = RES_OKAY;
  6411. } else {
  6412. res = RES_OUTOFMEMORY;
  6413. }
  6414. } else {
  6415. ao2_ref(old_member, -1);
  6416. res = RES_EXISTS;
  6417. }
  6418. ao2_unlock(q);
  6419. queue_t_unref(q, "Expiring temporary reference");
  6420. return res;
  6421. }
  6422. static int publish_queue_member_pause(struct call_queue *q, struct member *member, const char *reason)
  6423. {
  6424. struct ast_json *json_blob = queue_member_blob_create(q, member);
  6425. if (!json_blob) {
  6426. return -1;
  6427. }
  6428. if (!ast_strlen_zero(reason)) {
  6429. ast_json_object_set(json_blob, "Reason", ast_json_string_create(reason));
  6430. }
  6431. queue_publish_member_blob(queue_member_pause_type(), json_blob);
  6432. return 0;
  6433. }
  6434. static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused)
  6435. {
  6436. int found = 0;
  6437. struct call_queue *q;
  6438. struct ao2_iterator queue_iter;
  6439. queue_iter = ao2_iterator_init(queues, 0);
  6440. while ((q = ao2_t_iterator_next(&queue_iter, "Iterate over queues"))) {
  6441. ao2_lock(q);
  6442. if (ast_strlen_zero(queuename) || !strcasecmp(q->name, queuename)) {
  6443. struct member *mem;
  6444. if ((mem = interface_exists(q, interface))) {
  6445. if (mem->paused == paused) {
  6446. ast_debug(1, "%spausing already-%spaused queue member %s:%s\n", (paused ? "" : "un"), (paused ? "" : "un"), q->name, interface);
  6447. }
  6448. if (mem->realtime) {
  6449. if (update_realtime_member_field(mem, q->name, "paused", paused ? "1" : "0")) {
  6450. ast_log(LOG_WARNING, "Failed %spausing realtime queue member %s:%s\n", (paused ? "" : "un"), q->name, interface);
  6451. ao2_ref(mem, -1);
  6452. ao2_unlock(q);
  6453. queue_t_unref(q, "Done with iterator");
  6454. continue;
  6455. }
  6456. }
  6457. mem->paused = paused;
  6458. ast_devstate_changed(mem->paused ? QUEUE_PAUSED_DEVSTATE : QUEUE_UNPAUSED_DEVSTATE,
  6459. AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", q->name, mem->interface);
  6460. found++;
  6461. /* Before we do the PAUSE/UNPAUSE log, if this was a PAUSEALL/UNPAUSEALL, log that here, but only on the first found entry. */
  6462. if (found == 1) {
  6463. /* XXX In all other cases, we use the membername, but since this affects all queues, we cannot */
  6464. if (ast_strlen_zero(queuename)) {
  6465. ast_queue_log("NONE", "NONE", interface, (paused ? "PAUSEALL" : "UNPAUSEALL"), "%s", "");
  6466. }
  6467. }
  6468. if (queue_persistent_members) {
  6469. dump_queue_members(q);
  6470. }
  6471. if (is_member_available(q, mem)) {
  6472. ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
  6473. } else if (!num_available_members(q)) {
  6474. ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
  6475. }
  6476. ast_queue_log(q->name, "NONE", mem->membername, (paused ? "PAUSE" : "UNPAUSE"), "%s", S_OR(reason, ""));
  6477. publish_queue_member_pause(q, mem, reason);
  6478. ao2_ref(mem, -1);
  6479. }
  6480. }
  6481. if (!ast_strlen_zero(queuename) && !strcasecmp(queuename, q->name)) {
  6482. ao2_unlock(q);
  6483. queue_t_unref(q, "Done with iterator");
  6484. break;
  6485. }
  6486. ao2_unlock(q);
  6487. queue_t_unref(q, "Done with iterator");
  6488. }
  6489. ao2_iterator_destroy(&queue_iter);
  6490. return found ? RESULT_SUCCESS : RESULT_FAILURE;
  6491. }
  6492. /*!
  6493. * \internal
  6494. * \brief helper function for set_member_penalty - given a queue, sets all member penalties with the interface
  6495. * \param[in] q queue which is having its member's penalty changed - must be unlocked prior to calling
  6496. * \param[in] interface String of interface used to search for queue members being changed
  6497. * \param[in] penalty Value penalty is being changed to for the member.
  6498. * \retval 0 if the there is no member with interface belonging to q and no change is made
  6499. * \retval 1 if the there is a member with interface belonging to q and changes are made
  6500. */
  6501. static int set_member_penalty_help_members(struct call_queue *q, const char *interface, int penalty)
  6502. {
  6503. struct member *mem;
  6504. int foundinterface = 0;
  6505. ao2_lock(q);
  6506. if ((mem = interface_exists(q, interface))) {
  6507. foundinterface++;
  6508. if (mem->realtime) {
  6509. char rtpenalty[80];
  6510. sprintf(rtpenalty, "%i", penalty);
  6511. update_realtime_member_field(mem, q->name, "penalty", rtpenalty);
  6512. }
  6513. mem->penalty = penalty;
  6514. ast_queue_log(q->name, "NONE", interface, "PENALTY", "%d", penalty);
  6515. queue_publish_member_blob(queue_member_penalty_type(), queue_member_blob_create(q, mem));
  6516. ao2_ref(mem, -1);
  6517. }
  6518. ao2_unlock(q);
  6519. return foundinterface;
  6520. }
  6521. static int set_member_ringinuse_help_members(struct call_queue *q, const char *interface, int ringinuse)
  6522. {
  6523. struct member *mem;
  6524. int foundinterface = 0;
  6525. ao2_lock(q);
  6526. if ((mem = interface_exists(q, interface))) {
  6527. foundinterface++;
  6528. if (mem->realtime) {
  6529. char rtringinuse[80];
  6530. sprintf(rtringinuse, "%i", ringinuse);
  6531. update_realtime_member_field(mem, q->name, realtime_ringinuse_field, rtringinuse);
  6532. }
  6533. mem->ringinuse = ringinuse;
  6534. ast_queue_log(q->name, "NONE", interface, "RINGINUSE", "%d", ringinuse);
  6535. queue_publish_member_blob(queue_member_ringinuse_type(), queue_member_blob_create(q, mem));
  6536. ao2_ref(mem, -1);
  6537. }
  6538. ao2_unlock(q);
  6539. return foundinterface;
  6540. }
  6541. static int set_member_value_help_members(struct call_queue *q, const char *interface, int property, int value)
  6542. {
  6543. switch(property) {
  6544. case MEMBER_PENALTY:
  6545. return set_member_penalty_help_members(q, interface, value);
  6546. case MEMBER_RINGINUSE:
  6547. return set_member_ringinuse_help_members(q, interface, value);
  6548. default:
  6549. ast_log(LOG_ERROR, "Attempted to set invalid property\n");
  6550. return 0;
  6551. }
  6552. }
  6553. /*!
  6554. * \internal
  6555. * \brief Sets members penalty, if queuename=NULL we set member penalty in all the queues.
  6556. * \param[in] queuename If specified, only act on a member if it belongs to this queue
  6557. * \param[in] interface Interface of queue member(s) having priority set.
  6558. * \param[in] property Which queue property is being set
  6559. * \param[in] penalty Value penalty is being changed to for each member
  6560. */
  6561. static int set_member_value(const char *queuename, const char *interface, int property, int value)
  6562. {
  6563. int foundinterface = 0, foundqueue = 0;
  6564. struct call_queue *q;
  6565. struct ast_config *queue_config = NULL;
  6566. struct ao2_iterator queue_iter;
  6567. /* property dependent restrictions on values should be checked in this switch */
  6568. switch (property) {
  6569. case MEMBER_PENALTY:
  6570. if (value < 0 && !negative_penalty_invalid) {
  6571. ast_log(LOG_ERROR, "Invalid penalty (%d)\n", value);
  6572. return RESULT_FAILURE;
  6573. }
  6574. }
  6575. if (ast_strlen_zero(queuename)) { /* This means we need to iterate through all the queues. */
  6576. if (ast_check_realtime("queues")) {
  6577. char *name;
  6578. queue_config = ast_load_realtime_multientry("queues", "name LIKE", "%", SENTINEL);
  6579. if (queue_config) {
  6580. for (name = ast_category_browse(queue_config, NULL);
  6581. !ast_strlen_zero(name);
  6582. name = ast_category_browse(queue_config, name)) {
  6583. if ((q = find_load_queue_rt_friendly(name))) {
  6584. foundqueue++;
  6585. foundinterface += set_member_value_help_members(q, interface, property, value);
  6586. queue_unref(q);
  6587. }
  6588. }
  6589. }
  6590. }
  6591. /* After hitting realtime queues, go back and get the regular ones. */
  6592. queue_iter = ao2_iterator_init(queues, 0);
  6593. while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
  6594. foundqueue++;
  6595. foundinterface += set_member_value_help_members(q, interface, property, value);
  6596. queue_unref(q);
  6597. }
  6598. ao2_iterator_destroy(&queue_iter);
  6599. } else { /* We actually have a queuename, so we can just act on the single queue. */
  6600. if ((q = find_load_queue_rt_friendly(queuename))) {
  6601. foundqueue++;
  6602. foundinterface += set_member_value_help_members(q, interface, property, value);
  6603. queue_unref(q);
  6604. }
  6605. }
  6606. if (foundinterface) {
  6607. return RESULT_SUCCESS;
  6608. } else if (!foundqueue) {
  6609. ast_log (LOG_ERROR, "Invalid queuename\n");
  6610. } else {
  6611. ast_log (LOG_ERROR, "Invalid interface\n");
  6612. }
  6613. return RESULT_FAILURE;
  6614. }
  6615. /* \brief Gets members penalty.
  6616. * \return Return the members penalty or RESULT_FAILURE on error.
  6617. */
  6618. static int get_member_penalty(char *queuename, char *interface)
  6619. {
  6620. int foundqueue = 0, penalty;
  6621. struct call_queue *q, tmpq = {
  6622. .name = queuename,
  6623. };
  6624. struct member *mem;
  6625. if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Search for queue"))) {
  6626. foundqueue = 1;
  6627. ao2_lock(q);
  6628. if ((mem = interface_exists(q, interface))) {
  6629. penalty = mem->penalty;
  6630. ao2_ref(mem, -1);
  6631. ao2_unlock(q);
  6632. queue_t_unref(q, "Search complete");
  6633. return penalty;
  6634. }
  6635. ao2_unlock(q);
  6636. queue_t_unref(q, "Search complete");
  6637. }
  6638. /* some useful debuging */
  6639. if (foundqueue) {
  6640. ast_log (LOG_ERROR, "Invalid queuename\n");
  6641. } else {
  6642. ast_log (LOG_ERROR, "Invalid interface\n");
  6643. }
  6644. return RESULT_FAILURE;
  6645. }
  6646. /*! \brief Reload dynamic queue members persisted into the astdb */
  6647. static void reload_queue_members(void)
  6648. {
  6649. char *cur_ptr;
  6650. const char *queue_name;
  6651. char *member;
  6652. char *interface;
  6653. char *membername = NULL;
  6654. char *state_interface;
  6655. char *penalty_tok;
  6656. int penalty = 0;
  6657. char *paused_tok;
  6658. int paused = 0;
  6659. struct ast_db_entry *db_tree;
  6660. struct ast_db_entry *entry;
  6661. struct call_queue *cur_queue;
  6662. char *queue_data;
  6663. /* Each key in 'pm_family' is the name of a queue */
  6664. db_tree = ast_db_gettree(pm_family, NULL);
  6665. for (entry = db_tree; entry; entry = entry->next) {
  6666. queue_name = entry->key + strlen(pm_family) + 2;
  6667. {
  6668. struct call_queue tmpq = {
  6669. .name = queue_name,
  6670. };
  6671. cur_queue = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Reload queue members");
  6672. }
  6673. if (!cur_queue) {
  6674. cur_queue = find_load_queue_rt_friendly(queue_name);
  6675. }
  6676. if (!cur_queue) {
  6677. /* If the queue no longer exists, remove it from the
  6678. * database */
  6679. ast_log(LOG_WARNING, "Error loading persistent queue: '%s': it does not exist\n", queue_name);
  6680. ast_db_del(pm_family, queue_name);
  6681. continue;
  6682. }
  6683. if (ast_db_get_allocated(pm_family, queue_name, &queue_data)) {
  6684. queue_t_unref(cur_queue, "Expire reload reference");
  6685. continue;
  6686. }
  6687. cur_ptr = queue_data;
  6688. while ((member = strsep(&cur_ptr, ",|"))) {
  6689. if (ast_strlen_zero(member)) {
  6690. continue;
  6691. }
  6692. interface = strsep(&member, ";");
  6693. penalty_tok = strsep(&member, ";");
  6694. paused_tok = strsep(&member, ";");
  6695. membername = strsep(&member, ";");
  6696. state_interface = strsep(&member, ";");
  6697. if (!penalty_tok) {
  6698. ast_log(LOG_WARNING, "Error parsing persistent member string for '%s' (penalty)\n", queue_name);
  6699. break;
  6700. }
  6701. penalty = strtol(penalty_tok, NULL, 10);
  6702. if (errno == ERANGE) {
  6703. ast_log(LOG_WARNING, "Error converting penalty: %s: Out of range.\n", penalty_tok);
  6704. break;
  6705. }
  6706. if (!paused_tok) {
  6707. ast_log(LOG_WARNING, "Error parsing persistent member string for '%s' (paused)\n", queue_name);
  6708. break;
  6709. }
  6710. paused = strtol(paused_tok, NULL, 10);
  6711. if ((errno == ERANGE) || paused < 0 || paused > 1) {
  6712. ast_log(LOG_WARNING, "Error converting paused: %s: Expected 0 or 1.\n", paused_tok);
  6713. break;
  6714. }
  6715. ast_debug(1, "Reload Members: Queue: %s Member: %s Name: %s Penalty: %d Paused: %d\n", queue_name, interface, membername, penalty, paused);
  6716. if (add_to_queue(queue_name, interface, membername, penalty, paused, 0, state_interface) == RES_OUTOFMEMORY) {
  6717. ast_log(LOG_ERROR, "Out of Memory when reloading persistent queue member\n");
  6718. break;
  6719. }
  6720. }
  6721. queue_t_unref(cur_queue, "Expire reload reference");
  6722. ast_free(queue_data);
  6723. }
  6724. if (db_tree) {
  6725. ast_log(LOG_NOTICE, "Queue members successfully reloaded from database.\n");
  6726. ast_db_freetree(db_tree);
  6727. }
  6728. }
  6729. /*! \brief PauseQueueMember application */
  6730. static int pqm_exec(struct ast_channel *chan, const char *data)
  6731. {
  6732. char *parse;
  6733. AST_DECLARE_APP_ARGS(args,
  6734. AST_APP_ARG(queuename);
  6735. AST_APP_ARG(interface);
  6736. AST_APP_ARG(options);
  6737. AST_APP_ARG(reason);
  6738. );
  6739. if (ast_strlen_zero(data)) {
  6740. ast_log(LOG_WARNING, "PauseQueueMember requires an argument ([queuename],interface[,options][,reason])\n");
  6741. return -1;
  6742. }
  6743. parse = ast_strdupa(data);
  6744. AST_STANDARD_APP_ARGS(args, parse);
  6745. if (ast_strlen_zero(args.interface)) {
  6746. ast_log(LOG_WARNING, "Missing interface argument to PauseQueueMember ([queuename],interface[,options[,reason]])\n");
  6747. return -1;
  6748. }
  6749. if (set_member_paused(args.queuename, args.interface, args.reason, 1)) {
  6750. ast_log(LOG_WARNING, "Attempt to pause interface %s, not found\n", args.interface);
  6751. pbx_builtin_setvar_helper(chan, "PQMSTATUS", "NOTFOUND");
  6752. return 0;
  6753. }
  6754. pbx_builtin_setvar_helper(chan, "PQMSTATUS", "PAUSED");
  6755. return 0;
  6756. }
  6757. /*! \brief UnPauseQueueMember application */
  6758. static int upqm_exec(struct ast_channel *chan, const char *data)
  6759. {
  6760. char *parse;
  6761. AST_DECLARE_APP_ARGS(args,
  6762. AST_APP_ARG(queuename);
  6763. AST_APP_ARG(interface);
  6764. AST_APP_ARG(options);
  6765. AST_APP_ARG(reason);
  6766. );
  6767. if (ast_strlen_zero(data)) {
  6768. ast_log(LOG_WARNING, "UnpauseQueueMember requires an argument ([queuename],interface[,options[,reason]])\n");
  6769. return -1;
  6770. }
  6771. parse = ast_strdupa(data);
  6772. AST_STANDARD_APP_ARGS(args, parse);
  6773. if (ast_strlen_zero(args.interface)) {
  6774. ast_log(LOG_WARNING, "Missing interface argument to PauseQueueMember ([queuename],interface[,options[,reason]])\n");
  6775. return -1;
  6776. }
  6777. if (set_member_paused(args.queuename, args.interface, args.reason, 0)) {
  6778. ast_log(LOG_WARNING, "Attempt to unpause interface %s, not found\n", args.interface);
  6779. pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "NOTFOUND");
  6780. return 0;
  6781. }
  6782. pbx_builtin_setvar_helper(chan, "UPQMSTATUS", "UNPAUSED");
  6783. return 0;
  6784. }
  6785. /*! \brief RemoveQueueMember application */
  6786. static int rqm_exec(struct ast_channel *chan, const char *data)
  6787. {
  6788. int res=-1;
  6789. char *parse, *temppos = NULL;
  6790. struct member *mem = NULL;
  6791. AST_DECLARE_APP_ARGS(args,
  6792. AST_APP_ARG(queuename);
  6793. AST_APP_ARG(interface);
  6794. );
  6795. if (ast_strlen_zero(data)) {
  6796. ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename[,interface])\n");
  6797. return -1;
  6798. }
  6799. parse = ast_strdupa(data);
  6800. AST_STANDARD_APP_ARGS(args, parse);
  6801. if (ast_strlen_zero(args.interface)) {
  6802. args.interface = ast_strdupa(ast_channel_name(chan));
  6803. temppos = strrchr(args.interface, '-');
  6804. if (temppos) {
  6805. *temppos = '\0';
  6806. }
  6807. }
  6808. ast_debug(1, "queue: %s, member: %s\n", args.queuename, args.interface);
  6809. if (log_membername_as_agent) {
  6810. mem = find_member_by_queuename_and_interface(args.queuename, args.interface);
  6811. }
  6812. switch (remove_from_queue(args.queuename, args.interface)) {
  6813. case RES_OKAY:
  6814. if (!mem || ast_strlen_zero(mem->membername)) {
  6815. ast_queue_log(args.queuename, ast_channel_uniqueid(chan), args.interface, "REMOVEMEMBER", "%s", "");
  6816. } else {
  6817. ast_queue_log(args.queuename, ast_channel_uniqueid(chan), mem->membername, "REMOVEMEMBER", "%s", "");
  6818. }
  6819. ast_log(LOG_NOTICE, "Removed interface '%s' from queue '%s'\n", args.interface, args.queuename);
  6820. pbx_builtin_setvar_helper(chan, "RQMSTATUS", "REMOVED");
  6821. res = 0;
  6822. break;
  6823. case RES_EXISTS:
  6824. ast_debug(1, "Unable to remove interface '%s' from queue '%s': Not there\n", args.interface, args.queuename);
  6825. pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOTINQUEUE");
  6826. res = 0;
  6827. break;
  6828. case RES_NOSUCHQUEUE:
  6829. ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", args.queuename);
  6830. pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOSUCHQUEUE");
  6831. res = 0;
  6832. break;
  6833. case RES_NOT_DYNAMIC:
  6834. ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': '%s' is not a dynamic member\n", args.queuename, args.interface);
  6835. pbx_builtin_setvar_helper(chan, "RQMSTATUS", "NOTDYNAMIC");
  6836. res = 0;
  6837. break;
  6838. }
  6839. if (mem) {
  6840. ao2_ref(mem, -1);
  6841. }
  6842. return res;
  6843. }
  6844. /*! \brief AddQueueMember application */
  6845. static int aqm_exec(struct ast_channel *chan, const char *data)
  6846. {
  6847. int res=-1;
  6848. char *parse, *temppos = NULL;
  6849. AST_DECLARE_APP_ARGS(args,
  6850. AST_APP_ARG(queuename);
  6851. AST_APP_ARG(interface);
  6852. AST_APP_ARG(penalty);
  6853. AST_APP_ARG(options);
  6854. AST_APP_ARG(membername);
  6855. AST_APP_ARG(state_interface);
  6856. );
  6857. int penalty = 0;
  6858. if (ast_strlen_zero(data)) {
  6859. ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename[,interface[,penalty[,options[,membername[,stateinterface]]]]])\n");
  6860. return -1;
  6861. }
  6862. parse = ast_strdupa(data);
  6863. AST_STANDARD_APP_ARGS(args, parse);
  6864. if (ast_strlen_zero(args.interface)) {
  6865. args.interface = ast_strdupa(ast_channel_name(chan));
  6866. temppos = strrchr(args.interface, '-');
  6867. if (temppos) {
  6868. *temppos = '\0';
  6869. }
  6870. }
  6871. if (!ast_strlen_zero(args.penalty)) {
  6872. if ((sscanf(args.penalty, "%30d", &penalty) != 1) || penalty < 0) {
  6873. ast_log(LOG_WARNING, "Penalty '%s' is invalid, must be an integer >= 0\n", args.penalty);
  6874. penalty = 0;
  6875. }
  6876. }
  6877. switch (add_to_queue(args.queuename, args.interface, args.membername, penalty, 0, queue_persistent_members, args.state_interface)) {
  6878. case RES_OKAY:
  6879. if (ast_strlen_zero(args.membername) || !log_membername_as_agent) {
  6880. ast_queue_log(args.queuename, ast_channel_uniqueid(chan), args.interface, "ADDMEMBER", "%s", "");
  6881. } else {
  6882. ast_queue_log(args.queuename, ast_channel_uniqueid(chan), args.membername, "ADDMEMBER", "%s", "");
  6883. }
  6884. ast_log(LOG_NOTICE, "Added interface '%s' to queue '%s'\n", args.interface, args.queuename);
  6885. pbx_builtin_setvar_helper(chan, "AQMSTATUS", "ADDED");
  6886. res = 0;
  6887. break;
  6888. case RES_EXISTS:
  6889. ast_log(LOG_WARNING, "Unable to add interface '%s' to queue '%s': Already there\n", args.interface, args.queuename);
  6890. pbx_builtin_setvar_helper(chan, "AQMSTATUS", "MEMBERALREADY");
  6891. res = 0;
  6892. break;
  6893. case RES_NOSUCHQUEUE:
  6894. ast_log(LOG_WARNING, "Unable to add interface to queue '%s': No such queue\n", args.queuename);
  6895. pbx_builtin_setvar_helper(chan, "AQMSTATUS", "NOSUCHQUEUE");
  6896. res = 0;
  6897. break;
  6898. case RES_OUTOFMEMORY:
  6899. ast_log(LOG_ERROR, "Out of memory adding interface %s to queue %s\n", args.interface, args.queuename);
  6900. break;
  6901. }
  6902. return res;
  6903. }
  6904. /*! \brief QueueLog application */
  6905. static int ql_exec(struct ast_channel *chan, const char *data)
  6906. {
  6907. char *parse;
  6908. AST_DECLARE_APP_ARGS(args,
  6909. AST_APP_ARG(queuename);
  6910. AST_APP_ARG(uniqueid);
  6911. AST_APP_ARG(membername);
  6912. AST_APP_ARG(event);
  6913. AST_APP_ARG(params);
  6914. );
  6915. if (ast_strlen_zero(data)) {
  6916. ast_log(LOG_WARNING, "QueueLog requires arguments (queuename,uniqueid,membername,event[,additionalinfo]\n");
  6917. return -1;
  6918. }
  6919. parse = ast_strdupa(data);
  6920. AST_STANDARD_APP_ARGS(args, parse);
  6921. if (ast_strlen_zero(args.queuename) || ast_strlen_zero(args.uniqueid)
  6922. || ast_strlen_zero(args.membername) || ast_strlen_zero(args.event)) {
  6923. ast_log(LOG_WARNING, "QueueLog requires arguments (queuename,uniqueid,membername,event[,additionalinfo])\n");
  6924. return -1;
  6925. }
  6926. ast_queue_log(args.queuename, args.uniqueid, args.membername, args.event,
  6927. "%s", args.params ? args.params : "");
  6928. return 0;
  6929. }
  6930. /*! \brief Copy rule from global list into specified queue */
  6931. static void copy_rules(struct queue_ent *qe, const char *rulename)
  6932. {
  6933. struct penalty_rule *pr_iter;
  6934. struct rule_list *rl_iter;
  6935. const char *tmp = ast_strlen_zero(rulename) ? qe->parent->defaultrule : rulename;
  6936. AST_LIST_LOCK(&rule_lists);
  6937. AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
  6938. if (!strcasecmp(rl_iter->name, tmp)) {
  6939. break;
  6940. }
  6941. }
  6942. if (rl_iter) {
  6943. AST_LIST_TRAVERSE(&rl_iter->rules, pr_iter, list) {
  6944. struct penalty_rule *new_pr = ast_calloc(1, sizeof(*new_pr));
  6945. if (!new_pr) {
  6946. ast_log(LOG_ERROR, "Memory allocation error when copying penalty rules! Aborting!\n");
  6947. break;
  6948. }
  6949. new_pr->time = pr_iter->time;
  6950. new_pr->max_value = pr_iter->max_value;
  6951. new_pr->min_value = pr_iter->min_value;
  6952. new_pr->max_relative = pr_iter->max_relative;
  6953. new_pr->min_relative = pr_iter->min_relative;
  6954. AST_LIST_INSERT_TAIL(&qe->qe_rules, new_pr, list);
  6955. }
  6956. }
  6957. AST_LIST_UNLOCK(&rule_lists);
  6958. }
  6959. /*!\brief The starting point for all queue calls
  6960. *
  6961. * The process involved here is to
  6962. * 1. Parse the options specified in the call to Queue()
  6963. * 2. Join the queue
  6964. * 3. Wait in a loop until it is our turn to try calling a queue member
  6965. * 4. Attempt to call a queue member
  6966. * 5. If 4. did not result in a bridged call, then check for between
  6967. * call options such as periodic announcements etc.
  6968. * 6. Try 4 again unless some condition (such as an expiration time) causes us to
  6969. * exit the queue.
  6970. */
  6971. static int queue_exec(struct ast_channel *chan, const char *data)
  6972. {
  6973. int res=-1;
  6974. int ringing=0;
  6975. const char *user_priority;
  6976. const char *max_penalty_str;
  6977. const char *min_penalty_str;
  6978. int prio;
  6979. int qcontinue = 0;
  6980. int max_penalty, min_penalty;
  6981. enum queue_result reason = QUEUE_UNKNOWN;
  6982. /* whether to exit Queue application after the timeout hits */
  6983. int tries = 0;
  6984. int noption = 0;
  6985. char *parse;
  6986. int makeannouncement = 0;
  6987. int position = 0;
  6988. AST_DECLARE_APP_ARGS(args,
  6989. AST_APP_ARG(queuename);
  6990. AST_APP_ARG(options);
  6991. AST_APP_ARG(url);
  6992. AST_APP_ARG(announceoverride);
  6993. AST_APP_ARG(queuetimeoutstr);
  6994. AST_APP_ARG(agi);
  6995. AST_APP_ARG(macro);
  6996. AST_APP_ARG(gosub);
  6997. AST_APP_ARG(rule);
  6998. AST_APP_ARG(position);
  6999. );
  7000. /* Our queue entry */
  7001. struct queue_ent qe = { 0 };
  7002. struct ast_flags opts = { 0, };
  7003. char *opt_args[OPT_ARG_ARRAY_SIZE];
  7004. if (ast_strlen_zero(data)) {
  7005. ast_log(LOG_WARNING, "Queue requires an argument: queuename[,options[,URL[,announceoverride[,timeout[,agi[,macro[,gosub[,rule[,position]]]]]]]]]\n");
  7006. return -1;
  7007. }
  7008. parse = ast_strdupa(data);
  7009. AST_STANDARD_APP_ARGS(args, parse);
  7010. ast_debug(1, "queue: %s, options: %s, url: %s, announce: %s, timeout: %s, agi: %s, macro: %s, gosub: %s, rule: %s, position: %s\n",
  7011. args.queuename,
  7012. S_OR(args.options, ""),
  7013. S_OR(args.url, ""),
  7014. S_OR(args.announceoverride, ""),
  7015. S_OR(args.queuetimeoutstr, ""),
  7016. S_OR(args.agi, ""),
  7017. S_OR(args.macro, ""),
  7018. S_OR(args.gosub, ""),
  7019. S_OR(args.rule, ""),
  7020. S_OR(args.position, ""));
  7021. if (!ast_strlen_zero(args.options)) {
  7022. ast_app_parse_options(queue_exec_options, &opts, opt_args, args.options);
  7023. }
  7024. /* Setup our queue entry */
  7025. qe.start = time(NULL);
  7026. /* set the expire time based on the supplied timeout; */
  7027. if (!ast_strlen_zero(args.queuetimeoutstr)) {
  7028. qe.expire = qe.start + atoi(args.queuetimeoutstr);
  7029. } else {
  7030. qe.expire = 0;
  7031. }
  7032. /* Get the priority from the variable ${QUEUE_PRIO} */
  7033. ast_channel_lock(chan);
  7034. user_priority = pbx_builtin_getvar_helper(chan, "QUEUE_PRIO");
  7035. if (user_priority) {
  7036. if (sscanf(user_priority, "%30d", &prio) == 1) {
  7037. ast_debug(1, "%s: Got priority %d from ${QUEUE_PRIO}.\n", ast_channel_name(chan), prio);
  7038. } else {
  7039. ast_log(LOG_WARNING, "${QUEUE_PRIO}: Invalid value (%s), channel %s.\n",
  7040. user_priority, ast_channel_name(chan));
  7041. prio = 0;
  7042. }
  7043. } else {
  7044. ast_debug(3, "NO QUEUE_PRIO variable found. Using default.\n");
  7045. prio = 0;
  7046. }
  7047. /* Get the maximum penalty from the variable ${QUEUE_MAX_PENALTY} */
  7048. if ((max_penalty_str = pbx_builtin_getvar_helper(chan, "QUEUE_MAX_PENALTY"))) {
  7049. if (sscanf(max_penalty_str, "%30d", &max_penalty) == 1) {
  7050. ast_debug(1, "%s: Got max penalty %d from ${QUEUE_MAX_PENALTY}.\n", ast_channel_name(chan), max_penalty);
  7051. } else {
  7052. ast_log(LOG_WARNING, "${QUEUE_MAX_PENALTY}: Invalid value (%s), channel %s.\n",
  7053. max_penalty_str, ast_channel_name(chan));
  7054. max_penalty = INT_MAX;
  7055. }
  7056. } else {
  7057. max_penalty = INT_MAX;
  7058. }
  7059. if ((min_penalty_str = pbx_builtin_getvar_helper(chan, "QUEUE_MIN_PENALTY"))) {
  7060. if (sscanf(min_penalty_str, "%30d", &min_penalty) == 1) {
  7061. ast_debug(1, "%s: Got min penalty %d from ${QUEUE_MIN_PENALTY}.\n", ast_channel_name(chan), min_penalty);
  7062. } else {
  7063. ast_log(LOG_WARNING, "${QUEUE_MIN_PENALTY}: Invalid value (%s), channel %s.\n",
  7064. min_penalty_str, ast_channel_name(chan));
  7065. min_penalty = INT_MAX;
  7066. }
  7067. } else {
  7068. min_penalty = INT_MAX;
  7069. }
  7070. ast_channel_unlock(chan);
  7071. if (ast_test_flag(&opts, OPT_RINGING)) {
  7072. ringing = 1;
  7073. }
  7074. if (ringing != 1 && ast_test_flag(&opts, OPT_RING_WHEN_RINGING)) {
  7075. qe.ring_when_ringing = 1;
  7076. }
  7077. if (ast_test_flag(&opts, OPT_GO_ON)) {
  7078. qcontinue = 1;
  7079. }
  7080. if (args.position) {
  7081. position = atoi(args.position);
  7082. if (position < 0) {
  7083. ast_log(LOG_WARNING, "Invalid position '%s' given for call to queue '%s'. Assuming no preference for position\n", args.position, args.queuename);
  7084. position = 0;
  7085. }
  7086. }
  7087. ast_debug(1, "queue: %s, expires: %ld, priority: %d\n",
  7088. args.queuename, (long)qe.expire, prio);
  7089. qe.chan = chan;
  7090. qe.prio = prio;
  7091. qe.max_penalty = max_penalty;
  7092. qe.min_penalty = min_penalty;
  7093. qe.last_pos_said = 0;
  7094. qe.last_pos = 0;
  7095. qe.last_periodic_announce_time = time(NULL);
  7096. qe.last_periodic_announce_sound = 0;
  7097. qe.valid_digits = 0;
  7098. if (join_queue(args.queuename, &qe, &reason, position)) {
  7099. ast_log(LOG_WARNING, "Unable to join queue '%s'\n", args.queuename);
  7100. set_queue_result(chan, reason);
  7101. return 0;
  7102. }
  7103. ast_assert(qe.parent != NULL);
  7104. ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "ENTERQUEUE", "%s|%s|%d",
  7105. S_OR(args.url, ""),
  7106. S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, ""),
  7107. qe.opos);
  7108. copy_rules(&qe, args.rule);
  7109. qe.pr = AST_LIST_FIRST(&qe.qe_rules);
  7110. check_turns:
  7111. if (ringing) {
  7112. ast_indicate(chan, AST_CONTROL_RINGING);
  7113. } else {
  7114. ast_moh_start(chan, qe.moh, NULL);
  7115. }
  7116. /* This is the wait loop for callers 2 through maxlen */
  7117. res = wait_our_turn(&qe, ringing, &reason);
  7118. if (res) {
  7119. goto stop;
  7120. }
  7121. makeannouncement = 0;
  7122. for (;;) {
  7123. /* This is the wait loop for the head caller*/
  7124. /* To exit, they may get their call answered; */
  7125. /* they may dial a digit from the queue context; */
  7126. /* or, they may timeout. */
  7127. /* Leave if we have exceeded our queuetimeout */
  7128. if (qe.expire && (time(NULL) >= qe.expire)) {
  7129. record_abandoned(&qe);
  7130. reason = QUEUE_TIMEOUT;
  7131. res = 0;
  7132. ast_queue_log(args.queuename, ast_channel_uniqueid(chan),"NONE", "EXITWITHTIMEOUT", "%d|%d|%ld",
  7133. qe.pos, qe.opos, (long) (time(NULL) - qe.start));
  7134. break;
  7135. }
  7136. if (makeannouncement) {
  7137. /* Make a position announcement, if enabled */
  7138. if (qe.parent->announcefrequency)
  7139. if ((res = say_position(&qe,ringing)))
  7140. goto stop;
  7141. }
  7142. makeannouncement = 1;
  7143. /* Make a periodic announcement, if enabled */
  7144. if (qe.parent->periodicannouncefrequency) {
  7145. if ((res = say_periodic_announcement(&qe,ringing))) {
  7146. goto stop;
  7147. }
  7148. }
  7149. /* Leave if we have exceeded our queuetimeout */
  7150. if (qe.expire && (time(NULL) >= qe.expire)) {
  7151. record_abandoned(&qe);
  7152. reason = QUEUE_TIMEOUT;
  7153. res = 0;
  7154. ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
  7155. break;
  7156. }
  7157. /* see if we need to move to the next penalty level for this queue */
  7158. while (qe.pr && ((time(NULL) - qe.start) > qe.pr->time)) {
  7159. update_qe_rule(&qe);
  7160. }
  7161. /* Try calling all queue members for 'timeout' seconds */
  7162. res = try_calling(&qe, opts, opt_args, args.announceoverride, args.url, &tries, &noption, args.agi, args.macro, args.gosub, ringing);
  7163. if (res) {
  7164. goto stop;
  7165. }
  7166. if (qe.parent->leavewhenempty) {
  7167. int status = 0;
  7168. if ((status = get_member_status(qe.parent, qe.max_penalty, qe.min_penalty, qe.parent->leavewhenempty, 0))) {
  7169. record_abandoned(&qe);
  7170. reason = QUEUE_LEAVEEMPTY;
  7171. ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "EXITEMPTY", "%d|%d|%ld", qe.pos, qe.opos, (long)(time(NULL) - qe.start));
  7172. res = 0;
  7173. break;
  7174. }
  7175. }
  7176. /* exit after 'timeout' cycle if 'n' option enabled */
  7177. if (noption && tries >= ao2_container_count(qe.parent->members)) {
  7178. ast_verb(3, "Exiting on time-out cycle\n");
  7179. ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
  7180. record_abandoned(&qe);
  7181. reason = QUEUE_TIMEOUT;
  7182. res = 0;
  7183. break;
  7184. }
  7185. /* Leave if we have exceeded our queuetimeout */
  7186. if (qe.expire && (time(NULL) >= qe.expire)) {
  7187. record_abandoned(&qe);
  7188. reason = QUEUE_TIMEOUT;
  7189. res = 0;
  7190. ast_queue_log(qe.parent->name, ast_channel_uniqueid(qe.chan),"NONE", "EXITWITHTIMEOUT", "%d|%d|%ld", qe.pos, qe.opos, (long) (time(NULL) - qe.start));
  7191. break;
  7192. }
  7193. /* If using dynamic realtime members, we should regenerate the member list for this queue */
  7194. update_realtime_members(qe.parent);
  7195. /* OK, we didn't get anybody; wait for 'retry' seconds; may get a digit to exit with */
  7196. res = wait_a_bit(&qe);
  7197. if (res) {
  7198. goto stop;
  7199. }
  7200. /* Since this is a priority queue and
  7201. * it is not sure that we are still at the head
  7202. * of the queue, go and check for our turn again.
  7203. */
  7204. if (!is_our_turn(&qe)) {
  7205. ast_debug(1, "Darn priorities, going back in queue (%s)!\n", ast_channel_name(qe.chan));
  7206. goto check_turns;
  7207. }
  7208. }
  7209. stop:
  7210. if (res) {
  7211. if (res < 0) {
  7212. if (!qe.handled) {
  7213. record_abandoned(&qe);
  7214. ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "ABANDON",
  7215. "%d|%d|%ld", qe.pos, qe.opos,
  7216. (long) (time(NULL) - qe.start));
  7217. res = -1;
  7218. } else if (qcontinue) {
  7219. reason = QUEUE_CONTINUE;
  7220. res = 0;
  7221. }
  7222. } else if (qe.valid_digits) {
  7223. ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "EXITWITHKEY",
  7224. "%s|%d|%d|%ld", qe.digits, qe.pos, qe.opos, (long) (time(NULL) - qe.start));
  7225. }
  7226. }
  7227. /* Don't allow return code > 0 */
  7228. if (res >= 0) {
  7229. res = 0;
  7230. if (ringing) {
  7231. ast_indicate(chan, -1);
  7232. } else {
  7233. ast_moh_stop(chan);
  7234. }
  7235. ast_stopstream(chan);
  7236. }
  7237. set_queue_variables(qe.parent, qe.chan);
  7238. leave_queue(&qe);
  7239. if (reason != QUEUE_UNKNOWN)
  7240. set_queue_result(chan, reason);
  7241. /*
  7242. * every queue_ent is given a reference to it's parent
  7243. * call_queue when it joins the queue. This ref must be taken
  7244. * away right before the queue_ent is destroyed. In this case
  7245. * the queue_ent is about to be returned on the stack
  7246. */
  7247. qe.parent = queue_unref(qe.parent);
  7248. return res;
  7249. }
  7250. /*!
  7251. * \brief create interface var with all queue details.
  7252. * \retval 0 on success
  7253. * \retval -1 on error
  7254. */
  7255. static int queue_function_var(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  7256. {
  7257. int res = -1;
  7258. struct call_queue *q, tmpq = {
  7259. .name = data,
  7260. };
  7261. char interfacevar[256] = "";
  7262. float sl = 0;
  7263. if (ast_strlen_zero(data)) {
  7264. ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
  7265. return -1;
  7266. }
  7267. if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find for QUEUE() function"))) {
  7268. ao2_lock(q);
  7269. if (q->setqueuevar) {
  7270. sl = 0;
  7271. res = 0;
  7272. if (q->callscompleted > 0) {
  7273. sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
  7274. }
  7275. snprintf(interfacevar, sizeof(interfacevar),
  7276. "QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
  7277. q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned, q->servicelevel, sl);
  7278. pbx_builtin_setvar_multiple(chan, interfacevar);
  7279. }
  7280. ao2_unlock(q);
  7281. queue_t_unref(q, "Done with QUEUE() function");
  7282. } else {
  7283. ast_log(LOG_WARNING, "queue %s was not found\n", data);
  7284. }
  7285. snprintf(buf, len, "%d", res);
  7286. return 0;
  7287. }
  7288. /*!
  7289. * \brief Check if a given queue exists
  7290. *
  7291. */
  7292. static int queue_function_exists(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  7293. {
  7294. struct call_queue *q;
  7295. buf[0] = '\0';
  7296. if (ast_strlen_zero(data)) {
  7297. ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
  7298. return -1;
  7299. }
  7300. q = find_load_queue_rt_friendly(data);
  7301. snprintf(buf, len, "%d", q != NULL? 1 : 0);
  7302. if (q) {
  7303. queue_t_unref(q, "Done with temporary reference in QUEUE_EXISTS()");
  7304. }
  7305. return 0;
  7306. }
  7307. /*!
  7308. * \brief Get number either busy / free / ready or total members of a specific queue
  7309. * \brief Get or set member properties penalty / paused / ringinuse
  7310. * \retval number of members (busy / free / ready / total) or member info (penalty / paused / ringinuse)
  7311. * \retval -1 on error
  7312. */
  7313. static int queue_function_mem_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  7314. {
  7315. int count = 0;
  7316. struct member *m;
  7317. struct ao2_iterator mem_iter;
  7318. struct call_queue *q;
  7319. AST_DECLARE_APP_ARGS(args,
  7320. AST_APP_ARG(queuename);
  7321. AST_APP_ARG(option);
  7322. AST_APP_ARG(interface);
  7323. );
  7324. /* Make sure the returned value on error is zero length string. */
  7325. buf[0] = '\0';
  7326. if (ast_strlen_zero(data)) {
  7327. ast_log(LOG_ERROR, "Missing required argument. %s(<queuename>,<option>[<interface>])\n", cmd);
  7328. return -1;
  7329. }
  7330. AST_STANDARD_APP_ARGS(args, data);
  7331. if (args.argc < 2) {
  7332. ast_log(LOG_ERROR, "Missing required argument. %s(<queuename>,<option>[<interface>])\n", cmd);
  7333. return -1;
  7334. }
  7335. if ((q = find_load_queue_rt_friendly(args.queuename))) {
  7336. ao2_lock(q);
  7337. if (!strcasecmp(args.option, "logged")) {
  7338. mem_iter = ao2_iterator_init(q->members, 0);
  7339. while ((m = ao2_iterator_next(&mem_iter))) {
  7340. /* Count the agents who are logged in and presently answering calls */
  7341. if ((m->status != AST_DEVICE_UNAVAILABLE) && (m->status != AST_DEVICE_INVALID)) {
  7342. count++;
  7343. }
  7344. ao2_ref(m, -1);
  7345. }
  7346. ao2_iterator_destroy(&mem_iter);
  7347. } else if (!strcasecmp(args.option, "free")) {
  7348. mem_iter = ao2_iterator_init(q->members, 0);
  7349. while ((m = ao2_iterator_next(&mem_iter))) {
  7350. /* Count the agents who are logged in and presently answering calls */
  7351. if ((m->status == AST_DEVICE_NOT_INUSE) && (!m->paused)) {
  7352. count++;
  7353. }
  7354. ao2_ref(m, -1);
  7355. }
  7356. ao2_iterator_destroy(&mem_iter);
  7357. } else if (!strcasecmp(args.option, "ready")) {
  7358. time_t now;
  7359. time(&now);
  7360. mem_iter = ao2_iterator_init(q->members, 0);
  7361. while ((m = ao2_iterator_next(&mem_iter))) {
  7362. /* Count the agents who are logged in, not paused and not wrapping up */
  7363. if ((m->status == AST_DEVICE_NOT_INUSE) && (!m->paused) &&
  7364. !(m->lastcall && q->wrapuptime && ((now - q->wrapuptime) < m->lastcall))) {
  7365. count++;
  7366. }
  7367. ao2_ref(m, -1);
  7368. }
  7369. ao2_iterator_destroy(&mem_iter);
  7370. } else if (!strcasecmp(args.option, "count") || ast_strlen_zero(args.option)) {
  7371. count = ao2_container_count(q->members);
  7372. } else if (!strcasecmp(args.option, "penalty") && !ast_strlen_zero(args.interface) &&
  7373. ((m = interface_exists(q, args.interface)))) {
  7374. count = m->penalty;
  7375. ao2_ref(m, -1);
  7376. } else if (!strcasecmp(args.option, "paused") && !ast_strlen_zero(args.interface) &&
  7377. ((m = interface_exists(q, args.interface)))) {
  7378. count = m->paused;
  7379. ao2_ref(m, -1);
  7380. } else if ( (!strcasecmp(args.option, "ignorebusy") || !strcasecmp(args.option, "ringinuse")) &&
  7381. !ast_strlen_zero(args.interface) &&
  7382. ((m = interface_exists(q, args.interface)))) {
  7383. count = m->ringinuse;
  7384. ao2_ref(m, -1);
  7385. } else if (!ast_strlen_zero(args.interface)) {
  7386. ast_log(LOG_ERROR, "Queue member interface %s not in queue %s\n",
  7387. args.interface, args.queuename);
  7388. } else {
  7389. ast_log(LOG_ERROR, "Unknown option %s provided to %s, valid values are: "
  7390. "logged, free, ready, count, penalty, paused, ringinuse\n", args.option, cmd);
  7391. }
  7392. ao2_unlock(q);
  7393. queue_t_unref(q, "Done with temporary reference in QUEUE_MEMBER()");
  7394. } else {
  7395. ast_log(LOG_WARNING, "queue %s was not found\n", args.queuename);
  7396. }
  7397. snprintf(buf, len, "%d", count);
  7398. return 0;
  7399. }
  7400. /*! \brief Dialplan function QUEUE_MEMBER() Sets the members penalty / paused / ringinuse. */
  7401. static int queue_function_mem_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
  7402. {
  7403. int memvalue;
  7404. struct call_queue *q;
  7405. struct member *m;
  7406. char rtvalue[80];
  7407. AST_DECLARE_APP_ARGS(args,
  7408. AST_APP_ARG(queuename);
  7409. AST_APP_ARG(option);
  7410. AST_APP_ARG(interface);
  7411. );
  7412. if (ast_strlen_zero(data)) {
  7413. ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER(<queuename>,<option>,<interface>)\n");
  7414. return -1;
  7415. }
  7416. AST_STANDARD_APP_ARGS(args, data);
  7417. if (args.argc < 3) {
  7418. ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
  7419. return -1;
  7420. }
  7421. if (ast_strlen_zero(args.interface) && ast_strlen_zero(args.option)) {
  7422. ast_log (LOG_ERROR, "<interface> and <option> parameter's can't be null\n");
  7423. return -1;
  7424. }
  7425. memvalue = atoi(value);
  7426. if (!strcasecmp(args.option, "penalty")) {
  7427. /* if queuename = NULL then penalty will be set for interface in all the queues.*/
  7428. if (set_member_value(args.queuename, args.interface, MEMBER_PENALTY, memvalue)) {
  7429. ast_log(LOG_ERROR, "Invalid interface, queue or penalty\n");
  7430. return -1;
  7431. }
  7432. } else if ((q = find_load_queue_rt_friendly(args.queuename))) {
  7433. ao2_lock(q);
  7434. if ((m = interface_exists(q, args.interface))) {
  7435. sprintf(rtvalue, "%s",(memvalue <= 0) ? "0" : "1");
  7436. if (!strcasecmp(args.option, "paused")) {
  7437. if (m->realtime) {
  7438. update_realtime_member_field(m, q->name, args.option, rtvalue);
  7439. }
  7440. m->paused = (memvalue <= 0) ? 0 : 1;
  7441. ast_devstate_changed(m->paused ? QUEUE_PAUSED_DEVSTATE : QUEUE_UNPAUSED_DEVSTATE,
  7442. AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", q->name, args.interface);
  7443. } else if ((!strcasecmp(args.option, "ignorebusy")) || (!strcasecmp(args.option, "ringinuse"))) {
  7444. if (m->realtime) {
  7445. update_realtime_member_field(m, q->name, args.option, rtvalue);
  7446. }
  7447. m->ringinuse = (memvalue <= 0) ? 0 : 1;
  7448. } else {
  7449. ast_log(LOG_ERROR, "Invalid option, only penalty , paused or ringinuse/ignorebusy are valid\n");
  7450. ao2_ref(m, -1);
  7451. ao2_unlock(q);
  7452. ao2_ref(q, -1);
  7453. return -1;
  7454. }
  7455. ao2_ref(m, -1);
  7456. } else {
  7457. ao2_unlock(q);
  7458. ao2_ref(q, -1);
  7459. ast_log(LOG_ERROR, "Invalid interface for queue\n");
  7460. return -1;
  7461. }
  7462. ao2_unlock(q);
  7463. ao2_ref(q, -1);
  7464. } else {
  7465. ast_log(LOG_ERROR, "Invalid queue\n");
  7466. return -1;
  7467. }
  7468. return 0;
  7469. }
  7470. /*!
  7471. * \brief Get the total number of members in a specific queue (Deprecated)
  7472. * \retval number of members
  7473. * \retval -1 on error
  7474. */
  7475. static int queue_function_qac_dep(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  7476. {
  7477. int count = 0;
  7478. struct member *m;
  7479. struct call_queue *q;
  7480. struct ao2_iterator mem_iter;
  7481. static int depflag = 1;
  7482. if (depflag) {
  7483. depflag = 0;
  7484. ast_log(LOG_NOTICE, "The function QUEUE_MEMBER_COUNT has been deprecated in favor of the QUEUE_MEMBER function and will not be in further releases.\n");
  7485. }
  7486. if (ast_strlen_zero(data)) {
  7487. ast_log(LOG_ERROR, "%s requires an argument: queuename\n", cmd);
  7488. return -1;
  7489. }
  7490. if ((q = find_load_queue_rt_friendly(data))) {
  7491. ao2_lock(q);
  7492. mem_iter = ao2_iterator_init(q->members, 0);
  7493. while ((m = ao2_iterator_next(&mem_iter))) {
  7494. /* Count the agents who are logged in and presently answering calls */
  7495. if ((m->status != AST_DEVICE_UNAVAILABLE) && (m->status != AST_DEVICE_INVALID)) {
  7496. count++;
  7497. }
  7498. ao2_ref(m, -1);
  7499. }
  7500. ao2_iterator_destroy(&mem_iter);
  7501. ao2_unlock(q);
  7502. queue_t_unref(q, "Done with temporary reference in QUEUE_MEMBER_COUNT");
  7503. } else {
  7504. ast_log(LOG_WARNING, "queue %s was not found\n", data);
  7505. }
  7506. snprintf(buf, len, "%d", count);
  7507. return 0;
  7508. }
  7509. /*! \brief Dialplan function QUEUE_GET_CHANNEL() Get caller channel waiting at specified position in the queue */
  7510. static int queue_function_queuegetchannel(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  7511. {
  7512. int position;
  7513. char *parse;
  7514. struct call_queue *q;
  7515. struct ast_variable *var;
  7516. AST_DECLARE_APP_ARGS(args,
  7517. AST_APP_ARG(queuename);
  7518. AST_APP_ARG(position);
  7519. );
  7520. buf[0] = '\0';
  7521. if (ast_strlen_zero(data)) {
  7522. ast_log(LOG_ERROR, "Missing argument. QUEUE_GET_CHANNEL(<queuename>,<position>)\n");
  7523. return -1;
  7524. }
  7525. parse = ast_strdupa(data);
  7526. AST_STANDARD_APP_ARGS(args, parse);
  7527. if (ast_strlen_zero(args.queuename)) {
  7528. ast_log (LOG_ERROR, "The <queuename> parameter is required.\n");
  7529. return -1;
  7530. }
  7531. if (ast_strlen_zero(args.position)) {
  7532. position = 1;
  7533. } else {
  7534. if (sscanf(args.position, "%30d", &position) != 1) {
  7535. ast_log (LOG_ERROR, "<position> parameter must be an integer.\n");
  7536. return -1;
  7537. }
  7538. if (position < 1) {
  7539. ast_log (LOG_ERROR, "<position> parameter must be an integer greater than zero.\n");
  7540. return -1;
  7541. }
  7542. }
  7543. {
  7544. struct call_queue tmpq = {
  7545. .name = args.queuename,
  7546. };
  7547. q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find for QUEUE_GET_CHANNEL()");
  7548. }
  7549. if (q) {
  7550. ao2_lock(q);
  7551. if (q->count >= position) {
  7552. struct queue_ent *qe;
  7553. for (qe = q->head; qe; qe = qe->next) {
  7554. if (qe->pos == position) {
  7555. ast_copy_string(buf, ast_channel_name(qe->chan), len);
  7556. break;
  7557. }
  7558. }
  7559. }
  7560. ao2_unlock(q);
  7561. queue_t_unref(q, "Done with reference in QUEUE_GET_CHANNEL()");
  7562. return 0;
  7563. }
  7564. var = ast_load_realtime("queues", "name", args.queuename, SENTINEL);
  7565. if (var) {
  7566. /* if the queue is realtime but was not found in memory, this
  7567. * means that the queue had been deleted from memory since it was
  7568. * "dead."
  7569. */
  7570. ast_variables_destroy(var);
  7571. return 0;
  7572. }
  7573. ast_log(LOG_WARNING, "queue %s was not found\n", args.queuename);
  7574. return 0;
  7575. }
  7576. /*! \brief Dialplan function QUEUE_WAITING_COUNT() Get number callers waiting in a specific queue */
  7577. static int queue_function_queuewaitingcount(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  7578. {
  7579. int count = 0;
  7580. struct call_queue *q, tmpq = {
  7581. .name = data,
  7582. };
  7583. struct ast_variable *var = NULL;
  7584. buf[0] = '\0';
  7585. if (ast_strlen_zero(data)) {
  7586. ast_log(LOG_ERROR, "QUEUE_WAITING_COUNT requires an argument: queuename\n");
  7587. return -1;
  7588. }
  7589. if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find for QUEUE_WAITING_COUNT()"))) {
  7590. ao2_lock(q);
  7591. count = q->count;
  7592. ao2_unlock(q);
  7593. queue_t_unref(q, "Done with reference in QUEUE_WAITING_COUNT()");
  7594. } else if ((var = ast_load_realtime("queues", "name", data, SENTINEL))) {
  7595. /* if the queue is realtime but was not found in memory, this
  7596. * means that the queue had been deleted from memory since it was
  7597. * "dead." This means it has a 0 waiting count
  7598. */
  7599. count = 0;
  7600. ast_variables_destroy(var);
  7601. } else {
  7602. ast_log(LOG_WARNING, "queue %s was not found\n", data);
  7603. }
  7604. snprintf(buf, len, "%d", count);
  7605. return 0;
  7606. }
  7607. /*! \brief Dialplan function QUEUE_MEMBER_LIST() Get list of members in a specific queue */
  7608. static int queue_function_queuememberlist(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  7609. {
  7610. struct call_queue *q, tmpq = {
  7611. .name = data,
  7612. };
  7613. struct member *m;
  7614. /* Ensure an otherwise empty list doesn't return garbage */
  7615. buf[0] = '\0';
  7616. if (ast_strlen_zero(data)) {
  7617. ast_log(LOG_ERROR, "QUEUE_MEMBER_LIST requires an argument: queuename\n");
  7618. return -1;
  7619. }
  7620. if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find for QUEUE_MEMBER_LIST()"))) {
  7621. int buflen = 0, count = 0;
  7622. struct ao2_iterator mem_iter;
  7623. ao2_lock(q);
  7624. mem_iter = ao2_iterator_init(q->members, 0);
  7625. while ((m = ao2_iterator_next(&mem_iter))) {
  7626. /* strcat() is always faster than printf() */
  7627. if (count++) {
  7628. strncat(buf + buflen, ",", len - buflen - 1);
  7629. buflen++;
  7630. }
  7631. strncat(buf + buflen, m->interface, len - buflen - 1);
  7632. buflen += strlen(m->interface);
  7633. /* Safeguard against overflow (negative length) */
  7634. if (buflen >= len - 2) {
  7635. ao2_ref(m, -1);
  7636. ast_log(LOG_WARNING, "Truncating list\n");
  7637. break;
  7638. }
  7639. ao2_ref(m, -1);
  7640. }
  7641. ao2_iterator_destroy(&mem_iter);
  7642. ao2_unlock(q);
  7643. queue_t_unref(q, "Done with QUEUE_MEMBER_LIST()");
  7644. } else
  7645. ast_log(LOG_WARNING, "queue %s was not found\n", data);
  7646. /* We should already be terminated, but let's make sure. */
  7647. buf[len - 1] = '\0';
  7648. return 0;
  7649. }
  7650. /*! \brief Dialplan function QUEUE_MEMBER_PENALTY() Gets the members penalty. */
  7651. static int queue_function_memberpenalty_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  7652. {
  7653. int penalty;
  7654. AST_DECLARE_APP_ARGS(args,
  7655. AST_APP_ARG(queuename);
  7656. AST_APP_ARG(interface);
  7657. );
  7658. /* Make sure the returned value on error is NULL. */
  7659. buf[0] = '\0';
  7660. if (ast_strlen_zero(data)) {
  7661. ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
  7662. return -1;
  7663. }
  7664. AST_STANDARD_APP_ARGS(args, data);
  7665. if (args.argc < 2) {
  7666. ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
  7667. return -1;
  7668. }
  7669. penalty = get_member_penalty (args.queuename, args.interface);
  7670. if (penalty >= 0) { /* remember that buf is already '\0' */
  7671. snprintf (buf, len, "%d", penalty);
  7672. }
  7673. return 0;
  7674. }
  7675. /*! \brief Dialplan function QUEUE_MEMBER_PENALTY() Sets the members penalty. */
  7676. static int queue_function_memberpenalty_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
  7677. {
  7678. int penalty;
  7679. AST_DECLARE_APP_ARGS(args,
  7680. AST_APP_ARG(queuename);
  7681. AST_APP_ARG(interface);
  7682. );
  7683. if (ast_strlen_zero(data)) {
  7684. ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
  7685. return -1;
  7686. }
  7687. AST_STANDARD_APP_ARGS(args, data);
  7688. if (args.argc < 2) {
  7689. ast_log(LOG_ERROR, "Missing argument. QUEUE_MEMBER_PENALTY(<queuename>,<interface>)\n");
  7690. return -1;
  7691. }
  7692. penalty = atoi(value);
  7693. if (ast_strlen_zero(args.interface)) {
  7694. ast_log (LOG_ERROR, "<interface> parameter can't be null\n");
  7695. return -1;
  7696. }
  7697. /* if queuename = NULL then penalty will be set for interface in all the queues. */
  7698. if (set_member_value(args.queuename, args.interface, MEMBER_PENALTY, penalty)) {
  7699. ast_log(LOG_ERROR, "Invalid interface, queue or penalty\n");
  7700. return -1;
  7701. }
  7702. return 0;
  7703. }
  7704. static struct ast_custom_function queueexists_function = {
  7705. .name = "QUEUE_EXISTS",
  7706. .read = queue_function_exists,
  7707. };
  7708. static struct ast_custom_function queuevar_function = {
  7709. .name = "QUEUE_VARIABLES",
  7710. .read = queue_function_var,
  7711. };
  7712. static struct ast_custom_function queuemembercount_function = {
  7713. .name = "QUEUE_MEMBER",
  7714. .read = queue_function_mem_read,
  7715. .write = queue_function_mem_write,
  7716. };
  7717. static struct ast_custom_function queuemembercount_dep = {
  7718. .name = "QUEUE_MEMBER_COUNT",
  7719. .read = queue_function_qac_dep,
  7720. };
  7721. static struct ast_custom_function queuegetchannel_function = {
  7722. .name = "QUEUE_GET_CHANNEL",
  7723. .read = queue_function_queuegetchannel,
  7724. };
  7725. static struct ast_custom_function queuewaitingcount_function = {
  7726. .name = "QUEUE_WAITING_COUNT",
  7727. .read = queue_function_queuewaitingcount,
  7728. };
  7729. static struct ast_custom_function queuememberlist_function = {
  7730. .name = "QUEUE_MEMBER_LIST",
  7731. .read = queue_function_queuememberlist,
  7732. };
  7733. static struct ast_custom_function queuememberpenalty_function = {
  7734. .name = "QUEUE_MEMBER_PENALTY",
  7735. .read = queue_function_memberpenalty_read,
  7736. .write = queue_function_memberpenalty_write,
  7737. };
  7738. /*! Set the global queue rules parameters as defined in the "general" section of queuerules.conf */
  7739. static void queue_rules_set_global_params(struct ast_config *cfg)
  7740. {
  7741. const char *general_val = NULL;
  7742. realtime_rules = 0;
  7743. if ((general_val = ast_variable_retrieve(cfg, "general", "realtime_rules"))) {
  7744. realtime_rules = ast_true(general_val);
  7745. }
  7746. }
  7747. /*! \brief Reload the rules defined in queuerules.conf
  7748. *
  7749. * \param reload If 1, then only process queuerules.conf if the file
  7750. * has changed since the last time we inspected it.
  7751. * \return Always returns AST_MODULE_LOAD_SUCCESS
  7752. */
  7753. static int reload_queue_rules(int reload)
  7754. {
  7755. struct ast_config *cfg;
  7756. struct rule_list *rl_iter, *new_rl;
  7757. struct penalty_rule *pr_iter;
  7758. char *rulecat = NULL;
  7759. struct ast_variable *rulevar = NULL;
  7760. struct ast_flags config_flags = { (reload && !realtime_rules) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  7761. if (!(cfg = ast_config_load("queuerules.conf", config_flags))) {
  7762. ast_log(LOG_NOTICE, "No queuerules.conf file found, queues will not follow penalty rules\n");
  7763. return AST_MODULE_LOAD_SUCCESS;
  7764. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  7765. ast_log(LOG_NOTICE, "queuerules.conf has not changed since it was last loaded. Not taking any action.\n");
  7766. return AST_MODULE_LOAD_SUCCESS;
  7767. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  7768. ast_log(LOG_ERROR, "Config file queuerules.conf is in an invalid format. Aborting.\n");
  7769. return AST_MODULE_LOAD_SUCCESS;
  7770. }
  7771. AST_LIST_LOCK(&rule_lists);
  7772. while ((rl_iter = AST_LIST_REMOVE_HEAD(&rule_lists, list))) {
  7773. while ((pr_iter = AST_LIST_REMOVE_HEAD(&rl_iter->rules, list)))
  7774. ast_free(pr_iter);
  7775. ast_free(rl_iter);
  7776. }
  7777. while ((rulecat = ast_category_browse(cfg, rulecat))) {
  7778. if (!strcasecmp(rulecat, "general")) {
  7779. queue_rules_set_global_params(cfg);
  7780. continue;
  7781. }
  7782. if (!(new_rl = ast_calloc(1, sizeof(*new_rl)))) {
  7783. AST_LIST_UNLOCK(&rule_lists);
  7784. ast_config_destroy(cfg);
  7785. return AST_MODULE_LOAD_FAILURE;
  7786. } else {
  7787. ast_copy_string(new_rl->name, rulecat, sizeof(new_rl->name));
  7788. AST_LIST_INSERT_TAIL(&rule_lists, new_rl, list);
  7789. for (rulevar = ast_variable_browse(cfg, rulecat); rulevar; rulevar = rulevar->next)
  7790. if(!strcasecmp(rulevar->name, "penaltychange"))
  7791. insert_penaltychange(new_rl->name, rulevar->value, rulevar->lineno);
  7792. else
  7793. ast_log(LOG_WARNING, "Don't know how to handle rule type '%s' on line %d\n", rulevar->name, rulevar->lineno);
  7794. }
  7795. }
  7796. ast_config_destroy(cfg);
  7797. if (realtime_rules && load_realtime_rules()) {
  7798. AST_LIST_UNLOCK(&rule_lists);
  7799. return AST_MODULE_LOAD_DECLINE;
  7800. }
  7801. AST_LIST_UNLOCK(&rule_lists);
  7802. return AST_MODULE_LOAD_SUCCESS;
  7803. }
  7804. /*! Set the global queue parameters as defined in the "general" section of queues.conf */
  7805. static void queue_set_global_params(struct ast_config *cfg)
  7806. {
  7807. const char *general_val = NULL;
  7808. queue_persistent_members = 0;
  7809. if ((general_val = ast_variable_retrieve(cfg, "general", "persistentmembers"))) {
  7810. queue_persistent_members = ast_true(general_val);
  7811. }
  7812. autofill_default = 0;
  7813. if ((general_val = ast_variable_retrieve(cfg, "general", "autofill"))) {
  7814. autofill_default = ast_true(general_val);
  7815. }
  7816. montype_default = 0;
  7817. if ((general_val = ast_variable_retrieve(cfg, "general", "monitor-type"))) {
  7818. if (!strcasecmp(general_val, "mixmonitor"))
  7819. montype_default = 1;
  7820. }
  7821. update_cdr = 0;
  7822. if ((general_val = ast_variable_retrieve(cfg, "general", "updatecdr"))) {
  7823. update_cdr = ast_true(general_val);
  7824. }
  7825. shared_lastcall = 0;
  7826. if ((general_val = ast_variable_retrieve(cfg, "general", "shared_lastcall"))) {
  7827. shared_lastcall = ast_true(general_val);
  7828. }
  7829. negative_penalty_invalid = 0;
  7830. if ((general_val = ast_variable_retrieve(cfg, "general", "negative_penalty_invalid"))) {
  7831. negative_penalty_invalid = ast_true(general_val);
  7832. }
  7833. log_membername_as_agent = 0;
  7834. if ((general_val = ast_variable_retrieve(cfg, "general", "log_membername_as_agent"))) {
  7835. log_membername_as_agent = ast_true(general_val);
  7836. }
  7837. }
  7838. /*! \brief reload information pertaining to a single member
  7839. *
  7840. * This function is called when a member = line is encountered in
  7841. * queues.conf.
  7842. *
  7843. * \param memberdata The part after member = in the config file
  7844. * \param q The queue to which this member belongs
  7845. */
  7846. static void reload_single_member(const char *memberdata, struct call_queue *q)
  7847. {
  7848. char *membername, *interface, *state_interface, *tmp;
  7849. char *parse;
  7850. struct member *cur, *newm;
  7851. struct member tmpmem;
  7852. int penalty;
  7853. int ringinuse;
  7854. AST_DECLARE_APP_ARGS(args,
  7855. AST_APP_ARG(interface);
  7856. AST_APP_ARG(penalty);
  7857. AST_APP_ARG(membername);
  7858. AST_APP_ARG(state_interface);
  7859. AST_APP_ARG(ringinuse);
  7860. );
  7861. if (ast_strlen_zero(memberdata)) {
  7862. ast_log(LOG_WARNING, "Empty queue member definition. Moving on!\n");
  7863. return;
  7864. }
  7865. /* Add a new member */
  7866. parse = ast_strdupa(memberdata);
  7867. AST_STANDARD_APP_ARGS(args, parse);
  7868. interface = args.interface;
  7869. if (!ast_strlen_zero(args.penalty)) {
  7870. tmp = args.penalty;
  7871. ast_strip(tmp);
  7872. penalty = atoi(tmp);
  7873. if (penalty < 0) {
  7874. penalty = 0;
  7875. }
  7876. } else {
  7877. penalty = 0;
  7878. }
  7879. if (!ast_strlen_zero(args.membername)) {
  7880. membername = args.membername;
  7881. ast_strip(membername);
  7882. } else {
  7883. membername = interface;
  7884. }
  7885. if (!ast_strlen_zero(args.state_interface)) {
  7886. state_interface = args.state_interface;
  7887. ast_strip(state_interface);
  7888. } else {
  7889. state_interface = interface;
  7890. }
  7891. if (!ast_strlen_zero(args.ringinuse)) {
  7892. tmp = args.ringinuse;
  7893. ast_strip(tmp);
  7894. if (ast_true(tmp)) {
  7895. ringinuse = 1;
  7896. } else if (ast_false(tmp)) {
  7897. ringinuse = 0;
  7898. } else {
  7899. ast_log(LOG_ERROR, "Member %s has an invalid ringinuse value. Using %s ringinuse value.\n",
  7900. membername, q->name);
  7901. ringinuse = q->ringinuse;
  7902. }
  7903. } else {
  7904. ringinuse = q->ringinuse;
  7905. }
  7906. /* Find the old position in the list */
  7907. ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
  7908. cur = ao2_find(q->members, &tmpmem, OBJ_POINTER);
  7909. if ((newm = create_queue_member(interface, membername, penalty, cur ? cur->paused : 0, state_interface, ringinuse))) {
  7910. if (cur) {
  7911. /* Round Robin Queue Position must be copied if this is replacing an existing member */
  7912. ao2_lock(q->members);
  7913. newm->queuepos = cur->queuepos;
  7914. ao2_link(q->members, newm);
  7915. ao2_unlink(q->members, cur);
  7916. ao2_unlock(q->members);
  7917. } else {
  7918. /* Otherwise we need to add using the function that will apply a round robin queue position manually. */
  7919. member_add_to_queue(q, newm);
  7920. }
  7921. ao2_ref(newm, -1);
  7922. }
  7923. newm = NULL;
  7924. if (cur) {
  7925. ao2_ref(cur, -1);
  7926. }
  7927. }
  7928. static int mark_member_dead(void *obj, void *arg, int flags)
  7929. {
  7930. struct member *member = obj;
  7931. if (!member->dynamic && !member->realtime) {
  7932. member->delme = 1;
  7933. }
  7934. return 0;
  7935. }
  7936. static int kill_dead_members(void *obj, void *arg, int flags)
  7937. {
  7938. struct member *member = obj;
  7939. if (!member->delme) {
  7940. member->status = get_queue_member_status(member);
  7941. return 0;
  7942. } else {
  7943. return CMP_MATCH;
  7944. }
  7945. }
  7946. /*! \brief Reload information pertaining to a particular queue
  7947. *
  7948. * Once we have isolated a queue within reload_queues, we call this. This will either
  7949. * reload information for the queue or if we're just reloading member information, we'll just
  7950. * reload that without touching other settings within the queue
  7951. *
  7952. * \param cfg The configuration which we are reading
  7953. * \param mask Tells us what information we need to reload
  7954. * \param queuename The name of the queue we are reloading information from
  7955. * \retval void
  7956. */
  7957. static void reload_single_queue(struct ast_config *cfg, struct ast_flags *mask, const char *queuename)
  7958. {
  7959. int new;
  7960. struct call_queue *q = NULL;
  7961. /*We're defining a queue*/
  7962. struct call_queue tmpq = {
  7963. .name = queuename,
  7964. };
  7965. const char *tmpvar;
  7966. const int queue_reload = ast_test_flag(mask, QUEUE_RELOAD_PARAMETERS);
  7967. const int member_reload = ast_test_flag(mask, QUEUE_RELOAD_MEMBER);
  7968. int prev_weight = 0;
  7969. struct ast_variable *var;
  7970. if (!(q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Find queue for reload"))) {
  7971. if (queue_reload) {
  7972. /* Make one then */
  7973. if (!(q = alloc_queue(queuename))) {
  7974. return;
  7975. }
  7976. } else {
  7977. /* Since we're not reloading queues, this means that we found a queue
  7978. * in the configuration file which we don't know about yet. Just return.
  7979. */
  7980. return;
  7981. }
  7982. new = 1;
  7983. } else {
  7984. new = 0;
  7985. }
  7986. if (!new) {
  7987. ao2_lock(q);
  7988. prev_weight = q->weight ? 1 : 0;
  7989. }
  7990. /* Check if we already found a queue with this name in the config file */
  7991. if (q->found) {
  7992. ast_log(LOG_WARNING, "Queue '%s' already defined! Skipping!\n", queuename);
  7993. if (!new) {
  7994. /* It should be impossible to *not* hit this case*/
  7995. ao2_unlock(q);
  7996. }
  7997. queue_t_unref(q, "We exist! Expiring temporary pointer");
  7998. return;
  7999. }
  8000. /* Due to the fact that the "linear" strategy will have a different allocation
  8001. * scheme for queue members, we must devise the queue's strategy before other initializations.
  8002. * To be specific, the linear strategy needs to function like a linked list, meaning the ao2
  8003. * container used will have only a single bucket instead of the typical number.
  8004. */
  8005. if (queue_reload) {
  8006. if ((tmpvar = ast_variable_retrieve(cfg, queuename, "strategy"))) {
  8007. q->strategy = strat2int(tmpvar);
  8008. if (q->strategy < 0) {
  8009. ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
  8010. tmpvar, q->name);
  8011. q->strategy = QUEUE_STRATEGY_RINGALL;
  8012. }
  8013. } else {
  8014. q->strategy = QUEUE_STRATEGY_RINGALL;
  8015. }
  8016. init_queue(q);
  8017. }
  8018. if (member_reload) {
  8019. ao2_callback(q->members, OBJ_NODATA, mark_member_dead, NULL);
  8020. q->found = 1;
  8021. }
  8022. /* On the first pass we just read the parameters of the queue */
  8023. for (var = ast_variable_browse(cfg, queuename); var; var = var->next) {
  8024. if (queue_reload && strcasecmp(var->name, "member")) {
  8025. queue_set_param(q, var->name, var->value, var->lineno, 1);
  8026. }
  8027. }
  8028. /* On the second pass, we read members */
  8029. for (var = ast_variable_browse(cfg, queuename); var; var = var->next) {
  8030. if (member_reload && !strcasecmp(var->name, "member")) {
  8031. reload_single_member(var->value, q);
  8032. }
  8033. }
  8034. /* At this point, we've determined if the queue has a weight, so update use_weight
  8035. * as appropriate
  8036. */
  8037. if (!q->weight && prev_weight) {
  8038. ast_atomic_fetchadd_int(&use_weight, -1);
  8039. } else if (q->weight && !prev_weight) {
  8040. ast_atomic_fetchadd_int(&use_weight, +1);
  8041. }
  8042. /* Free remaining members marked as delme */
  8043. if (member_reload) {
  8044. ao2_lock(q->members);
  8045. ao2_callback(q->members, OBJ_NODATA | OBJ_MULTIPLE, queue_delme_members_decrement_followers, q);
  8046. ao2_callback(q->members, OBJ_NODATA | OBJ_MULTIPLE | OBJ_UNLINK, kill_dead_members, q);
  8047. ao2_unlock(q->members);
  8048. }
  8049. if (new) {
  8050. queues_t_link(queues, q, "Add queue to container");
  8051. } else {
  8052. ao2_unlock(q);
  8053. }
  8054. queue_t_unref(q, "Expiring creation reference");
  8055. }
  8056. static int remove_members_and_mark_unfound(void *obj, void *arg, int flags)
  8057. {
  8058. struct call_queue *q = obj;
  8059. char *queuename = arg;
  8060. if (!q->realtime && (ast_strlen_zero(queuename) || !strcasecmp(queuename, q->name))) {
  8061. q->found = 0;
  8062. }
  8063. return 0;
  8064. }
  8065. static int mark_dead_and_unfound(void *obj, void *arg, int flags)
  8066. {
  8067. struct call_queue *q = obj;
  8068. char *queuename = arg;
  8069. if (!q->realtime && (ast_strlen_zero(queuename) || !strcasecmp(queuename, q->name))) {
  8070. q->dead = 1;
  8071. q->found = 0;
  8072. }
  8073. return 0;
  8074. }
  8075. static int kill_dead_queues(void *obj, void *arg, int flags)
  8076. {
  8077. struct call_queue *q = obj;
  8078. char *queuename = arg;
  8079. if ((ast_strlen_zero(queuename) || !strcasecmp(queuename, q->name)) && q->dead) {
  8080. return CMP_MATCH;
  8081. } else {
  8082. return 0;
  8083. }
  8084. }
  8085. /*! \brief reload the queues.conf file
  8086. *
  8087. * This function reloads the information in the general section of the queues.conf
  8088. * file and potentially more, depending on the value of mask.
  8089. *
  8090. * \param reload 0 if we are calling this the first time, 1 every other time
  8091. * \param mask Gives flags telling us what information to actually reload
  8092. * \param queuename If set to a non-zero string, then only reload information from
  8093. * that particular queue. Otherwise inspect all queues
  8094. * \retval -1 Failure occurred
  8095. * \retval 0 All clear!
  8096. */
  8097. static int reload_queues(int reload, struct ast_flags *mask, const char *queuename)
  8098. {
  8099. struct ast_config *cfg;
  8100. char *cat;
  8101. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  8102. const int queue_reload = ast_test_flag(mask, QUEUE_RELOAD_PARAMETERS);
  8103. const int member_reload = ast_test_flag(mask, QUEUE_RELOAD_MEMBER);
  8104. if (!(cfg = ast_config_load("queues.conf", config_flags))) {
  8105. ast_log(LOG_NOTICE, "No call queueing config file (queues.conf), so no call queues\n");
  8106. return -1;
  8107. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  8108. return 0;
  8109. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  8110. ast_log(LOG_ERROR, "Config file queues.conf is in an invalid format. Aborting.\n");
  8111. return -1;
  8112. }
  8113. /* We've made it here, so it looks like we're doing operations on all queues. */
  8114. ao2_lock(queues);
  8115. /* Mark all queues as dead for the moment if we're reloading queues.
  8116. * For clarity, we could just be reloading members, in which case we don't want to mess
  8117. * with the other queue parameters at all*/
  8118. if (queue_reload) {
  8119. ao2_callback(queues, OBJ_NODATA | OBJ_NOLOCK, mark_dead_and_unfound, (char *) queuename);
  8120. }
  8121. if (member_reload) {
  8122. ao2_callback(queues, OBJ_NODATA, remove_members_and_mark_unfound, (char *) queuename);
  8123. }
  8124. /* Chug through config file */
  8125. cat = NULL;
  8126. while ((cat = ast_category_browse(cfg, cat)) ) {
  8127. if (!strcasecmp(cat, "general") && queue_reload) {
  8128. queue_set_global_params(cfg);
  8129. continue;
  8130. }
  8131. if (ast_strlen_zero(queuename) || !strcasecmp(cat, queuename))
  8132. reload_single_queue(cfg, mask, cat);
  8133. }
  8134. ast_config_destroy(cfg);
  8135. /* Unref all the dead queues if we were reloading queues */
  8136. if (queue_reload) {
  8137. ao2_callback(queues, OBJ_NODATA | OBJ_MULTIPLE | OBJ_UNLINK | OBJ_NOLOCK, kill_dead_queues, (char *) queuename);
  8138. }
  8139. ao2_unlock(queues);
  8140. return 0;
  8141. }
  8142. /*! \brief Facilitates resetting statistics for a queue
  8143. *
  8144. * This function actually does not reset any statistics, but
  8145. * rather finds a call_queue struct which corresponds to the
  8146. * passed-in queue name and passes that structure to the
  8147. * clear_queue function. If no queuename is passed in, then
  8148. * all queues will have their statistics reset.
  8149. *
  8150. * \param queuename The name of the queue to reset the statistics
  8151. * for. If this is NULL or zero-length, then this means to reset
  8152. * the statistics for all queues
  8153. * \retval void
  8154. */
  8155. static int clear_stats(const char *queuename)
  8156. {
  8157. struct call_queue *q;
  8158. struct ao2_iterator queue_iter;
  8159. queue_iter = ao2_iterator_init(queues, 0);
  8160. while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
  8161. ao2_lock(q);
  8162. if (ast_strlen_zero(queuename) || !strcasecmp(q->name, queuename))
  8163. clear_queue(q);
  8164. ao2_unlock(q);
  8165. queue_t_unref(q, "Done with iterator");
  8166. }
  8167. ao2_iterator_destroy(&queue_iter);
  8168. return 0;
  8169. }
  8170. /*! \brief The command center for all reload operations
  8171. *
  8172. * Whenever any piece of queue information is to be reloaded, this function
  8173. * is called. It interprets the flags set in the mask parameter and acts
  8174. * based on how they are set.
  8175. *
  8176. * \param reload True if we are reloading information, false if we are loading
  8177. * information for the first time.
  8178. * \param mask A bitmask which tells the handler what actions to take
  8179. * \param queuename The name of the queue on which we wish to take action
  8180. * \retval 0 All reloads were successful
  8181. * \retval non-zero There was a failure
  8182. */
  8183. static int reload_handler(int reload, struct ast_flags *mask, const char *queuename)
  8184. {
  8185. int res = 0;
  8186. if (ast_test_flag(mask, QUEUE_RELOAD_RULES)) {
  8187. res |= reload_queue_rules(reload);
  8188. }
  8189. if (ast_test_flag(mask, QUEUE_RESET_STATS)) {
  8190. res |= clear_stats(queuename);
  8191. }
  8192. if (ast_test_flag(mask, (QUEUE_RELOAD_PARAMETERS | QUEUE_RELOAD_MEMBER))) {
  8193. res |= reload_queues(reload, mask, queuename);
  8194. }
  8195. return res;
  8196. }
  8197. /*! \brief direct ouput to manager or cli with proper terminator */
  8198. static void do_print(struct mansession *s, int fd, const char *str)
  8199. {
  8200. if (s) {
  8201. astman_append(s, "%s\r\n", str);
  8202. } else {
  8203. ast_cli(fd, "%s\n", str);
  8204. }
  8205. }
  8206. /*!
  8207. * \brief Show queue(s) status and statistics
  8208. *
  8209. * List the queues strategy, calls processed, members logged in,
  8210. * other queue statistics such as avg hold time.
  8211. */
  8212. static char *__queues_show(struct mansession *s, int fd, int argc, const char * const *argv)
  8213. {
  8214. struct call_queue *q;
  8215. struct ast_str *out = ast_str_alloca(240);
  8216. int found = 0;
  8217. time_t now = time(NULL);
  8218. struct ao2_iterator queue_iter;
  8219. struct ao2_iterator mem_iter;
  8220. if (argc != 2 && argc != 3) {
  8221. return CLI_SHOWUSAGE;
  8222. }
  8223. if (argc == 3) { /* specific queue */
  8224. if ((q = find_load_queue_rt_friendly(argv[2]))) {
  8225. queue_t_unref(q, "Done with temporary pointer");
  8226. }
  8227. } else if (ast_check_realtime("queues")) {
  8228. /* This block is to find any queues which are defined in realtime but
  8229. * which have not yet been added to the in-core container
  8230. */
  8231. struct ast_config *cfg = ast_load_realtime_multientry("queues", "name LIKE", "%", SENTINEL);
  8232. char *queuename;
  8233. if (cfg) {
  8234. for (queuename = ast_category_browse(cfg, NULL); !ast_strlen_zero(queuename); queuename = ast_category_browse(cfg, queuename)) {
  8235. if ((q = find_load_queue_rt_friendly(queuename))) {
  8236. queue_t_unref(q, "Done with temporary pointer");
  8237. }
  8238. }
  8239. ast_config_destroy(cfg);
  8240. }
  8241. }
  8242. ao2_lock(queues);
  8243. queue_iter = ao2_iterator_init(queues, AO2_ITERATOR_DONTLOCK);
  8244. while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
  8245. float sl;
  8246. struct call_queue *realtime_queue = NULL;
  8247. ao2_lock(q);
  8248. /* This check is to make sure we don't print information for realtime
  8249. * queues which have been deleted from realtime but which have not yet
  8250. * been deleted from the in-core container. Only do this if we're not
  8251. * looking for a specific queue.
  8252. */
  8253. if (argc < 3 && q->realtime) {
  8254. realtime_queue = find_load_queue_rt_friendly(q->name);
  8255. if (!realtime_queue) {
  8256. ao2_unlock(q);
  8257. queue_t_unref(q, "Done with iterator");
  8258. continue;
  8259. }
  8260. queue_t_unref(realtime_queue, "Queue is already in memory");
  8261. }
  8262. if (argc == 3 && strcasecmp(q->name, argv[2])) {
  8263. ao2_unlock(q);
  8264. queue_t_unref(q, "Done with iterator");
  8265. continue;
  8266. }
  8267. found = 1;
  8268. ast_str_set(&out, 0, "%s has %d calls (max ", q->name, q->count);
  8269. if (q->maxlen) {
  8270. ast_str_append(&out, 0, "%d", q->maxlen);
  8271. } else {
  8272. ast_str_append(&out, 0, "unlimited");
  8273. }
  8274. sl = 0;
  8275. if (q->callscompleted > 0) {
  8276. sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
  8277. }
  8278. ast_str_append(&out, 0, ") in '%s' strategy (%ds holdtime, %ds talktime), W:%d, C:%d, A:%d, SL:%2.1f%% within %ds",
  8279. int2strat(q->strategy), q->holdtime, q->talktime, q->weight,
  8280. q->callscompleted, q->callsabandoned,sl,q->servicelevel);
  8281. do_print(s, fd, ast_str_buffer(out));
  8282. if (!ao2_container_count(q->members)) {
  8283. do_print(s, fd, " No Members");
  8284. } else {
  8285. struct member *mem;
  8286. do_print(s, fd, " Members: ");
  8287. mem_iter = ao2_iterator_init(q->members, 0);
  8288. while ((mem = ao2_iterator_next(&mem_iter))) {
  8289. ast_str_set(&out, 0, " %s", mem->membername);
  8290. if (strcasecmp(mem->membername, mem->interface)) {
  8291. ast_str_append(&out, 0, " (%s", mem->interface);
  8292. if (!ast_strlen_zero(mem->state_interface)) {
  8293. ast_str_append(&out, 0, " from %s", mem->state_interface);
  8294. }
  8295. ast_str_append(&out, 0, ")");
  8296. }
  8297. if (mem->penalty) {
  8298. ast_str_append(&out, 0, " with penalty %d", mem->penalty);
  8299. }
  8300. ast_str_append(&out, 0, " (ringinuse %s)", mem->ringinuse ? "enabled" : "disabled");
  8301. ast_str_append(&out, 0, "%s%s%s%s%s%s%s%s%s (%s%s%s)",
  8302. mem->dynamic ? ast_term_color(COLOR_CYAN, COLOR_BLACK) : "", mem->dynamic ? " (dynamic)" : "", ast_term_reset(),
  8303. mem->realtime ? ast_term_color(COLOR_MAGENTA, COLOR_BLACK) : "", mem->realtime ? " (realtime)" : "", ast_term_reset(),
  8304. mem->paused ? ast_term_color(COLOR_BROWN, COLOR_BLACK) : "", mem->paused ? " (paused)" : "", ast_term_reset(),
  8305. ast_term_color(
  8306. mem->status == AST_DEVICE_UNAVAILABLE || mem->status == AST_DEVICE_UNKNOWN ?
  8307. COLOR_RED : COLOR_GREEN, COLOR_BLACK),
  8308. ast_devstate2str(mem->status), ast_term_reset());
  8309. if (mem->calls) {
  8310. ast_str_append(&out, 0, " has taken %d calls (last was %ld secs ago)",
  8311. mem->calls, (long) (time(NULL) - mem->lastcall));
  8312. } else {
  8313. ast_str_append(&out, 0, " has taken no calls yet");
  8314. }
  8315. do_print(s, fd, ast_str_buffer(out));
  8316. ao2_ref(mem, -1);
  8317. }
  8318. ao2_iterator_destroy(&mem_iter);
  8319. }
  8320. if (!q->head) {
  8321. do_print(s, fd, " No Callers");
  8322. } else {
  8323. struct queue_ent *qe;
  8324. int pos = 1;
  8325. do_print(s, fd, " Callers: ");
  8326. for (qe = q->head; qe; qe = qe->next) {
  8327. ast_str_set(&out, 0, " %d. %s (wait: %ld:%2.2ld, prio: %d)",
  8328. pos++, ast_channel_name(qe->chan), (long) (now - qe->start) / 60,
  8329. (long) (now - qe->start) % 60, qe->prio);
  8330. do_print(s, fd, ast_str_buffer(out));
  8331. }
  8332. }
  8333. do_print(s, fd, ""); /* blank line between entries */
  8334. ao2_unlock(q);
  8335. queue_t_unref(q, "Done with iterator"); /* Unref the iterator's reference */
  8336. }
  8337. ao2_iterator_destroy(&queue_iter);
  8338. ao2_unlock(queues);
  8339. if (!found) {
  8340. if (argc == 3) {
  8341. ast_str_set(&out, 0, "No such queue: %s.", argv[2]);
  8342. } else {
  8343. ast_str_set(&out, 0, "No queues.");
  8344. }
  8345. do_print(s, fd, ast_str_buffer(out));
  8346. }
  8347. return CLI_SUCCESS;
  8348. }
  8349. /*!
  8350. * \brief Check if a given word is in a space-delimited list
  8351. *
  8352. * \param list Space delimited list of words
  8353. * \param word The word used to search the list
  8354. *
  8355. * \note This function will not return 1 if the word is at the very end of the
  8356. * list (followed immediately by a \0, not a space) since it is used for
  8357. * checking tab-completion and a word at the end is still being tab-completed.
  8358. *
  8359. * \return Returns 1 if the word is found
  8360. * \return Returns 0 if the word is not found
  8361. */
  8362. static int word_in_list(const char *list, const char *word) {
  8363. int list_len, word_len = strlen(word);
  8364. const char *find, *end_find, *end_list;
  8365. /* strip whitespace from front */
  8366. while(isspace(*list)) {
  8367. list++;
  8368. }
  8369. while((find = strstr(list, word))) {
  8370. /* beginning of find starts inside another word? */
  8371. if (find != list && *(find - 1) != ' ') {
  8372. list = find;
  8373. /* strip word from front */
  8374. while(!isspace(*list) && *list != '\0') {
  8375. list++;
  8376. }
  8377. /* strip whitespace from front */
  8378. while(isspace(*list)) {
  8379. list++;
  8380. }
  8381. continue;
  8382. }
  8383. /* end of find ends inside another word or at very end of list? */
  8384. list_len = strlen(list);
  8385. end_find = find + word_len;
  8386. end_list = list + list_len;
  8387. if (end_find == end_list || *end_find != ' ') {
  8388. list = find;
  8389. /* strip word from front */
  8390. while(!isspace(*list) && *list != '\0') {
  8391. list++;
  8392. }
  8393. /* strip whitespace from front */
  8394. while(isspace(*list)) {
  8395. list++;
  8396. }
  8397. continue;
  8398. }
  8399. /* terminating conditions satisfied, word at beginning or separated by ' ' */
  8400. return 1;
  8401. }
  8402. return 0;
  8403. }
  8404. /*!
  8405. * \brief Check if a given word is in a space-delimited list
  8406. *
  8407. * \param line The line as typed not including the current word being completed
  8408. * \param word The word currently being completed
  8409. * \param pos The number of completed words in line
  8410. * \param state The nth desired completion option
  8411. * \param word_list_offset Offset into the line where the list of queues begins. If non-zero, queues in the list will not be offered for further completion.
  8412. *
  8413. * \return Returns the queue tab-completion for the given word and state
  8414. */
  8415. static char *complete_queue(const char *line, const char *word, int pos, int state, ptrdiff_t word_list_offset)
  8416. {
  8417. struct call_queue *q;
  8418. char *ret = NULL;
  8419. int which = 0;
  8420. int wordlen = strlen(word);
  8421. struct ao2_iterator queue_iter;
  8422. const char *word_list = NULL;
  8423. /* for certain commands, already completed items should be left out of
  8424. * the list */
  8425. if (word_list_offset && strlen(line) >= word_list_offset) {
  8426. word_list = line + word_list_offset;
  8427. }
  8428. queue_iter = ao2_iterator_init(queues, 0);
  8429. while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
  8430. if (!strncasecmp(word, q->name, wordlen) && ++which > state
  8431. && (!word_list_offset || !word_in_list(word_list, q->name))) {
  8432. ret = ast_strdup(q->name);
  8433. queue_t_unref(q, "Done with iterator");
  8434. break;
  8435. }
  8436. queue_t_unref(q, "Done with iterator");
  8437. }
  8438. ao2_iterator_destroy(&queue_iter);
  8439. /* Pretend "rules" is at the end of the queues list in certain
  8440. * circumstances since it is an alternate command that should be
  8441. * tab-completable for "queue show" */
  8442. if (!ret && which == state && !wordlen && !strncmp("queue show", line, 10)) {
  8443. ret = ast_strdup("rules");
  8444. }
  8445. return ret;
  8446. }
  8447. static char *complete_queue_show(const char *line, const char *word, int pos, int state)
  8448. {
  8449. if (pos == 2) {
  8450. return complete_queue(line, word, pos, state, 0);
  8451. }
  8452. return NULL;
  8453. }
  8454. static char *queue_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  8455. {
  8456. switch ( cmd ) {
  8457. case CLI_INIT:
  8458. e->command = "queue show";
  8459. e->usage =
  8460. "Usage: queue show\n"
  8461. " Provides summary information on a specified queue.\n";
  8462. return NULL;
  8463. case CLI_GENERATE:
  8464. return complete_queue_show(a->line, a->word, a->pos, a->n);
  8465. }
  8466. return __queues_show(NULL, a->fd, a->argc, a->argv);
  8467. }
  8468. /*!\brief callback to display queues status in manager
  8469. \addtogroup Group_AMI
  8470. */
  8471. static int manager_queues_show(struct mansession *s, const struct message *m)
  8472. {
  8473. static const char * const a[] = { "queue", "show" };
  8474. __queues_show(s, -1, 2, a);
  8475. astman_append(s, "\r\n\r\n"); /* Properly terminate Manager output */
  8476. return RESULT_SUCCESS;
  8477. }
  8478. static int manager_queue_rule_show(struct mansession *s, const struct message *m)
  8479. {
  8480. const char *rule = astman_get_header(m, "Rule");
  8481. const char *id = astman_get_header(m, "ActionID");
  8482. struct rule_list *rl_iter;
  8483. struct penalty_rule *pr_iter;
  8484. astman_append(s, "Response: Success\r\n");
  8485. if (!ast_strlen_zero(id)) {
  8486. astman_append(s, "ActionID: %s\r\n", id);
  8487. }
  8488. AST_LIST_LOCK(&rule_lists);
  8489. AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
  8490. if (ast_strlen_zero(rule) || !strcasecmp(rule, rl_iter->name)) {
  8491. astman_append(s, "RuleList: %s\r\n", rl_iter->name);
  8492. AST_LIST_TRAVERSE(&rl_iter->rules, pr_iter, list) {
  8493. astman_append(s, "Rule: %d,%s%d,%s%d\r\n", pr_iter->time, pr_iter->max_relative && pr_iter->max_value >= 0 ? "+" : "", pr_iter->max_value, pr_iter->min_relative && pr_iter->min_value >= 0 ? "+" : "", pr_iter->min_value );
  8494. }
  8495. if (!ast_strlen_zero(rule)) {
  8496. break;
  8497. }
  8498. }
  8499. }
  8500. AST_LIST_UNLOCK(&rule_lists);
  8501. /*
  8502. * Two blank lines instead of one because the Response and
  8503. * ActionID headers used to not be present.
  8504. */
  8505. astman_append(s, "\r\n\r\n");
  8506. return RESULT_SUCCESS;
  8507. }
  8508. /*! \brief Summary of queue info via the AMI */
  8509. static int manager_queues_summary(struct mansession *s, const struct message *m)
  8510. {
  8511. time_t now;
  8512. int qmemcount = 0;
  8513. int qmemavail = 0;
  8514. int qchancount = 0;
  8515. int qlongestholdtime = 0;
  8516. int qsummaries = 0;
  8517. const char *id = astman_get_header(m, "ActionID");
  8518. const char *queuefilter = astman_get_header(m, "Queue");
  8519. char idText[256];
  8520. struct call_queue *q;
  8521. struct queue_ent *qe;
  8522. struct member *mem;
  8523. struct ao2_iterator queue_iter;
  8524. struct ao2_iterator mem_iter;
  8525. astman_send_listack(s, m, "Queue summary will follow", "start");
  8526. time(&now);
  8527. idText[0] = '\0';
  8528. if (!ast_strlen_zero(id)) {
  8529. snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
  8530. }
  8531. queue_iter = ao2_iterator_init(queues, 0);
  8532. while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
  8533. ao2_lock(q);
  8534. /* List queue properties */
  8535. if (ast_strlen_zero(queuefilter) || !strcmp(q->name, queuefilter)) {
  8536. /* Reset the necessary local variables if no queuefilter is set*/
  8537. qmemcount = 0;
  8538. qmemavail = 0;
  8539. qchancount = 0;
  8540. qlongestholdtime = 0;
  8541. /* List Queue Members */
  8542. mem_iter = ao2_iterator_init(q->members, 0);
  8543. while ((mem = ao2_iterator_next(&mem_iter))) {
  8544. if ((mem->status != AST_DEVICE_UNAVAILABLE) && (mem->status != AST_DEVICE_INVALID)) {
  8545. ++qmemcount;
  8546. if (member_status_available(mem->status) && !mem->paused) {
  8547. ++qmemavail;
  8548. }
  8549. }
  8550. ao2_ref(mem, -1);
  8551. }
  8552. ao2_iterator_destroy(&mem_iter);
  8553. for (qe = q->head; qe; qe = qe->next) {
  8554. if ((now - qe->start) > qlongestholdtime) {
  8555. qlongestholdtime = now - qe->start;
  8556. }
  8557. ++qchancount;
  8558. }
  8559. astman_append(s, "Event: QueueSummary\r\n"
  8560. "Queue: %s\r\n"
  8561. "LoggedIn: %d\r\n"
  8562. "Available: %d\r\n"
  8563. "Callers: %d\r\n"
  8564. "HoldTime: %d\r\n"
  8565. "TalkTime: %d\r\n"
  8566. "LongestHoldTime: %d\r\n"
  8567. "%s"
  8568. "\r\n",
  8569. q->name, qmemcount, qmemavail, qchancount, q->holdtime, q->talktime, qlongestholdtime, idText);
  8570. ++qsummaries;
  8571. }
  8572. ao2_unlock(q);
  8573. queue_t_unref(q, "Done with iterator");
  8574. }
  8575. ao2_iterator_destroy(&queue_iter);
  8576. astman_send_list_complete_start(s, m, "QueueSummaryComplete", qsummaries);
  8577. astman_send_list_complete_end(s);
  8578. return RESULT_SUCCESS;
  8579. }
  8580. /*! \brief Queue status info via AMI */
  8581. static int manager_queues_status(struct mansession *s, const struct message *m)
  8582. {
  8583. time_t now;
  8584. int pos;
  8585. int q_items = 0;
  8586. const char *id = astman_get_header(m,"ActionID");
  8587. const char *queuefilter = astman_get_header(m,"Queue");
  8588. const char *memberfilter = astman_get_header(m,"Member");
  8589. char idText[256];
  8590. struct call_queue *q;
  8591. struct queue_ent *qe;
  8592. float sl = 0;
  8593. struct member *mem;
  8594. struct ao2_iterator queue_iter;
  8595. struct ao2_iterator mem_iter;
  8596. astman_send_listack(s, m, "Queue status will follow", "start");
  8597. time(&now);
  8598. idText[0] = '\0';
  8599. if (!ast_strlen_zero(id)) {
  8600. snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
  8601. }
  8602. queue_iter = ao2_iterator_init(queues, 0);
  8603. while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
  8604. ao2_lock(q);
  8605. /* List queue properties */
  8606. if (ast_strlen_zero(queuefilter) || !strcmp(q->name, queuefilter)) {
  8607. sl = ((q->callscompleted > 0) ? 100 * ((float)q->callscompletedinsl / (float)q->callscompleted) : 0);
  8608. astman_append(s, "Event: QueueParams\r\n"
  8609. "Queue: %s\r\n"
  8610. "Max: %d\r\n"
  8611. "Strategy: %s\r\n"
  8612. "Calls: %d\r\n"
  8613. "Holdtime: %d\r\n"
  8614. "TalkTime: %d\r\n"
  8615. "Completed: %d\r\n"
  8616. "Abandoned: %d\r\n"
  8617. "ServiceLevel: %d\r\n"
  8618. "ServicelevelPerf: %2.1f\r\n"
  8619. "Weight: %d\r\n"
  8620. "%s"
  8621. "\r\n",
  8622. q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted,
  8623. q->callsabandoned, q->servicelevel, sl, q->weight, idText);
  8624. ++q_items;
  8625. /* List Queue Members */
  8626. mem_iter = ao2_iterator_init(q->members, 0);
  8627. while ((mem = ao2_iterator_next(&mem_iter))) {
  8628. if (ast_strlen_zero(memberfilter) || !strcmp(mem->interface, memberfilter) || !strcmp(mem->membername, memberfilter)) {
  8629. astman_append(s, "Event: QueueMember\r\n"
  8630. "Queue: %s\r\n"
  8631. "Name: %s\r\n"
  8632. "Location: %s\r\n"
  8633. "StateInterface: %s\r\n"
  8634. "Membership: %s\r\n"
  8635. "Penalty: %d\r\n"
  8636. "CallsTaken: %d\r\n"
  8637. "LastCall: %d\r\n"
  8638. "Status: %d\r\n"
  8639. "Paused: %d\r\n"
  8640. "%s"
  8641. "\r\n",
  8642. q->name, mem->membername, mem->interface, mem->state_interface, mem->dynamic ? "dynamic" : "static",
  8643. mem->penalty, mem->calls, (int)mem->lastcall, mem->status, mem->paused, idText);
  8644. ++q_items;
  8645. }
  8646. ao2_ref(mem, -1);
  8647. }
  8648. ao2_iterator_destroy(&mem_iter);
  8649. /* List Queue Entries */
  8650. pos = 1;
  8651. for (qe = q->head; qe; qe = qe->next) {
  8652. astman_append(s, "Event: QueueEntry\r\n"
  8653. "Queue: %s\r\n"
  8654. "Position: %d\r\n"
  8655. "Channel: %s\r\n"
  8656. "Uniqueid: %s\r\n"
  8657. "CallerIDNum: %s\r\n"
  8658. "CallerIDName: %s\r\n"
  8659. "ConnectedLineNum: %s\r\n"
  8660. "ConnectedLineName: %s\r\n"
  8661. "Wait: %ld\r\n"
  8662. "%s"
  8663. "\r\n",
  8664. q->name, pos++, ast_channel_name(qe->chan), ast_channel_uniqueid(qe->chan),
  8665. S_COR(ast_channel_caller(qe->chan)->id.number.valid, ast_channel_caller(qe->chan)->id.number.str, "unknown"),
  8666. S_COR(ast_channel_caller(qe->chan)->id.name.valid, ast_channel_caller(qe->chan)->id.name.str, "unknown"),
  8667. S_COR(ast_channel_connected(qe->chan)->id.number.valid, ast_channel_connected(qe->chan)->id.number.str, "unknown"),
  8668. S_COR(ast_channel_connected(qe->chan)->id.name.valid, ast_channel_connected(qe->chan)->id.name.str, "unknown"),
  8669. (long) (now - qe->start), idText);
  8670. ++q_items;
  8671. }
  8672. }
  8673. ao2_unlock(q);
  8674. queue_t_unref(q, "Done with iterator");
  8675. }
  8676. ao2_iterator_destroy(&queue_iter);
  8677. astman_send_list_complete_start(s, m, "QueueStatusComplete", q_items);
  8678. astman_send_list_complete_end(s);
  8679. return RESULT_SUCCESS;
  8680. }
  8681. static int manager_add_queue_member(struct mansession *s, const struct message *m)
  8682. {
  8683. const char *queuename, *interface, *penalty_s, *paused_s, *membername, *state_interface;
  8684. int paused, penalty = 0;
  8685. queuename = astman_get_header(m, "Queue");
  8686. interface = astman_get_header(m, "Interface");
  8687. penalty_s = astman_get_header(m, "Penalty");
  8688. paused_s = astman_get_header(m, "Paused");
  8689. membername = astman_get_header(m, "MemberName");
  8690. state_interface = astman_get_header(m, "StateInterface");
  8691. if (ast_strlen_zero(queuename)) {
  8692. astman_send_error(s, m, "'Queue' not specified.");
  8693. return 0;
  8694. }
  8695. if (ast_strlen_zero(interface)) {
  8696. astman_send_error(s, m, "'Interface' not specified.");
  8697. return 0;
  8698. }
  8699. if (ast_strlen_zero(penalty_s)) {
  8700. penalty = 0;
  8701. } else if (sscanf(penalty_s, "%30d", &penalty) != 1 || penalty < 0) {
  8702. penalty = 0;
  8703. }
  8704. if (ast_strlen_zero(paused_s)) {
  8705. paused = 0;
  8706. } else {
  8707. paused = abs(ast_true(paused_s));
  8708. }
  8709. switch (add_to_queue(queuename, interface, membername, penalty, paused, queue_persistent_members, state_interface)) {
  8710. case RES_OKAY:
  8711. if (ast_strlen_zero(membername) || !log_membername_as_agent) {
  8712. ast_queue_log(queuename, "MANAGER", interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
  8713. } else {
  8714. ast_queue_log(queuename, "MANAGER", membername, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
  8715. }
  8716. astman_send_ack(s, m, "Added interface to queue");
  8717. break;
  8718. case RES_EXISTS:
  8719. astman_send_error(s, m, "Unable to add interface: Already there");
  8720. break;
  8721. case RES_NOSUCHQUEUE:
  8722. astman_send_error(s, m, "Unable to add interface to queue: No such queue");
  8723. break;
  8724. case RES_OUTOFMEMORY:
  8725. astman_send_error(s, m, "Out of memory");
  8726. break;
  8727. }
  8728. return 0;
  8729. }
  8730. static int manager_remove_queue_member(struct mansession *s, const struct message *m)
  8731. {
  8732. const char *queuename, *interface;
  8733. struct member *mem = NULL;
  8734. queuename = astman_get_header(m, "Queue");
  8735. interface = astman_get_header(m, "Interface");
  8736. if (ast_strlen_zero(queuename) || ast_strlen_zero(interface)) {
  8737. astman_send_error(s, m, "Need 'Queue' and 'Interface' parameters.");
  8738. return 0;
  8739. }
  8740. if (log_membername_as_agent) {
  8741. mem = find_member_by_queuename_and_interface(queuename, interface);
  8742. }
  8743. switch (remove_from_queue(queuename, interface)) {
  8744. case RES_OKAY:
  8745. if (!mem || ast_strlen_zero(mem->membername)) {
  8746. ast_queue_log(queuename, "MANAGER", interface, "REMOVEMEMBER", "%s", "");
  8747. } else {
  8748. ast_queue_log(queuename, "MANAGER", mem->membername, "REMOVEMEMBER", "%s", "");
  8749. }
  8750. astman_send_ack(s, m, "Removed interface from queue");
  8751. break;
  8752. case RES_EXISTS:
  8753. astman_send_error(s, m, "Unable to remove interface: Not there");
  8754. break;
  8755. case RES_NOSUCHQUEUE:
  8756. astman_send_error(s, m, "Unable to remove interface from queue: No such queue");
  8757. break;
  8758. case RES_OUTOFMEMORY:
  8759. astman_send_error(s, m, "Out of memory");
  8760. break;
  8761. case RES_NOT_DYNAMIC:
  8762. astman_send_error(s, m, "Member not dynamic");
  8763. break;
  8764. }
  8765. if (mem) {
  8766. ao2_ref(mem, -1);
  8767. }
  8768. return 0;
  8769. }
  8770. static int manager_pause_queue_member(struct mansession *s, const struct message *m)
  8771. {
  8772. const char *queuename, *interface, *paused_s, *reason;
  8773. int paused;
  8774. interface = astman_get_header(m, "Interface");
  8775. paused_s = astman_get_header(m, "Paused");
  8776. queuename = astman_get_header(m, "Queue"); /* Optional - if not supplied, pause the given Interface in all queues */
  8777. reason = astman_get_header(m, "Reason"); /* Optional - Only used for logging purposes */
  8778. if (ast_strlen_zero(interface) || ast_strlen_zero(paused_s)) {
  8779. astman_send_error(s, m, "Need 'Interface' and 'Paused' parameters.");
  8780. return 0;
  8781. }
  8782. paused = abs(ast_true(paused_s));
  8783. if (set_member_paused(queuename, interface, reason, paused)) {
  8784. astman_send_error(s, m, "Interface not found");
  8785. } else {
  8786. astman_send_ack(s, m, paused ? "Interface paused successfully" : "Interface unpaused successfully");
  8787. }
  8788. return 0;
  8789. }
  8790. static int manager_queue_log_custom(struct mansession *s, const struct message *m)
  8791. {
  8792. const char *queuename, *event, *message, *interface, *uniqueid;
  8793. queuename = astman_get_header(m, "Queue");
  8794. uniqueid = astman_get_header(m, "UniqueId");
  8795. interface = astman_get_header(m, "Interface");
  8796. event = astman_get_header(m, "Event");
  8797. message = astman_get_header(m, "Message");
  8798. if (ast_strlen_zero(queuename) || ast_strlen_zero(event)) {
  8799. astman_send_error(s, m, "Need 'Queue' and 'Event' parameters.");
  8800. return 0;
  8801. }
  8802. ast_queue_log(queuename, S_OR(uniqueid, "NONE"), interface, event, "%s", message);
  8803. astman_send_ack(s, m, "Event added successfully");
  8804. return 0;
  8805. }
  8806. static int manager_queue_reload(struct mansession *s, const struct message *m)
  8807. {
  8808. struct ast_flags mask = {0,};
  8809. const char *queuename = NULL;
  8810. int header_found = 0;
  8811. queuename = astman_get_header(m, "Queue");
  8812. if (!strcasecmp(S_OR(astman_get_header(m, "Members"), ""), "yes")) {
  8813. ast_set_flag(&mask, QUEUE_RELOAD_MEMBER);
  8814. header_found = 1;
  8815. }
  8816. if (!strcasecmp(S_OR(astman_get_header(m, "Rules"), ""), "yes")) {
  8817. ast_set_flag(&mask, QUEUE_RELOAD_RULES);
  8818. header_found = 1;
  8819. }
  8820. if (!strcasecmp(S_OR(astman_get_header(m, "Parameters"), ""), "yes")) {
  8821. ast_set_flag(&mask, QUEUE_RELOAD_PARAMETERS);
  8822. header_found = 1;
  8823. }
  8824. if (!header_found) {
  8825. ast_set_flag(&mask, AST_FLAGS_ALL);
  8826. }
  8827. if (!reload_handler(1, &mask, queuename)) {
  8828. astman_send_ack(s, m, "Queue reloaded successfully");
  8829. } else {
  8830. astman_send_error(s, m, "Error encountered while reloading queue");
  8831. }
  8832. return 0;
  8833. }
  8834. static int manager_queue_reset(struct mansession *s, const struct message *m)
  8835. {
  8836. const char *queuename = NULL;
  8837. struct ast_flags mask = {QUEUE_RESET_STATS,};
  8838. queuename = astman_get_header(m, "Queue");
  8839. if (!reload_handler(1, &mask, queuename)) {
  8840. astman_send_ack(s, m, "Queue stats reset successfully");
  8841. } else {
  8842. astman_send_error(s, m, "Error encountered while resetting queue stats");
  8843. }
  8844. return 0;
  8845. }
  8846. static char *complete_queue_add_member(const char *line, const char *word, int pos, int state)
  8847. {
  8848. /* 0 - queue; 1 - add; 2 - member; 3 - <interface>; 4 - to; 5 - <queue>; 6 - penalty; 7 - <penalty>; 8 - as; 9 - <membername> */
  8849. switch (pos) {
  8850. case 3: /* Don't attempt to complete name of interface (infinite possibilities) */
  8851. return NULL;
  8852. case 4: /* only one possible match, "to" */
  8853. return state == 0 ? ast_strdup("to") : NULL;
  8854. case 5: /* <queue> */
  8855. return complete_queue(line, word, pos, state, 0);
  8856. case 6: /* only one possible match, "penalty" */
  8857. return state == 0 ? ast_strdup("penalty") : NULL;
  8858. case 7:
  8859. if (state < 100) { /* 0-99 */
  8860. char *num;
  8861. if ((num = ast_malloc(3))) {
  8862. sprintf(num, "%d", state);
  8863. }
  8864. return num;
  8865. } else {
  8866. return NULL;
  8867. }
  8868. case 8: /* only one possible match, "as" */
  8869. return state == 0 ? ast_strdup("as") : NULL;
  8870. case 9: /* Don't attempt to complete name of member (infinite possibilities) */
  8871. return NULL;
  8872. default:
  8873. return NULL;
  8874. }
  8875. }
  8876. static int manager_queue_member_ringinuse(struct mansession *s, const struct message *m)
  8877. {
  8878. const char *queuename, *interface, *ringinuse_s;
  8879. int ringinuse;
  8880. interface = astman_get_header(m, "Interface");
  8881. ringinuse_s = astman_get_header(m, "RingInUse");
  8882. /* Optional - if not supplied, set the ringinuse value for the given Interface in all queues */
  8883. queuename = astman_get_header(m, "Queue");
  8884. if (ast_strlen_zero(interface) || ast_strlen_zero(ringinuse_s)) {
  8885. astman_send_error(s, m, "Need 'Interface' and 'RingInUse' parameters.");
  8886. return 0;
  8887. }
  8888. if (ast_true(ringinuse_s)) {
  8889. ringinuse = 1;
  8890. } else if (ast_false(ringinuse_s)) {
  8891. ringinuse = 0;
  8892. } else {
  8893. astman_send_error(s, m, "'RingInUse' parameter must be a truth value (yes/no, on/off, 0/1, etc)");
  8894. return 0;
  8895. }
  8896. if (set_member_value(queuename, interface, MEMBER_RINGINUSE, ringinuse)) {
  8897. astman_send_error(s, m, "Invalid interface, queuename, or ringinuse value\n");
  8898. } else {
  8899. astman_send_ack(s, m, "Interface ringinuse set successfully");
  8900. }
  8901. return 0;
  8902. }
  8903. static int manager_queue_member_penalty(struct mansession *s, const struct message *m)
  8904. {
  8905. const char *queuename, *interface, *penalty_s;
  8906. int penalty;
  8907. interface = astman_get_header(m, "Interface");
  8908. penalty_s = astman_get_header(m, "Penalty");
  8909. /* Optional - if not supplied, set the penalty value for the given Interface in all queues */
  8910. queuename = astman_get_header(m, "Queue");
  8911. if (ast_strlen_zero(interface) || ast_strlen_zero(penalty_s)) {
  8912. astman_send_error(s, m, "Need 'Interface' and 'Penalty' parameters.");
  8913. return 0;
  8914. }
  8915. penalty = atoi(penalty_s);
  8916. if (set_member_value((char *)queuename, (char *)interface, MEMBER_PENALTY, penalty)) {
  8917. astman_send_error(s, m, "Invalid interface, queuename or penalty");
  8918. } else {
  8919. astman_send_ack(s, m, "Interface penalty set successfully");
  8920. }
  8921. return 0;
  8922. }
  8923. static char *handle_queue_add_member(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  8924. {
  8925. const char *queuename, *interface, *membername = NULL, *state_interface = NULL;
  8926. int penalty;
  8927. switch ( cmd ) {
  8928. case CLI_INIT:
  8929. e->command = "queue add member";
  8930. e->usage =
  8931. "Usage: queue add member <dial string> to <queue> [[[penalty <penalty>] as <membername>] state_interface <interface>]\n"
  8932. " Add a dial string (Such as a channel,e.g. SIP/6001) to a queue with optionally: a penalty, membername and a state_interface\n";
  8933. return NULL;
  8934. case CLI_GENERATE:
  8935. return complete_queue_add_member(a->line, a->word, a->pos, a->n);
  8936. }
  8937. if ((a->argc != 6) && (a->argc != 8) && (a->argc != 10) && (a->argc != 12)) {
  8938. return CLI_SHOWUSAGE;
  8939. } else if (strcmp(a->argv[4], "to")) {
  8940. return CLI_SHOWUSAGE;
  8941. } else if ((a->argc >= 8) && strcmp(a->argv[6], "penalty")) {
  8942. return CLI_SHOWUSAGE;
  8943. } else if ((a->argc >= 10) && strcmp(a->argv[8], "as")) {
  8944. return CLI_SHOWUSAGE;
  8945. } else if ((a->argc == 12) && strcmp(a->argv[10], "state_interface")) {
  8946. return CLI_SHOWUSAGE;
  8947. }
  8948. queuename = a->argv[5];
  8949. interface = a->argv[3];
  8950. if (a->argc >= 8) {
  8951. if (sscanf(a->argv[7], "%30d", &penalty) == 1) {
  8952. if (penalty < 0) {
  8953. ast_cli(a->fd, "Penalty must be >= 0\n");
  8954. penalty = 0;
  8955. }
  8956. } else {
  8957. ast_cli(a->fd, "Penalty must be an integer >= 0\n");
  8958. penalty = 0;
  8959. }
  8960. } else {
  8961. penalty = 0;
  8962. }
  8963. if (a->argc >= 10) {
  8964. membername = a->argv[9];
  8965. }
  8966. if (a->argc >= 12) {
  8967. state_interface = a->argv[11];
  8968. }
  8969. switch (add_to_queue(queuename, interface, membername, penalty, 0, queue_persistent_members, state_interface)) {
  8970. case RES_OKAY:
  8971. if (ast_strlen_zero(membername) || !log_membername_as_agent) {
  8972. ast_queue_log(queuename, "CLI", interface, "ADDMEMBER", "%s", "");
  8973. } else {
  8974. ast_queue_log(queuename, "CLI", membername, "ADDMEMBER", "%s", "");
  8975. }
  8976. ast_cli(a->fd, "Added interface '%s' to queue '%s'\n", interface, queuename);
  8977. return CLI_SUCCESS;
  8978. case RES_EXISTS:
  8979. ast_cli(a->fd, "Unable to add interface '%s' to queue '%s': Already there\n", interface, queuename);
  8980. return CLI_FAILURE;
  8981. case RES_NOSUCHQUEUE:
  8982. ast_cli(a->fd, "Unable to add interface to queue '%s': No such queue\n", queuename);
  8983. return CLI_FAILURE;
  8984. case RES_OUTOFMEMORY:
  8985. ast_cli(a->fd, "Out of memory\n");
  8986. return CLI_FAILURE;
  8987. case RES_NOT_DYNAMIC:
  8988. ast_cli(a->fd, "Member not dynamic\n");
  8989. return CLI_FAILURE;
  8990. default:
  8991. return CLI_FAILURE;
  8992. }
  8993. }
  8994. static char *complete_queue_remove_member(const char *line, const char *word, int pos, int state)
  8995. {
  8996. int which = 0;
  8997. struct call_queue *q;
  8998. struct member *m;
  8999. struct ao2_iterator queue_iter;
  9000. struct ao2_iterator mem_iter;
  9001. int wordlen = strlen(word);
  9002. /* 0 - queue; 1 - remove; 2 - member; 3 - <member>; 4 - from; 5 - <queue> */
  9003. if (pos > 5 || pos < 3) {
  9004. return NULL;
  9005. }
  9006. if (pos == 4) { /* only one possible match, 'from' */
  9007. return (state == 0 ? ast_strdup("from") : NULL);
  9008. }
  9009. if (pos == 5) { /* No need to duplicate code */
  9010. return complete_queue(line, word, pos, state, 0);
  9011. }
  9012. /* here is the case for 3, <member> */
  9013. queue_iter = ao2_iterator_init(queues, 0);
  9014. while ((q = ao2_t_iterator_next(&queue_iter, "Iterate through queues"))) {
  9015. ao2_lock(q);
  9016. mem_iter = ao2_iterator_init(q->members, 0);
  9017. while ((m = ao2_iterator_next(&mem_iter))) {
  9018. if (!strncasecmp(word, m->membername, wordlen) && ++which > state) {
  9019. char *tmp;
  9020. tmp = ast_strdup(m->interface);
  9021. ao2_ref(m, -1);
  9022. ao2_iterator_destroy(&mem_iter);
  9023. ao2_unlock(q);
  9024. queue_t_unref(q, "Done with iterator, returning interface name");
  9025. ao2_iterator_destroy(&queue_iter);
  9026. return tmp;
  9027. }
  9028. ao2_ref(m, -1);
  9029. }
  9030. ao2_iterator_destroy(&mem_iter);
  9031. ao2_unlock(q);
  9032. queue_t_unref(q, "Done with iterator");
  9033. }
  9034. ao2_iterator_destroy(&queue_iter);
  9035. return NULL;
  9036. }
  9037. static char *handle_queue_remove_member(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  9038. {
  9039. const char *queuename, *interface;
  9040. struct member *mem = NULL;
  9041. char *res = CLI_FAILURE;
  9042. switch (cmd) {
  9043. case CLI_INIT:
  9044. e->command = "queue remove member";
  9045. e->usage =
  9046. "Usage: queue remove member <channel> from <queue>\n"
  9047. " Remove a specific channel from a queue.\n";
  9048. return NULL;
  9049. case CLI_GENERATE:
  9050. return complete_queue_remove_member(a->line, a->word, a->pos, a->n);
  9051. }
  9052. if (a->argc != 6) {
  9053. return CLI_SHOWUSAGE;
  9054. } else if (strcmp(a->argv[4], "from")) {
  9055. return CLI_SHOWUSAGE;
  9056. }
  9057. queuename = a->argv[5];
  9058. interface = a->argv[3];
  9059. if (log_membername_as_agent) {
  9060. mem = find_member_by_queuename_and_interface(queuename, interface);
  9061. }
  9062. switch (remove_from_queue(queuename, interface)) {
  9063. case RES_OKAY:
  9064. if (!mem || ast_strlen_zero(mem->membername)) {
  9065. ast_queue_log(queuename, "CLI", interface, "REMOVEMEMBER", "%s", "");
  9066. } else {
  9067. ast_queue_log(queuename, "CLI", mem->membername, "REMOVEMEMBER", "%s", "");
  9068. }
  9069. ast_cli(a->fd, "Removed interface %s from queue '%s'\n", interface, queuename);
  9070. res = CLI_SUCCESS;
  9071. break;
  9072. case RES_EXISTS:
  9073. ast_cli(a->fd, "Unable to remove interface '%s' from queue '%s': Not there\n", interface, queuename);
  9074. break;
  9075. case RES_NOSUCHQUEUE:
  9076. ast_cli(a->fd, "Unable to remove interface from queue '%s': No such queue\n", queuename);
  9077. break;
  9078. case RES_OUTOFMEMORY:
  9079. ast_cli(a->fd, "Out of memory\n");
  9080. break;
  9081. case RES_NOT_DYNAMIC:
  9082. ast_cli(a->fd, "Unable to remove interface '%s' from queue '%s': Member is not dynamic\n", interface, queuename);
  9083. break;
  9084. }
  9085. if (mem) {
  9086. ao2_ref(mem, -1);
  9087. }
  9088. return res;
  9089. }
  9090. static char *complete_queue_pause_member(const char *line, const char *word, int pos, int state)
  9091. {
  9092. /* 0 - queue; 1 - pause; 2 - member; 3 - <interface>; 4 - queue; 5 - <queue>; 6 - reason; 7 - <reason> */
  9093. switch (pos) {
  9094. case 3: /* Don't attempt to complete name of interface (infinite possibilities) */
  9095. return NULL;
  9096. case 4: /* only one possible match, "queue" */
  9097. return state == 0 ? ast_strdup("queue") : NULL;
  9098. case 5: /* <queue> */
  9099. return complete_queue(line, word, pos, state, 0);
  9100. case 6: /* "reason" */
  9101. return state == 0 ? ast_strdup("reason") : NULL;
  9102. case 7: /* Can't autocomplete a reason, since it's 100% customizeable */
  9103. return NULL;
  9104. default:
  9105. return NULL;
  9106. }
  9107. }
  9108. static char *handle_queue_pause_member(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  9109. {
  9110. const char *queuename, *interface, *reason;
  9111. int paused;
  9112. switch (cmd) {
  9113. case CLI_INIT:
  9114. e->command = "queue {pause|unpause} member";
  9115. e->usage =
  9116. "Usage: queue {pause|unpause} member <member> [queue <queue> [reason <reason>]]\n"
  9117. " Pause or unpause a queue member. Not specifying a particular queue\n"
  9118. " will pause or unpause a member across all queues to which the member\n"
  9119. " belongs.\n";
  9120. return NULL;
  9121. case CLI_GENERATE:
  9122. return complete_queue_pause_member(a->line, a-> word, a->pos, a->n);
  9123. }
  9124. if (a->argc < 4 || a->argc == 5 || a->argc == 7 || a->argc > 8) {
  9125. return CLI_SHOWUSAGE;
  9126. } else if (a->argc >= 5 && strcmp(a->argv[4], "queue")) {
  9127. return CLI_SHOWUSAGE;
  9128. } else if (a->argc == 8 && strcmp(a->argv[6], "reason")) {
  9129. return CLI_SHOWUSAGE;
  9130. }
  9131. interface = a->argv[3];
  9132. queuename = a->argc >= 6 ? a->argv[5] : NULL;
  9133. reason = a->argc == 8 ? a->argv[7] : NULL;
  9134. paused = !strcasecmp(a->argv[1], "pause");
  9135. if (set_member_paused(queuename, interface, reason, paused) == RESULT_SUCCESS) {
  9136. ast_cli(a->fd, "%spaused interface '%s'", paused ? "" : "un", interface);
  9137. if (!ast_strlen_zero(queuename)) {
  9138. ast_cli(a->fd, " in queue '%s'", queuename);
  9139. }
  9140. if (!ast_strlen_zero(reason)) {
  9141. ast_cli(a->fd, " for reason '%s'", reason);
  9142. }
  9143. ast_cli(a->fd, "\n");
  9144. return CLI_SUCCESS;
  9145. } else {
  9146. ast_cli(a->fd, "Unable to %spause interface '%s'", paused ? "" : "un", interface);
  9147. if (!ast_strlen_zero(queuename)) {
  9148. ast_cli(a->fd, " in queue '%s'", queuename);
  9149. }
  9150. if (!ast_strlen_zero(reason)) {
  9151. ast_cli(a->fd, " for reason '%s'", reason);
  9152. }
  9153. ast_cli(a->fd, "\n");
  9154. return CLI_FAILURE;
  9155. }
  9156. }
  9157. static char *complete_queue_set_member_value(const char *line, const char *word, int pos, int state)
  9158. {
  9159. /* 0 - queue; 1 - set; 2 - penalty/ringinuse; 3 - <value>; 4 - on; 5 - <member>; 6 - in; 7 - <queue>;*/
  9160. switch (pos) {
  9161. case 4:
  9162. if (state == 0) {
  9163. return ast_strdup("on");
  9164. } else {
  9165. return NULL;
  9166. }
  9167. case 6:
  9168. if (state == 0) {
  9169. return ast_strdup("in");
  9170. } else {
  9171. return NULL;
  9172. }
  9173. case 7:
  9174. return complete_queue(line, word, pos, state, 0);
  9175. default:
  9176. return NULL;
  9177. }
  9178. }
  9179. static char *handle_queue_set_member_ringinuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  9180. {
  9181. const char *queuename = NULL, *interface;
  9182. int ringinuse;
  9183. switch (cmd) {
  9184. case CLI_INIT:
  9185. e->command = "queue set ringinuse";
  9186. e->usage =
  9187. "Usage: queue set ringinuse <yes/no> on <interface> [in <queue>]\n"
  9188. " Set a member's ringinuse in the queue specified. If no queue is specified\n"
  9189. " then that interface's penalty is set in all queues to which that interface is a member.\n";
  9190. break;
  9191. return NULL;
  9192. case CLI_GENERATE:
  9193. return complete_queue_set_member_value(a->line, a->word, a->pos, a->n);
  9194. }
  9195. /* Sensible argument counts */
  9196. if (a->argc != 6 && a->argc != 8) {
  9197. return CLI_SHOWUSAGE;
  9198. }
  9199. /* Uses proper indicational words */
  9200. if (strcmp(a->argv[4], "on") || (a->argc > 6 && strcmp(a->argv[6], "in"))) {
  9201. return CLI_SHOWUSAGE;
  9202. }
  9203. /* Set the queue name if applicale */
  9204. if (a->argc == 8) {
  9205. queuename = a->argv[7];
  9206. }
  9207. /* Interface being set */
  9208. interface = a->argv[5];
  9209. /* Check and set the ringinuse value */
  9210. if (ast_true(a->argv[3])) {
  9211. ringinuse = 1;
  9212. } else if (ast_false(a->argv[3])) {
  9213. ringinuse = 0;
  9214. } else {
  9215. return CLI_SHOWUSAGE;
  9216. }
  9217. switch (set_member_value(queuename, interface, MEMBER_RINGINUSE, ringinuse)) {
  9218. case RESULT_SUCCESS:
  9219. ast_cli(a->fd, "Set ringinuse on interface '%s' from queue '%s'\n", interface, queuename);
  9220. return CLI_SUCCESS;
  9221. case RESULT_FAILURE:
  9222. ast_cli(a->fd, "Failed to set ringinuse on interface '%s' from queue '%s'\n", interface, queuename);
  9223. return CLI_FAILURE;
  9224. default:
  9225. return CLI_FAILURE;
  9226. }
  9227. }
  9228. static char *handle_queue_set_member_penalty(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  9229. {
  9230. const char *queuename = NULL, *interface;
  9231. int penalty = 0;
  9232. switch (cmd) {
  9233. case CLI_INIT:
  9234. e->command = "queue set penalty";
  9235. e->usage =
  9236. "Usage: queue set penalty <penalty> on <interface> [in <queue>]\n"
  9237. " Set a member's penalty in the queue specified. If no queue is specified\n"
  9238. " then that interface's penalty is set in all queues to which that interface is a member\n";
  9239. return NULL;
  9240. case CLI_GENERATE:
  9241. return complete_queue_set_member_value(a->line, a->word, a->pos, a->n);
  9242. }
  9243. if (a->argc != 6 && a->argc != 8) {
  9244. return CLI_SHOWUSAGE;
  9245. } else if (strcmp(a->argv[4], "on") || (a->argc > 6 && strcmp(a->argv[6], "in"))) {
  9246. return CLI_SHOWUSAGE;
  9247. }
  9248. if (a->argc == 8) {
  9249. queuename = a->argv[7];
  9250. }
  9251. interface = a->argv[5];
  9252. penalty = atoi(a->argv[3]);
  9253. switch (set_member_value(queuename, interface, MEMBER_PENALTY, penalty)) {
  9254. case RESULT_SUCCESS:
  9255. ast_cli(a->fd, "Set penalty on interface '%s' from queue '%s'\n", interface, queuename);
  9256. return CLI_SUCCESS;
  9257. case RESULT_FAILURE:
  9258. ast_cli(a->fd, "Failed to set penalty on interface '%s' from queue '%s'\n", interface, queuename);
  9259. return CLI_FAILURE;
  9260. default:
  9261. return CLI_FAILURE;
  9262. }
  9263. }
  9264. static char *complete_queue_rule_show(const char *line, const char *word, int pos, int state)
  9265. {
  9266. int which = 0;
  9267. struct rule_list *rl_iter;
  9268. int wordlen = strlen(word);
  9269. char *ret = NULL;
  9270. if (pos != 3) /* Wha? */ {
  9271. return NULL;
  9272. }
  9273. AST_LIST_LOCK(&rule_lists);
  9274. AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
  9275. if (!strncasecmp(word, rl_iter->name, wordlen) && ++which > state) {
  9276. ret = ast_strdup(rl_iter->name);
  9277. break;
  9278. }
  9279. }
  9280. AST_LIST_UNLOCK(&rule_lists);
  9281. return ret;
  9282. }
  9283. static char *handle_queue_rule_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  9284. {
  9285. const char *rule;
  9286. struct rule_list *rl_iter;
  9287. struct penalty_rule *pr_iter;
  9288. switch (cmd) {
  9289. case CLI_INIT:
  9290. e->command = "queue show rules";
  9291. e->usage =
  9292. "Usage: queue show rules [rulename]\n"
  9293. " Show the list of rules associated with rulename. If no\n"
  9294. " rulename is specified, list all rules defined in queuerules.conf\n";
  9295. return NULL;
  9296. case CLI_GENERATE:
  9297. return complete_queue_rule_show(a->line, a->word, a->pos, a->n);
  9298. }
  9299. if (a->argc != 3 && a->argc != 4) {
  9300. return CLI_SHOWUSAGE;
  9301. }
  9302. rule = a->argc == 4 ? a->argv[3] : "";
  9303. AST_LIST_LOCK(&rule_lists);
  9304. AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
  9305. if (ast_strlen_zero(rule) || !strcasecmp(rl_iter->name, rule)) {
  9306. ast_cli(a->fd, "Rule: %s\n", rl_iter->name);
  9307. AST_LIST_TRAVERSE(&rl_iter->rules, pr_iter, list) {
  9308. ast_cli(a->fd, "\tAfter %d seconds, adjust QUEUE_MAX_PENALTY %s %d and adjust QUEUE_MIN_PENALTY %s %d\n", pr_iter->time, pr_iter->max_relative ? "by" : "to", pr_iter->max_value, pr_iter->min_relative ? "by" : "to", pr_iter->min_value);
  9309. }
  9310. }
  9311. }
  9312. AST_LIST_UNLOCK(&rule_lists);
  9313. return CLI_SUCCESS;
  9314. }
  9315. static char *handle_queue_reset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  9316. {
  9317. struct ast_flags mask = {QUEUE_RESET_STATS,};
  9318. int i;
  9319. switch (cmd) {
  9320. case CLI_INIT:
  9321. e->command = "queue reset stats";
  9322. e->usage =
  9323. "Usage: queue reset stats [<queuenames>]\n"
  9324. "\n"
  9325. "Issuing this command will reset statistics for\n"
  9326. "<queuenames>, or for all queues if no queue is\n"
  9327. "specified.\n";
  9328. return NULL;
  9329. case CLI_GENERATE:
  9330. if (a->pos >= 3) {
  9331. return complete_queue(a->line, a->word, a->pos, a->n, 17);
  9332. } else {
  9333. return NULL;
  9334. }
  9335. }
  9336. if (a->argc < 3) {
  9337. return CLI_SHOWUSAGE;
  9338. }
  9339. if (a->argc == 3) {
  9340. reload_handler(1, &mask, NULL);
  9341. return CLI_SUCCESS;
  9342. }
  9343. for (i = 3; i < a->argc; ++i) {
  9344. reload_handler(1, &mask, a->argv[i]);
  9345. }
  9346. return CLI_SUCCESS;
  9347. }
  9348. static char *handle_queue_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  9349. {
  9350. struct ast_flags mask = {0,};
  9351. int i;
  9352. switch (cmd) {
  9353. case CLI_INIT:
  9354. e->command = "queue reload {parameters|members|rules|all}";
  9355. e->usage =
  9356. "Usage: queue reload {parameters|members|rules|all} [<queuenames>]\n"
  9357. "Reload queues. If <queuenames> are specified, only reload information pertaining\n"
  9358. "to <queuenames>. One of 'parameters,' 'members,' 'rules,' or 'all' must be\n"
  9359. "specified in order to know what information to reload. Below is an explanation\n"
  9360. "of each of these qualifiers.\n"
  9361. "\n"
  9362. "\t'members' - reload queue members from queues.conf\n"
  9363. "\t'parameters' - reload all queue options except for queue members\n"
  9364. "\t'rules' - reload the queuerules.conf file\n"
  9365. "\t'all' - reload queue rules, parameters, and members\n"
  9366. "\n"
  9367. "Note: the 'rules' qualifier here cannot actually be applied to a specific queue.\n"
  9368. "Use of the 'rules' qualifier causes queuerules.conf to be reloaded. Even if only\n"
  9369. "one queue is specified when using this command, reloading queue rules may cause\n"
  9370. "other queues to be affected\n";
  9371. return NULL;
  9372. case CLI_GENERATE:
  9373. if (a->pos >= 3) {
  9374. /* find the point at which the list of queue names starts */
  9375. const char *command_end = a->line + strlen("queue reload ");
  9376. command_end = strchr(command_end, ' ');
  9377. if (!command_end) {
  9378. command_end = a->line + strlen(a->line);
  9379. }
  9380. return complete_queue(a->line, a->word, a->pos, a->n, command_end - a->line);
  9381. } else {
  9382. return NULL;
  9383. }
  9384. }
  9385. if (a->argc < 3)
  9386. return CLI_SHOWUSAGE;
  9387. if (!strcasecmp(a->argv[2], "rules")) {
  9388. ast_set_flag(&mask, QUEUE_RELOAD_RULES);
  9389. } else if (!strcasecmp(a->argv[2], "members")) {
  9390. ast_set_flag(&mask, QUEUE_RELOAD_MEMBER);
  9391. } else if (!strcasecmp(a->argv[2], "parameters")) {
  9392. ast_set_flag(&mask, QUEUE_RELOAD_PARAMETERS);
  9393. } else if (!strcasecmp(a->argv[2], "all")) {
  9394. ast_set_flag(&mask, AST_FLAGS_ALL);
  9395. }
  9396. if (a->argc == 3) {
  9397. reload_handler(1, &mask, NULL);
  9398. return CLI_SUCCESS;
  9399. }
  9400. for (i = 3; i < a->argc; ++i) {
  9401. reload_handler(1, &mask, a->argv[i]);
  9402. }
  9403. return CLI_SUCCESS;
  9404. }
  9405. static struct ast_cli_entry cli_queue[] = {
  9406. AST_CLI_DEFINE(queue_show, "Show status of a specified queue"),
  9407. AST_CLI_DEFINE(handle_queue_rule_show, "Show the rules defined in queuerules.conf"),
  9408. AST_CLI_DEFINE(handle_queue_add_member, "Add a channel to a specified queue"),
  9409. AST_CLI_DEFINE(handle_queue_remove_member, "Removes a channel from a specified queue"),
  9410. AST_CLI_DEFINE(handle_queue_pause_member, "Pause or unpause a queue member"),
  9411. AST_CLI_DEFINE(handle_queue_set_member_penalty, "Set penalty for a channel of a specified queue"),
  9412. AST_CLI_DEFINE(handle_queue_set_member_ringinuse, "Set ringinuse for a channel of a specified queue"),
  9413. AST_CLI_DEFINE(handle_queue_reload, "Reload queues, members, queue rules, or parameters"),
  9414. AST_CLI_DEFINE(handle_queue_reset, "Reset statistics for a queue"),
  9415. };
  9416. /* struct call_queue astdata mapping. */
  9417. #define DATA_EXPORT_CALL_QUEUE(MEMBER) \
  9418. MEMBER(call_queue, name, AST_DATA_STRING) \
  9419. MEMBER(call_queue, moh, AST_DATA_STRING) \
  9420. MEMBER(call_queue, announce, AST_DATA_STRING) \
  9421. MEMBER(call_queue, context, AST_DATA_STRING) \
  9422. MEMBER(call_queue, membermacro, AST_DATA_STRING) \
  9423. MEMBER(call_queue, membergosub, AST_DATA_STRING) \
  9424. MEMBER(call_queue, defaultrule, AST_DATA_STRING) \
  9425. MEMBER(call_queue, sound_next, AST_DATA_STRING) \
  9426. MEMBER(call_queue, sound_thereare, AST_DATA_STRING) \
  9427. MEMBER(call_queue, sound_calls, AST_DATA_STRING) \
  9428. MEMBER(call_queue, queue_quantity1, AST_DATA_STRING) \
  9429. MEMBER(call_queue, queue_quantity2, AST_DATA_STRING) \
  9430. MEMBER(call_queue, sound_holdtime, AST_DATA_STRING) \
  9431. MEMBER(call_queue, sound_minutes, AST_DATA_STRING) \
  9432. MEMBER(call_queue, sound_minute, AST_DATA_STRING) \
  9433. MEMBER(call_queue, sound_seconds, AST_DATA_STRING) \
  9434. MEMBER(call_queue, sound_thanks, AST_DATA_STRING) \
  9435. MEMBER(call_queue, sound_callerannounce, AST_DATA_STRING) \
  9436. MEMBER(call_queue, sound_reporthold, AST_DATA_STRING) \
  9437. MEMBER(call_queue, dead, AST_DATA_BOOLEAN) \
  9438. MEMBER(call_queue, ringinuse, AST_DATA_BOOLEAN) \
  9439. MEMBER(call_queue, announce_to_first_user, AST_DATA_BOOLEAN) \
  9440. MEMBER(call_queue, setinterfacevar, AST_DATA_BOOLEAN) \
  9441. MEMBER(call_queue, setqueuevar, AST_DATA_BOOLEAN) \
  9442. MEMBER(call_queue, setqueueentryvar, AST_DATA_BOOLEAN) \
  9443. MEMBER(call_queue, reportholdtime, AST_DATA_BOOLEAN) \
  9444. MEMBER(call_queue, wrapped, AST_DATA_BOOLEAN) \
  9445. MEMBER(call_queue, timeoutrestart, AST_DATA_BOOLEAN) \
  9446. MEMBER(call_queue, announceholdtime, AST_DATA_INTEGER) \
  9447. MEMBER(call_queue, realtime, AST_DATA_BOOLEAN) \
  9448. MEMBER(call_queue, found, AST_DATA_BOOLEAN) \
  9449. MEMBER(call_queue, announcepositionlimit, AST_DATA_INTEGER) \
  9450. MEMBER(call_queue, announcefrequency, AST_DATA_SECONDS) \
  9451. MEMBER(call_queue, minannouncefrequency, AST_DATA_SECONDS) \
  9452. MEMBER(call_queue, periodicannouncefrequency, AST_DATA_SECONDS) \
  9453. MEMBER(call_queue, numperiodicannounce, AST_DATA_INTEGER) \
  9454. MEMBER(call_queue, randomperiodicannounce, AST_DATA_INTEGER) \
  9455. MEMBER(call_queue, roundingseconds, AST_DATA_SECONDS) \
  9456. MEMBER(call_queue, holdtime, AST_DATA_SECONDS) \
  9457. MEMBER(call_queue, talktime, AST_DATA_SECONDS) \
  9458. MEMBER(call_queue, callscompleted, AST_DATA_INTEGER) \
  9459. MEMBER(call_queue, callsabandoned, AST_DATA_INTEGER) \
  9460. MEMBER(call_queue, servicelevel, AST_DATA_INTEGER) \
  9461. MEMBER(call_queue, callscompletedinsl, AST_DATA_INTEGER) \
  9462. MEMBER(call_queue, monfmt, AST_DATA_STRING) \
  9463. MEMBER(call_queue, montype, AST_DATA_INTEGER) \
  9464. MEMBER(call_queue, count, AST_DATA_INTEGER) \
  9465. MEMBER(call_queue, maxlen, AST_DATA_INTEGER) \
  9466. MEMBER(call_queue, wrapuptime, AST_DATA_SECONDS) \
  9467. MEMBER(call_queue, retry, AST_DATA_SECONDS) \
  9468. MEMBER(call_queue, timeout, AST_DATA_SECONDS) \
  9469. MEMBER(call_queue, weight, AST_DATA_INTEGER) \
  9470. MEMBER(call_queue, autopause, AST_DATA_INTEGER) \
  9471. MEMBER(call_queue, timeoutpriority, AST_DATA_INTEGER) \
  9472. MEMBER(call_queue, rrpos, AST_DATA_INTEGER) \
  9473. MEMBER(call_queue, memberdelay, AST_DATA_INTEGER) \
  9474. MEMBER(call_queue, autofill, AST_DATA_INTEGER) \
  9475. MEMBER(call_queue, members, AST_DATA_CONTAINER)
  9476. AST_DATA_STRUCTURE(call_queue, DATA_EXPORT_CALL_QUEUE);
  9477. /* struct member astdata mapping. */
  9478. #define DATA_EXPORT_MEMBER(MEMBER) \
  9479. MEMBER(member, interface, AST_DATA_STRING) \
  9480. MEMBER(member, state_interface, AST_DATA_STRING) \
  9481. MEMBER(member, membername, AST_DATA_STRING) \
  9482. MEMBER(member, penalty, AST_DATA_INTEGER) \
  9483. MEMBER(member, calls, AST_DATA_INTEGER) \
  9484. MEMBER(member, dynamic, AST_DATA_INTEGER) \
  9485. MEMBER(member, realtime, AST_DATA_INTEGER) \
  9486. MEMBER(member, status, AST_DATA_INTEGER) \
  9487. MEMBER(member, paused, AST_DATA_BOOLEAN) \
  9488. MEMBER(member, rt_uniqueid, AST_DATA_STRING)
  9489. AST_DATA_STRUCTURE(member, DATA_EXPORT_MEMBER);
  9490. #define DATA_EXPORT_QUEUE_ENT(MEMBER) \
  9491. MEMBER(queue_ent, moh, AST_DATA_STRING) \
  9492. MEMBER(queue_ent, announce, AST_DATA_STRING) \
  9493. MEMBER(queue_ent, context, AST_DATA_STRING) \
  9494. MEMBER(queue_ent, digits, AST_DATA_STRING) \
  9495. MEMBER(queue_ent, valid_digits, AST_DATA_INTEGER) \
  9496. MEMBER(queue_ent, pos, AST_DATA_INTEGER) \
  9497. MEMBER(queue_ent, prio, AST_DATA_INTEGER) \
  9498. MEMBER(queue_ent, last_pos_said, AST_DATA_INTEGER) \
  9499. MEMBER(queue_ent, last_periodic_announce_time, AST_DATA_INTEGER) \
  9500. MEMBER(queue_ent, last_periodic_announce_sound, AST_DATA_INTEGER) \
  9501. MEMBER(queue_ent, last_pos, AST_DATA_INTEGER) \
  9502. MEMBER(queue_ent, opos, AST_DATA_INTEGER) \
  9503. MEMBER(queue_ent, handled, AST_DATA_INTEGER) \
  9504. MEMBER(queue_ent, pending, AST_DATA_INTEGER) \
  9505. MEMBER(queue_ent, max_penalty, AST_DATA_INTEGER) \
  9506. MEMBER(queue_ent, min_penalty, AST_DATA_INTEGER) \
  9507. MEMBER(queue_ent, linpos, AST_DATA_INTEGER) \
  9508. MEMBER(queue_ent, linwrapped, AST_DATA_INTEGER) \
  9509. MEMBER(queue_ent, start, AST_DATA_INTEGER) \
  9510. MEMBER(queue_ent, expire, AST_DATA_INTEGER) \
  9511. MEMBER(queue_ent, cancel_answered_elsewhere, AST_DATA_INTEGER)
  9512. AST_DATA_STRUCTURE(queue_ent, DATA_EXPORT_QUEUE_ENT);
  9513. /*!
  9514. * \internal
  9515. * \brief Add a queue to the data_root node.
  9516. * \param[in] search The search tree.
  9517. * \param[in] data_root The main result node.
  9518. * \param[in] queue The queue to add.
  9519. */
  9520. static void queues_data_provider_get_helper(const struct ast_data_search *search,
  9521. struct ast_data *data_root, struct call_queue *queue)
  9522. {
  9523. struct ao2_iterator im;
  9524. struct member *member;
  9525. struct queue_ent *qe;
  9526. struct ast_data *data_queue, *data_members = NULL, *enum_node;
  9527. struct ast_data *data_member, *data_callers = NULL, *data_caller, *data_caller_channel;
  9528. data_queue = ast_data_add_node(data_root, "queue");
  9529. if (!data_queue) {
  9530. return;
  9531. }
  9532. ast_data_add_structure(call_queue, data_queue, queue);
  9533. ast_data_add_str(data_queue, "strategy", int2strat(queue->strategy));
  9534. ast_data_add_int(data_queue, "membercount", ao2_container_count(queue->members));
  9535. /* announce position */
  9536. enum_node = ast_data_add_node(data_queue, "announceposition");
  9537. if (!enum_node) {
  9538. return;
  9539. }
  9540. switch (queue->announceposition) {
  9541. case ANNOUNCEPOSITION_LIMIT:
  9542. ast_data_add_str(enum_node, "text", "limit");
  9543. break;
  9544. case ANNOUNCEPOSITION_MORE_THAN:
  9545. ast_data_add_str(enum_node, "text", "more");
  9546. break;
  9547. case ANNOUNCEPOSITION_YES:
  9548. ast_data_add_str(enum_node, "text", "yes");
  9549. break;
  9550. case ANNOUNCEPOSITION_NO:
  9551. ast_data_add_str(enum_node, "text", "no");
  9552. break;
  9553. default:
  9554. ast_data_add_str(enum_node, "text", "unknown");
  9555. break;
  9556. }
  9557. ast_data_add_int(enum_node, "value", queue->announceposition);
  9558. /* add queue members */
  9559. im = ao2_iterator_init(queue->members, 0);
  9560. while ((member = ao2_iterator_next(&im))) {
  9561. if (!data_members) {
  9562. data_members = ast_data_add_node(data_queue, "members");
  9563. if (!data_members) {
  9564. ao2_ref(member, -1);
  9565. continue;
  9566. }
  9567. }
  9568. data_member = ast_data_add_node(data_members, "member");
  9569. if (!data_member) {
  9570. ao2_ref(member, -1);
  9571. continue;
  9572. }
  9573. ast_data_add_structure(member, data_member, member);
  9574. ao2_ref(member, -1);
  9575. }
  9576. ao2_iterator_destroy(&im);
  9577. /* include the callers inside the result. */
  9578. if (queue->head) {
  9579. for (qe = queue->head; qe; qe = qe->next) {
  9580. if (!data_callers) {
  9581. data_callers = ast_data_add_node(data_queue, "callers");
  9582. if (!data_callers) {
  9583. continue;
  9584. }
  9585. }
  9586. data_caller = ast_data_add_node(data_callers, "caller");
  9587. if (!data_caller) {
  9588. continue;
  9589. }
  9590. ast_data_add_structure(queue_ent, data_caller, qe);
  9591. /* add the caller channel. */
  9592. data_caller_channel = ast_data_add_node(data_caller, "channel");
  9593. if (!data_caller_channel) {
  9594. continue;
  9595. }
  9596. ast_channel_data_add_structure(data_caller_channel, qe->chan, 1);
  9597. }
  9598. }
  9599. /* if this queue doesn't match remove the added queue. */
  9600. if (!ast_data_search_match(search, data_queue)) {
  9601. ast_data_remove_node(data_root, data_queue);
  9602. }
  9603. }
  9604. /*!
  9605. * \internal
  9606. * \brief Callback used to generate the queues tree.
  9607. * \param[in] search The search pattern tree.
  9608. * \retval NULL on error.
  9609. * \retval non-NULL The generated tree.
  9610. */
  9611. static int queues_data_provider_get(const struct ast_data_search *search,
  9612. struct ast_data *data_root)
  9613. {
  9614. struct ao2_iterator i;
  9615. struct call_queue *queue, *queue_realtime = NULL;
  9616. struct ast_config *cfg;
  9617. char *queuename;
  9618. /* load realtime queues. */
  9619. cfg = ast_load_realtime_multientry("queues", "name LIKE", "%", SENTINEL);
  9620. if (cfg) {
  9621. for (queuename = ast_category_browse(cfg, NULL);
  9622. !ast_strlen_zero(queuename);
  9623. queuename = ast_category_browse(cfg, queuename)) {
  9624. if ((queue = find_load_queue_rt_friendly(queuename))) {
  9625. queue_unref(queue);
  9626. }
  9627. }
  9628. ast_config_destroy(cfg);
  9629. }
  9630. /* static queues. */
  9631. i = ao2_iterator_init(queues, 0);
  9632. while ((queue = ao2_iterator_next(&i))) {
  9633. ao2_lock(queue);
  9634. if (queue->realtime) {
  9635. queue_realtime = find_load_queue_rt_friendly(queue->name);
  9636. if (!queue_realtime) {
  9637. ao2_unlock(queue);
  9638. queue_unref(queue);
  9639. continue;
  9640. }
  9641. queue_unref(queue_realtime);
  9642. }
  9643. queues_data_provider_get_helper(search, data_root, queue);
  9644. ao2_unlock(queue);
  9645. queue_unref(queue);
  9646. }
  9647. ao2_iterator_destroy(&i);
  9648. return 0;
  9649. }
  9650. static const struct ast_data_handler queues_data_provider = {
  9651. .version = AST_DATA_HANDLER_VERSION,
  9652. .get = queues_data_provider_get
  9653. };
  9654. static const struct ast_data_entry queue_data_providers[] = {
  9655. AST_DATA_ENTRY("asterisk/application/queue/list", &queues_data_provider),
  9656. };
  9657. static struct stasis_message_router *agent_router;
  9658. static struct stasis_forward *topic_forwarder;
  9659. static int unload_module(void)
  9660. {
  9661. stasis_message_router_unsubscribe_and_join(agent_router);
  9662. agent_router = NULL;
  9663. topic_forwarder = stasis_forward_cancel(topic_forwarder);
  9664. STASIS_MESSAGE_TYPE_CLEANUP(queue_caller_join_type);
  9665. STASIS_MESSAGE_TYPE_CLEANUP(queue_caller_leave_type);
  9666. STASIS_MESSAGE_TYPE_CLEANUP(queue_caller_abandon_type);
  9667. STASIS_MESSAGE_TYPE_CLEANUP(queue_member_status_type);
  9668. STASIS_MESSAGE_TYPE_CLEANUP(queue_member_added_type);
  9669. STASIS_MESSAGE_TYPE_CLEANUP(queue_member_removed_type);
  9670. STASIS_MESSAGE_TYPE_CLEANUP(queue_member_pause_type);
  9671. STASIS_MESSAGE_TYPE_CLEANUP(queue_member_penalty_type);
  9672. STASIS_MESSAGE_TYPE_CLEANUP(queue_member_ringinuse_type);
  9673. STASIS_MESSAGE_TYPE_CLEANUP(queue_agent_called_type);
  9674. STASIS_MESSAGE_TYPE_CLEANUP(queue_agent_connect_type);
  9675. STASIS_MESSAGE_TYPE_CLEANUP(queue_agent_complete_type);
  9676. STASIS_MESSAGE_TYPE_CLEANUP(queue_agent_dump_type);
  9677. STASIS_MESSAGE_TYPE_CLEANUP(queue_agent_ringnoanswer_type);
  9678. ast_cli_unregister_multiple(cli_queue, ARRAY_LEN(cli_queue));
  9679. ast_manager_unregister("QueueStatus");
  9680. ast_manager_unregister("Queues");
  9681. ast_manager_unregister("QueueRule");
  9682. ast_manager_unregister("QueueSummary");
  9683. ast_manager_unregister("QueueAdd");
  9684. ast_manager_unregister("QueueRemove");
  9685. ast_manager_unregister("QueuePause");
  9686. ast_manager_unregister("QueueLog");
  9687. ast_manager_unregister("QueuePenalty");
  9688. ast_manager_unregister("QueueReload");
  9689. ast_manager_unregister("QueueReset");
  9690. ast_manager_unregister("QueueMemberRingInUse");
  9691. ast_unregister_application(app_aqm);
  9692. ast_unregister_application(app_rqm);
  9693. ast_unregister_application(app_pqm);
  9694. ast_unregister_application(app_upqm);
  9695. ast_unregister_application(app_ql);
  9696. ast_unregister_application(app);
  9697. ast_custom_function_unregister(&queueexists_function);
  9698. ast_custom_function_unregister(&queuevar_function);
  9699. ast_custom_function_unregister(&queuemembercount_function);
  9700. ast_custom_function_unregister(&queuemembercount_dep);
  9701. ast_custom_function_unregister(&queuememberlist_function);
  9702. ast_custom_function_unregister(&queuegetchannel_function);
  9703. ast_custom_function_unregister(&queuewaitingcount_function);
  9704. ast_custom_function_unregister(&queuememberpenalty_function);
  9705. ast_data_unregister(NULL);
  9706. device_state_sub = stasis_unsubscribe_and_join(device_state_sub);
  9707. ast_extension_state_del(0, extension_state_cb);
  9708. ast_unload_realtime("queue_members");
  9709. ao2_cleanup(queues);
  9710. queues = NULL;
  9711. return 0;
  9712. }
  9713. /*!
  9714. * \brief Load the module
  9715. *
  9716. * Module loading including tests for configuration or dependencies.
  9717. * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
  9718. * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
  9719. * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
  9720. * configuration file or other non-critical problem return
  9721. * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
  9722. */
  9723. static int load_module(void)
  9724. {
  9725. int err = 0;
  9726. struct ast_flags mask = {AST_FLAGS_ALL, };
  9727. struct ast_config *member_config;
  9728. struct stasis_topic *queue_topic;
  9729. struct stasis_topic *manager_topic;
  9730. queues = ao2_container_alloc(MAX_QUEUE_BUCKETS, queue_hash_cb, queue_cmp_cb);
  9731. if (!queues) {
  9732. return AST_MODULE_LOAD_DECLINE;
  9733. }
  9734. use_weight = 0;
  9735. if (reload_handler(0, &mask, NULL)) {
  9736. unload_module();
  9737. return AST_MODULE_LOAD_DECLINE;
  9738. }
  9739. ast_realtime_require_field("queue_members", "paused", RQ_INTEGER1, 1, "uniqueid", RQ_UINTEGER2, 5, SENTINEL);
  9740. /*
  9741. * This section is used to determine which name for 'ringinuse' to use in realtime members
  9742. * Necessary for supporting older setups.
  9743. */
  9744. member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name LIKE", "%", SENTINEL);
  9745. if (!member_config) {
  9746. realtime_ringinuse_field = "ringinuse";
  9747. } else {
  9748. const char *config_val;
  9749. if ((config_val = ast_variable_retrieve(member_config, NULL, "ringinuse"))) {
  9750. ast_log(LOG_NOTICE, "ringinuse field entries found in queue_members table. Using 'ringinuse'\n");
  9751. realtime_ringinuse_field = "ringinuse";
  9752. } else if ((config_val = ast_variable_retrieve(member_config, NULL, "ignorebusy"))) {
  9753. ast_log(LOG_NOTICE, "ignorebusy field found in queue_members table with no ringinuse field. Using 'ignorebusy'\n");
  9754. realtime_ringinuse_field = "ignorebusy";
  9755. } else {
  9756. ast_log(LOG_NOTICE, "No entries were found for ringinuse/ignorebusy in queue_members table. Using 'ringinuse'\n");
  9757. realtime_ringinuse_field = "ringinuse";
  9758. }
  9759. }
  9760. ast_config_destroy(member_config);
  9761. if (queue_persistent_members) {
  9762. reload_queue_members();
  9763. }
  9764. ast_data_register_multiple(queue_data_providers, ARRAY_LEN(queue_data_providers));
  9765. err |= ast_cli_register_multiple(cli_queue, ARRAY_LEN(cli_queue));
  9766. err |= ast_register_application_xml(app, queue_exec);
  9767. err |= ast_register_application_xml(app_aqm, aqm_exec);
  9768. err |= ast_register_application_xml(app_rqm, rqm_exec);
  9769. err |= ast_register_application_xml(app_pqm, pqm_exec);
  9770. err |= ast_register_application_xml(app_upqm, upqm_exec);
  9771. err |= ast_register_application_xml(app_ql, ql_exec);
  9772. err |= ast_manager_register_xml("Queues", 0, manager_queues_show);
  9773. err |= ast_manager_register_xml("QueueStatus", 0, manager_queues_status);
  9774. err |= ast_manager_register_xml("QueueSummary", 0, manager_queues_summary);
  9775. err |= ast_manager_register_xml("QueueAdd", EVENT_FLAG_AGENT, manager_add_queue_member);
  9776. err |= ast_manager_register_xml("QueueRemove", EVENT_FLAG_AGENT, manager_remove_queue_member);
  9777. err |= ast_manager_register_xml("QueuePause", EVENT_FLAG_AGENT, manager_pause_queue_member);
  9778. err |= ast_manager_register_xml("QueueLog", EVENT_FLAG_AGENT, manager_queue_log_custom);
  9779. err |= ast_manager_register_xml("QueuePenalty", EVENT_FLAG_AGENT, manager_queue_member_penalty);
  9780. err |= ast_manager_register_xml("QueueMemberRingInUse", EVENT_FLAG_AGENT, manager_queue_member_ringinuse);
  9781. err |= ast_manager_register_xml("QueueRule", 0, manager_queue_rule_show);
  9782. err |= ast_manager_register_xml("QueueReload", 0, manager_queue_reload);
  9783. err |= ast_manager_register_xml("QueueReset", 0, manager_queue_reset);
  9784. err |= ast_custom_function_register(&queuevar_function);
  9785. err |= ast_custom_function_register(&queueexists_function);
  9786. err |= ast_custom_function_register(&queuemembercount_function);
  9787. err |= ast_custom_function_register(&queuemembercount_dep);
  9788. err |= ast_custom_function_register(&queuememberlist_function);
  9789. err |= ast_custom_function_register(&queuegetchannel_function);
  9790. err |= ast_custom_function_register(&queuewaitingcount_function);
  9791. err |= ast_custom_function_register(&queuememberpenalty_function);
  9792. /* in the following subscribe call, do I use DEVICE_STATE, or DEVICE_STATE_CHANGE? */
  9793. device_state_sub = stasis_subscribe(ast_device_state_topic_all(), device_state_cb, NULL);
  9794. if (!device_state_sub) {
  9795. err = -1;
  9796. }
  9797. manager_topic = ast_manager_get_topic();
  9798. queue_topic = ast_queue_topic_all();
  9799. if (!manager_topic || !queue_topic) {
  9800. unload_module();
  9801. return AST_MODULE_LOAD_DECLINE;
  9802. }
  9803. topic_forwarder = stasis_forward_all(queue_topic, manager_topic);
  9804. if (!topic_forwarder) {
  9805. unload_module();
  9806. return AST_MODULE_LOAD_DECLINE;
  9807. }
  9808. if (!ast_channel_agent_login_type()
  9809. || !ast_channel_agent_logoff_type()) {
  9810. unload_module();
  9811. return AST_MODULE_LOAD_DECLINE;
  9812. }
  9813. agent_router = stasis_message_router_create(ast_channel_topic_all());
  9814. if (!agent_router) {
  9815. unload_module();
  9816. return AST_MODULE_LOAD_DECLINE;
  9817. }
  9818. err |= stasis_message_router_add(agent_router,
  9819. ast_channel_agent_login_type(),
  9820. queue_agent_cb,
  9821. NULL);
  9822. err |= stasis_message_router_add(agent_router,
  9823. ast_channel_agent_logoff_type(),
  9824. queue_agent_cb,
  9825. NULL);
  9826. err |= STASIS_MESSAGE_TYPE_INIT(queue_caller_join_type);
  9827. err |= STASIS_MESSAGE_TYPE_INIT(queue_caller_leave_type);
  9828. err |= STASIS_MESSAGE_TYPE_INIT(queue_caller_abandon_type);
  9829. err |= STASIS_MESSAGE_TYPE_INIT(queue_member_status_type);
  9830. err |= STASIS_MESSAGE_TYPE_INIT(queue_member_added_type);
  9831. err |= STASIS_MESSAGE_TYPE_INIT(queue_member_removed_type);
  9832. err |= STASIS_MESSAGE_TYPE_INIT(queue_member_pause_type);
  9833. err |= STASIS_MESSAGE_TYPE_INIT(queue_member_penalty_type);
  9834. err |= STASIS_MESSAGE_TYPE_INIT(queue_member_ringinuse_type);
  9835. err |= STASIS_MESSAGE_TYPE_INIT(queue_agent_called_type);
  9836. err |= STASIS_MESSAGE_TYPE_INIT(queue_agent_connect_type);
  9837. err |= STASIS_MESSAGE_TYPE_INIT(queue_agent_complete_type);
  9838. err |= STASIS_MESSAGE_TYPE_INIT(queue_agent_dump_type);
  9839. err |= STASIS_MESSAGE_TYPE_INIT(queue_agent_ringnoanswer_type);
  9840. ast_extension_state_add(NULL, NULL, extension_state_cb, NULL);
  9841. if (err) {
  9842. unload_module();
  9843. return AST_MODULE_LOAD_DECLINE;
  9844. }
  9845. return AST_MODULE_LOAD_SUCCESS;
  9846. }
  9847. static int reload(void)
  9848. {
  9849. struct ast_flags mask = {AST_FLAGS_ALL & ~QUEUE_RESET_STATS,};
  9850. ast_unload_realtime("queue_members");
  9851. reload_handler(1, &mask, NULL);
  9852. return 0;
  9853. }
  9854. /* \brief Find a member by looking up queuename and interface.
  9855. * \return Returns a member or NULL if member not found.
  9856. */
  9857. static struct member *find_member_by_queuename_and_interface(const char *queuename, const char *interface)
  9858. {
  9859. struct member *mem = NULL;
  9860. struct call_queue *q;
  9861. if ((q = find_load_queue_rt_friendly(queuename))) {
  9862. ao2_lock(q);
  9863. mem = ao2_find(q->members, interface, OBJ_KEY);
  9864. ao2_unlock(q);
  9865. queue_t_unref(q, "Expiring temporary reference.");
  9866. }
  9867. return mem;
  9868. }
  9869. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "True Call Queueing",
  9870. .support_level = AST_MODULE_SUPPORT_CORE,
  9871. .load = load_module,
  9872. .unload = unload_module,
  9873. .reload = reload,
  9874. .load_pri = AST_MODPRI_DEVSTATE_CONSUMER,
  9875. .nonoptreq = "res_monitor",
  9876. );