app_queue: Deprecate the QueueMemberPause.Reason field
[asterisk/asterisk.git] / apps / app_queue.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2018, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief True call queues with optional send URL on answer
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \par Development notes
26  * \note 2004-11-25: Persistent Dynamic Members added by:
27  *             NetNation Communications (www.netnation.com)
28  *             Kevin Lindsay <kevinl@netnation.com>
29  *
30  *             Each dynamic agent in each queue is now stored in the astdb.
31  *             When asterisk is restarted, each agent will be automatically
32  *             readded into their recorded queues. This feature can be
33  *             configured with the 'persistent_members=<1|0>' setting in the
34  *             '[general]' category in queues.conf. The default is on.
35  *
36  * \note 2004-06-04: Priorities in queues added by inAccess Networks (work funded by Hellas On Line (HOL) www.hol.gr).
37  *
38  * \note These features added by David C. Troy <dave@toad.net>:
39  *    - Per-queue holdtime calculation
40  *    - Estimated holdtime announcement
41  *    - Position announcement
42  *    - Abandoned/completed call counters
43  *    - Failout timer passed as optional app parameter
44  *    - Optional monitoring of calls, started when call is answered
45  *
46  * Patch Version 1.07 2003-12-24 01
47  *
48  * Added servicelevel statistic by Michiel Betel <michiel@betel.nl>
49  * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <asterisk@doilooklikeicare.com>
50  *
51  * Fixed to work with CVS as of 2004-02-25 and released as 1.07a
52  * by Matthew Enger <m.enger@xi.com.au>
53  *
54  * \ingroup applications
55  */
56
57 /*! \li \ref app_queues.c uses configuration file \ref queues.conf
58  * \addtogroup configuration_file
59  */
60
61 /*! \page queues.conf queues.conf
62  * \verbinclude queues.conf.sample
63  */
64
65 /*** MODULEINFO
66         <use type="module">res_monitor</use>
67         <support_level>core</support_level>
68  ***/
69
70 #include "asterisk.h"
71
72 #include <sys/time.h>
73 #include <signal.h>
74 #include <netinet/in.h>
75 #include <ctype.h>
76
77 #include "asterisk/lock.h"
78 #include "asterisk/file.h"
79 #include "asterisk/channel.h"
80 #include "asterisk/pbx.h"
81 #include "asterisk/app.h"
82 #include "asterisk/linkedlists.h"
83 #include "asterisk/module.h"
84 #include "asterisk/translate.h"
85 #include "asterisk/say.h"
86 #include "asterisk/features.h"
87 #include "asterisk/musiconhold.h"
88 #include "asterisk/cli.h"
89 #include "asterisk/manager.h"
90 #include "asterisk/config.h"
91 #include "asterisk/monitor.h"
92 #include "asterisk/utils.h"
93 #include "asterisk/causes.h"
94 #include "asterisk/astdb.h"
95 #include "asterisk/devicestate.h"
96 #include "asterisk/stringfields.h"
97 #include "asterisk/astobj2.h"
98 #include "asterisk/strings.h"
99 #include "asterisk/taskprocessor.h"
100 #include "asterisk/aoc.h"
101 #include "asterisk/callerid.h"
102 #include "asterisk/term.h"
103 #include "asterisk/dial.h"
104 #include "asterisk/stasis_channels.h"
105 #include "asterisk/stasis_message_router.h"
106 #include "asterisk/bridge_after.h"
107 #include "asterisk/stasis_bridges.h"
108 #include "asterisk/core_local.h"
109 #include "asterisk/mixmonitor.h"
110 #include "asterisk/bridge_basic.h"
111 #include "asterisk/max_forwards.h"
112
113 /*!
114  * \par Please read before modifying this file.
115  * There are three locks which are regularly used
116  * throughout this file, the queue list lock, the lock
117  * for each individual queue, and the interface list lock.
118  * Please be extra careful to always lock in the following order
119  * 1) queue list lock
120  * 2) individual queue lock
121  * 3) interface list lock
122  * This order has sort of "evolved" over the lifetime of this
123  * application, but it is now in place this way, so please adhere
124  * to this order!
125  */
126
127 /*** DOCUMENTATION
128         <application name="Queue" language="en_US">
129                 <synopsis>
130                         Queue a call for a call queue.
131                 </synopsis>
132                 <syntax>
133                         <parameter name="queuename" required="true" />
134                         <parameter name="options">
135                                 <optionlist>
136                                         <option name="b" argsep="^">
137                                                 <para>Before initiating an outgoing call, <literal>Gosub</literal> to the specified
138                                                 location using the newly created channel.  The <literal>Gosub</literal> will be
139                                                 executed for each destination channel.</para>
140                                                 <argument name="context" required="false" />
141                                                 <argument name="exten" required="false" />
142                                                 <argument name="priority" required="true" hasparams="optional" argsep="^">
143                                                         <argument name="arg1" multiple="true" required="true" />
144                                                         <argument name="argN" />
145                                                 </argument>
146                                         </option>
147                                         <option name="B" argsep="^">
148                                                 <para>Before initiating the outgoing call(s), <literal>Gosub</literal> to the
149                                                 specified location using the current channel.</para>
150                                                 <argument name="context" required="false" />
151                                                 <argument name="exten" required="false" />
152                                                 <argument name="priority" required="true" hasparams="optional" argsep="^">
153                                                         <argument name="arg1" multiple="true" required="true" />
154                                                         <argument name="argN" />
155                                                 </argument>
156                                         </option>
157                                         <option name="C">
158                                                 <para>Mark all calls as "answered elsewhere" when cancelled.</para>
159                                         </option>
160                                         <option name="c">
161                                                 <para>Continue in the dialplan if the callee hangs up.</para>
162                                         </option>
163                                         <option name="d">
164                                                 <para>data-quality (modem) call (minimum delay).</para>
165                                         </option>
166                                         <option name="F" argsep="^">
167                                                 <argument name="context" required="false" />
168                                                 <argument name="exten" required="false" />
169                                                 <argument name="priority" required="true" />
170                                                 <para>When the caller hangs up, transfer the <emphasis>called member</emphasis>
171                                                 to the specified destination and <emphasis>start</emphasis> execution at that location.</para>
172                                                 <para>NOTE: Any channel variables you want the called channel to inherit from the caller channel must be
173                                                 prefixed with one or two underbars ('_').</para>
174                                         </option>
175                                         <option name="F">
176                                                 <para>When the caller hangs up, transfer the <emphasis>called member</emphasis> to the next priority of
177                                                 the current extension and <emphasis>start</emphasis> execution at that location.</para>
178                                                 <para>NOTE: Any channel variables you want the called channel to inherit from the caller channel must be
179                                                 prefixed with one or two underbars ('_').</para>
180                                                 <para>NOTE: Using this option from a Macro() or GoSub() might not make sense as there would be no return points.</para>
181                                         </option>
182                                         <option name="h">
183                                                 <para>Allow <emphasis>callee</emphasis> to hang up by pressing <literal>*</literal>.</para>
184                                         </option>
185                                         <option name="H">
186                                                 <para>Allow <emphasis>caller</emphasis> to hang up by pressing <literal>*</literal>.</para>
187                                         </option>
188                                         <option name="n">
189                                                 <para>No retries on the timeout; will exit this application and
190                                                 go to the next step.</para>
191                                         </option>
192                                         <option name="i">
193                                                 <para>Ignore call forward requests from queue members and do nothing
194                                                 when they are requested.</para>
195                                         </option>
196                                         <option name="I">
197                                                 <para>Asterisk will ignore any connected line update requests or any redirecting party
198                                                 update requests it may receive on this dial attempt.</para>
199                                         </option>
200                                         <option name="r">
201                                                 <para>Ring instead of playing MOH. Periodic Announcements are still made, if applicable.</para>
202                                         </option>
203                                         <option name="R">
204                                                 <para>Ring instead of playing MOH when a member channel is actually ringing.</para>
205                                         </option>
206                                         <option name="t">
207                                                 <para>Allow the <emphasis>called</emphasis> user to transfer the calling user.</para>
208                                         </option>
209                                         <option name="T">
210                                                 <para>Allow the <emphasis>calling</emphasis> user to transfer the call.</para>
211                                         </option>
212                                         <option name="w">
213                                                 <para>Allow the <emphasis>called</emphasis> user to write the conversation to
214                                                 disk via Monitor.</para>
215                                         </option>
216                                         <option name="W">
217                                                 <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
218                                                 disk via Monitor.</para>
219                                         </option>
220                                         <option name="k">
221                                                 <para>Allow the <emphasis>called</emphasis> party to enable parking of the call by sending
222                                                 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
223                                         </option>
224                                         <option name="K">
225                                                 <para>Allow the <emphasis>calling</emphasis> party to enable parking of the call by sending
226                                                 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
227                                         </option>
228                                         <option name="x">
229                                                 <para>Allow the <emphasis>called</emphasis> user to write the conversation
230                                                 to disk via MixMonitor.</para>
231                                         </option>
232                                         <option name="X">
233                                                 <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
234                                                 disk via MixMonitor.</para>
235                                         </option>
236                                 </optionlist>
237                         </parameter>
238                         <parameter name="URL">
239                                 <para><replaceable>URL</replaceable> will be sent to the called party if the channel supports it.</para>
240                         </parameter>
241                         <parameter name="announceoverride" />
242                         <parameter name="timeout">
243                                 <para>Will cause the queue to fail out after a specified number of
244                                 seconds, checked between each <filename>queues.conf</filename> <replaceable>timeout</replaceable> and
245                                 <replaceable>retry</replaceable> cycle.</para>
246                         </parameter>
247                         <parameter name="AGI">
248                                 <para>Will setup an AGI script to be executed on the calling party's channel once they are
249                                 connected to a queue member.</para>
250                         </parameter>
251                         <parameter name="macro">
252                                 <para>Will run a macro on the called party's channel (the queue member) once the parties are connected.</para>
253                                 <para>NOTE: Macros are deprecated, GoSub should be used instead.</para>
254                         </parameter>
255                         <parameter name="gosub">
256                                 <para>Will run a gosub on the called party's channel (the queue member)
257                                 once the parties are connected.  The subroutine execution starts in the
258                                 named context at the s exten and priority 1.</para>
259                         </parameter>
260                         <parameter name="rule">
261                                 <para>Will cause the queue's defaultrule to be overridden by the rule specified.</para>
262                         </parameter>
263                         <parameter name="position">
264                                 <para>Attempt to enter the caller into the queue at the numerical position specified. <literal>1</literal>
265                                 would attempt to enter the caller at the head of the queue, and <literal>3</literal> would attempt to place
266                                 the caller third in the queue.</para>
267                         </parameter>
268                 </syntax>
269                 <description>
270                         <para>In addition to transferring the call, a call may be parked and then picked
271                         up by another user.</para>
272                         <para>This application will return to the dialplan if the queue does not exist, or
273                         any of the join options cause the caller to not enter the queue.</para>
274                         <para>This application does not automatically answer and should be preceeded
275                         by an application such as Answer(), Progress(), or Ringing().</para>
276                         <para>This application sets the following channel variables upon completion:</para>
277                         <variablelist>
278                                 <variable name="QUEUESTATUS">
279                                         <para>The status of the call as a text string.</para>
280                                         <value name="TIMEOUT" />
281                                         <value name="FULL" />
282                                         <value name="JOINEMPTY" />
283                                         <value name="LEAVEEMPTY" />
284                                         <value name="JOINUNAVAIL" />
285                                         <value name="LEAVEUNAVAIL" />
286                                         <value name="CONTINUE" />
287                                 </variable>
288                                 <variable name="ABANDONED">
289                                         <para>If the call was not answered by an agent this variable will be TRUE.</para>
290                                         <value name="TRUE" />
291                                 </variable>
292                         </variablelist>
293                 </description>
294                 <see-also>
295                         <ref type="application">Queue</ref>
296                         <ref type="application">QueueLog</ref>
297                         <ref type="application">AddQueueMember</ref>
298                         <ref type="application">RemoveQueueMember</ref>
299                         <ref type="application">PauseQueueMember</ref>
300                         <ref type="application">UnpauseQueueMember</ref>
301                         <ref type="function">QUEUE_VARIABLES</ref>
302                         <ref type="function">QUEUE_MEMBER</ref>
303                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
304                         <ref type="function">QUEUE_EXISTS</ref>
305                         <ref type="function">QUEUE_GET_CHANNEL</ref>
306                         <ref type="function">QUEUE_WAITING_COUNT</ref>
307                         <ref type="function">QUEUE_MEMBER_LIST</ref>
308                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
309                 </see-also>
310         </application>
311         <application name="AddQueueMember" language="en_US">
312                 <synopsis>
313                         Dynamically adds queue members.
314                 </synopsis>
315                 <syntax>
316                         <parameter name="queuename" required="true" />
317                         <parameter name="interface" />
318                         <parameter name="penalty" />
319                         <parameter name="options" />
320                         <parameter name="membername" />
321                         <parameter name="stateinterface" />
322                         <parameter name="wrapuptime" />
323                 </syntax>
324                 <description>
325                         <para>Dynamically adds interface to an existing queue. If the interface is
326                         already in the queue it will return an error.</para>
327                         <para>This application sets the following channel variable upon completion:</para>
328                         <variablelist>
329                                 <variable name="AQMSTATUS">
330                                         <para>The status of the attempt to add a queue member as a text string.</para>
331                                         <value name="ADDED" />
332                                         <value name="MEMBERALREADY" />
333                                         <value name="NOSUCHQUEUE" />
334                                 </variable>
335                         </variablelist>
336                 </description>
337                 <see-also>
338                         <ref type="application">Queue</ref>
339                         <ref type="application">QueueLog</ref>
340                         <ref type="application">AddQueueMember</ref>
341                         <ref type="application">RemoveQueueMember</ref>
342                         <ref type="application">PauseQueueMember</ref>
343                         <ref type="application">UnpauseQueueMember</ref>
344                         <ref type="function">QUEUE_VARIABLES</ref>
345                         <ref type="function">QUEUE_MEMBER</ref>
346                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
347                         <ref type="function">QUEUE_EXISTS</ref>
348                         <ref type="function">QUEUE_GET_CHANNEL</ref>
349                         <ref type="function">QUEUE_WAITING_COUNT</ref>
350                         <ref type="function">QUEUE_MEMBER_LIST</ref>
351                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
352                 </see-also>
353         </application>
354         <application name="RemoveQueueMember" language="en_US">
355                 <synopsis>
356                         Dynamically removes queue members.
357                 </synopsis>
358                 <syntax>
359                         <parameter name="queuename" required="true" />
360                         <parameter name="interface" />
361                 </syntax>
362                 <description>
363                         <para>If the interface is <emphasis>NOT</emphasis> in the queue it will return an error.</para>
364                         <para>This application sets the following channel variable upon completion:</para>
365                         <variablelist>
366                                 <variable name="RQMSTATUS">
367                                         <value name="REMOVED" />
368                                         <value name="NOTINQUEUE" />
369                                         <value name="NOSUCHQUEUE" />
370                                         <value name="NOTDYNAMIC" />
371                                 </variable>
372                         </variablelist>
373                         <para>Example: RemoveQueueMember(techsupport,SIP/3000)</para>
374                 </description>
375                 <see-also>
376                         <ref type="application">Queue</ref>
377                         <ref type="application">QueueLog</ref>
378                         <ref type="application">AddQueueMember</ref>
379                         <ref type="application">RemoveQueueMember</ref>
380                         <ref type="application">PauseQueueMember</ref>
381                         <ref type="application">UnpauseQueueMember</ref>
382                         <ref type="function">QUEUE_VARIABLES</ref>
383                         <ref type="function">QUEUE_MEMBER</ref>
384                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
385                         <ref type="function">QUEUE_EXISTS</ref>
386                         <ref type="function">QUEUE_GET_CHANNEL</ref>
387                         <ref type="function">QUEUE_WAITING_COUNT</ref>
388                         <ref type="function">QUEUE_MEMBER_LIST</ref>
389                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
390                 </see-also>
391         </application>
392         <application name="PauseQueueMember" language="en_US">
393                 <synopsis>
394                         Pauses a queue member.
395                 </synopsis>
396                 <syntax>
397                         <parameter name="queuename" />
398                         <parameter name="interface" required="true" />
399                         <parameter name="options" />
400                         <parameter name="reason">
401                                 <para>Is used to add extra information to the appropriate queue_log entries and manager events.</para>
402                         </parameter>
403                 </syntax>
404                 <description>
405                         <para>Pauses (blocks calls for) a queue member. The given interface will be paused in the given queue.
406                         This prevents any calls from being sent from the queue to the interface until it is
407                         unpaused with UnpauseQueueMember or the manager interface.  If no queuename is given,
408                         the interface is paused in every queue it is a member of. The application will fail if the
409                         interface is not found.</para>
410                         <para>This application sets the following channel variable upon completion:</para>
411                         <variablelist>
412                                 <variable name="PQMSTATUS">
413                                         <para>The status of the attempt to pause a queue member as a text string.</para>
414                                         <value name="PAUSED" />
415                                         <value name="NOTFOUND" />
416                                 </variable>
417                         </variablelist>
418                         <para>Example: PauseQueueMember(,SIP/3000)</para>
419                 </description>
420                 <see-also>
421                         <ref type="application">Queue</ref>
422                         <ref type="application">QueueLog</ref>
423                         <ref type="application">AddQueueMember</ref>
424                         <ref type="application">RemoveQueueMember</ref>
425                         <ref type="application">PauseQueueMember</ref>
426                         <ref type="application">UnpauseQueueMember</ref>
427                         <ref type="function">QUEUE_VARIABLES</ref>
428                         <ref type="function">QUEUE_MEMBER</ref>
429                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
430                         <ref type="function">QUEUE_EXISTS</ref>
431                         <ref type="function">QUEUE_GET_CHANNEL</ref>
432                         <ref type="function">QUEUE_WAITING_COUNT</ref>
433                         <ref type="function">QUEUE_MEMBER_LIST</ref>
434                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
435                 </see-also>
436         </application>
437         <application name="UnpauseQueueMember" language="en_US">
438                 <synopsis>
439                         Unpauses a queue member.
440                 </synopsis>
441                 <syntax>
442                         <parameter name="queuename" />
443                         <parameter name="interface" required="true" />
444                         <parameter name="options" />
445                         <parameter name="reason">
446                                 <para>Is used to add extra information to the appropriate queue_log entries and manager events.</para>
447                         </parameter>
448                 </syntax>
449                 <description>
450                         <para>Unpauses (resumes calls to) a queue member. This is the counterpart to <literal>PauseQueueMember()</literal>
451                         and operates exactly the same way, except it unpauses instead of pausing the given interface.</para>
452                         <para>This application sets the following channel variable upon completion:</para>
453                         <variablelist>
454                                 <variable name="UPQMSTATUS">
455                                         <para>The status of the attempt to unpause a queue member as a text string.</para>
456                                         <value name="UNPAUSED" />
457                                         <value name="NOTFOUND" />
458                                 </variable>
459                         </variablelist>
460                         <para>Example: UnpauseQueueMember(,SIP/3000)</para>
461                 </description>
462                 <see-also>
463                         <ref type="application">Queue</ref>
464                         <ref type="application">QueueLog</ref>
465                         <ref type="application">AddQueueMember</ref>
466                         <ref type="application">RemoveQueueMember</ref>
467                         <ref type="application">PauseQueueMember</ref>
468                         <ref type="application">UnpauseQueueMember</ref>
469                         <ref type="function">QUEUE_VARIABLES</ref>
470                         <ref type="function">QUEUE_MEMBER</ref>
471                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
472                         <ref type="function">QUEUE_EXISTS</ref>
473                         <ref type="function">QUEUE_GET_CHANNEL</ref>
474                         <ref type="function">QUEUE_WAITING_COUNT</ref>
475                         <ref type="function">QUEUE_MEMBER_LIST</ref>
476                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
477                 </see-also>
478         </application>
479         <application name="QueueLog" language="en_US">
480                 <synopsis>
481                         Writes to the queue_log file.
482                 </synopsis>
483                 <syntax>
484                         <parameter name="queuename" required="true" />
485                         <parameter name="uniqueid" required="true" />
486                         <parameter name="agent" required="true" />
487                         <parameter name="event" required="true" />
488                         <parameter name="additionalinfo" />
489                 </syntax>
490                 <description>
491                         <para>Allows you to write your own events into the queue log.</para>
492                         <para>Example: QueueLog(101,${UNIQUEID},${AGENT},WENTONBREAK,600)</para>
493                 </description>
494                 <see-also>
495                         <ref type="application">Queue</ref>
496                         <ref type="application">QueueLog</ref>
497                         <ref type="application">AddQueueMember</ref>
498                         <ref type="application">RemoveQueueMember</ref>
499                         <ref type="application">PauseQueueMember</ref>
500                         <ref type="application">UnpauseQueueMember</ref>
501                         <ref type="function">QUEUE_VARIABLES</ref>
502                         <ref type="function">QUEUE_MEMBER</ref>
503                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
504                         <ref type="function">QUEUE_EXISTS</ref>
505                         <ref type="function">QUEUE_GET_CHANNEL</ref>
506                         <ref type="function">QUEUE_WAITING_COUNT</ref>
507                         <ref type="function">QUEUE_MEMBER_LIST</ref>
508                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
509                 </see-also>
510         </application>
511         <application name="QueueUpdate" language="en_US">
512                 <synopsis>
513                         Writes to the queue_log file for OutBound calls and updates Realtime Data.
514                         Is used at h extension to be able to have all the parameters.
515                 </synopsis>
516                 <syntax>
517                         <parameter name="queuename" required="true" />
518                         <parameter name="uniqueid" required="true" />
519                         <parameter name="agent" required="true" />
520                         <parameter name="status" required="true" />
521                         <parameter name="talktime" required="true" />
522                         <parameter name="params" required="false" />
523                 </syntax>
524                 <description>
525                         <para>Allows you to write Outbound events into the queue log.</para>
526                         <para>Example: exten => h,1,QueueUpdate(${QUEUE}, ${UNIQUEID}, ${AGENT}, ${DIALSTATUS}, ${ANSWEREDTIME}, ${DIALEDTIME} | ${DIALEDNUMBER})</para>
527                 </description>
528         </application>
529         <function name="QUEUE_VARIABLES" language="en_US">
530                 <synopsis>
531                         Return Queue information in variables.
532                 </synopsis>
533                 <syntax>
534                         <parameter name="queuename" required="true">
535                                 <enumlist>
536                                         <enum name="QUEUEMAX">
537                                                 <para>Maxmimum number of calls allowed.</para>
538                                         </enum>
539                                         <enum name="QUEUESTRATEGY">
540                                                 <para>The strategy of the queue.</para>
541                                         </enum>
542                                         <enum name="QUEUECALLS">
543                                                 <para>Number of calls currently in the queue.</para>
544                                         </enum>
545                                         <enum name="QUEUEHOLDTIME">
546                                                 <para>Current average hold time.</para>
547                                         </enum>
548                                         <enum name="QUEUECOMPLETED">
549                                                 <para>Number of completed calls for the queue.</para>
550                                         </enum>
551                                         <enum name="QUEUEABANDONED">
552                                                 <para>Number of abandoned calls.</para>
553                                         </enum>
554                                         <enum name="QUEUESRVLEVEL">
555                                                 <para>Queue service level.</para>
556                                         </enum>
557                                         <enum name="QUEUESRVLEVELPERF">
558                                                 <para>Current service level performance.</para>
559                                         </enum>
560                                 </enumlist>
561                         </parameter>
562                 </syntax>
563                 <description>
564                         <para>Makes the following queue variables available.</para>
565                         <para>Returns <literal>0</literal> if queue is found and setqueuevar is defined, <literal>-1</literal> otherwise.</para>
566                 </description>
567                 <see-also>
568                         <ref type="application">Queue</ref>
569                         <ref type="application">QueueLog</ref>
570                         <ref type="application">AddQueueMember</ref>
571                         <ref type="application">RemoveQueueMember</ref>
572                         <ref type="application">PauseQueueMember</ref>
573                         <ref type="application">UnpauseQueueMember</ref>
574                         <ref type="function">QUEUE_VARIABLES</ref>
575                         <ref type="function">QUEUE_MEMBER</ref>
576                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
577                         <ref type="function">QUEUE_EXISTS</ref>
578                         <ref type="function">QUEUE_GET_CHANNEL</ref>
579                         <ref type="function">QUEUE_WAITING_COUNT</ref>
580                         <ref type="function">QUEUE_MEMBER_LIST</ref>
581                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
582                 </see-also>
583         </function>
584         <function name="QUEUE_MEMBER" language="en_US">
585                 <synopsis>
586                         Provides a count of queue members based on the provided criteria, or updates a
587                         queue member's settings.
588                 </synopsis>
589                 <syntax>
590                         <parameter name="queuename" required="false" />
591                         <parameter name="option" required="true">
592                                 <enumlist>
593                                         <enum name="logged">
594                                                 <para>Returns the number of logged-in members for the specified queue.</para>
595                                         </enum>
596                                         <enum name="free">
597                                                 <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>
598                                         </enum>
599                                         <enum name="ready">
600                                                 <para>Returns the number of logged-in members for the specified queue that are immediately available to answer a call.</para>
601                                         </enum>
602                                         <enum name="count">
603                                                 <para>Returns the total number of members for the specified queue.</para>
604                                         </enum>
605                                         <enum name="penalty">
606                                                 <para>Gets or sets queue member penalty.  If
607                                                 <replaceable>queuename</replaceable> is not specified
608                                                 when setting the penalty then the penalty is set in all queues
609                                                 the interface is a member.</para>
610                                         </enum>
611                                         <enum name="paused">
612                                                 <para>Gets or sets queue member paused status.  If
613                                                 <replaceable>queuename</replaceable> is not specified
614                                                 when setting the paused status then the paused status is set
615                                                 in all queues the interface is a member.</para>
616                                         </enum>
617                                         <enum name="ringinuse">
618                                                 <para>Gets or sets queue member ringinuse.  If
619                                                 <replaceable>queuename</replaceable> is not specified
620                                                 when setting ringinuse then ringinuse is set
621                                                 in all queues the interface is a member.</para>
622                                         </enum>
623                                 </enumlist>
624                         </parameter>
625                         <parameter name="interface" required="false" />
626                 </syntax>
627                 <description>
628                         <para>Allows access to queue counts [R] and member information [R/W].</para>
629                         <para><replaceable>queuename</replaceable> is required for all read operations.</para>
630                         <para><replaceable>interface</replaceable> is required for all member operations.</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_MEMBER_COUNT" language="en_US">
650                 <synopsis>
651                         Count number of members answering a queue.
652                 </synopsis>
653                 <syntax>
654                         <parameter name="queuename" required="true" />
655                 </syntax>
656                 <description>
657                         <para>Returns the number of members currently associated with the specified <replaceable>queuename</replaceable>.</para>
658                         <warning><para>This function has been deprecated in favor of the <literal>QUEUE_MEMBER()</literal> function</para></warning>
659                 </description>
660                 <see-also>
661                         <ref type="application">Queue</ref>
662                         <ref type="application">QueueLog</ref>
663                         <ref type="application">AddQueueMember</ref>
664                         <ref type="application">RemoveQueueMember</ref>
665                         <ref type="application">PauseQueueMember</ref>
666                         <ref type="application">UnpauseQueueMember</ref>
667                         <ref type="function">QUEUE_VARIABLES</ref>
668                         <ref type="function">QUEUE_MEMBER</ref>
669                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
670                         <ref type="function">QUEUE_EXISTS</ref>
671                         <ref type="function">QUEUE_GET_CHANNEL</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_EXISTS" language="en_US">
678                 <synopsis>
679                         Check if a named queue exists on this server
680                 </synopsis>
681                 <syntax>
682                         <parameter name="queuename" />
683                 </syntax>
684                 <description>
685                         <para>Returns 1 if the specified queue exists, 0 if it does not</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_GET_CHANNEL" language="en_US">
705                 <synopsis>
706                         Return caller at the specified position in a queue.
707                 </synopsis>
708                 <syntax>
709                         <parameter name="queuename" required="true" />
710                         <parameter name="position" />
711                 </syntax>
712                 <description>
713                         <para>Returns the caller channel at <replaceable>position</replaceable> in the specified <replaceable>queuename</replaceable>.</para>
714                         <para>If <replaceable>position</replaceable> is unspecified the first channel is returned.</para>
715                 </description>
716                 <see-also>
717                         <ref type="application">Queue</ref>
718                         <ref type="application">QueueLog</ref>
719                         <ref type="application">AddQueueMember</ref>
720                         <ref type="application">RemoveQueueMember</ref>
721                         <ref type="application">PauseQueueMember</ref>
722                         <ref type="application">UnpauseQueueMember</ref>
723                         <ref type="function">QUEUE_VARIABLES</ref>
724                         <ref type="function">QUEUE_MEMBER</ref>
725                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
726                         <ref type="function">QUEUE_EXISTS</ref>
727                         <ref type="function">QUEUE_WAITING_COUNT</ref>
728                         <ref type="function">QUEUE_MEMBER_LIST</ref>
729                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
730                 </see-also>
731         </function>
732         <function name="QUEUE_WAITING_COUNT" language="en_US">
733                 <synopsis>
734                         Count number of calls currently waiting in a queue.
735                 </synopsis>
736                 <syntax>
737                         <parameter name="queuename" />
738                 </syntax>
739                 <description>
740                         <para>Returns the number of callers currently waiting in the specified <replaceable>queuename</replaceable>.</para>
741                 </description>
742                 <see-also>
743                         <ref type="application">Queue</ref>
744                         <ref type="application">QueueLog</ref>
745                         <ref type="application">AddQueueMember</ref>
746                         <ref type="application">RemoveQueueMember</ref>
747                         <ref type="application">PauseQueueMember</ref>
748                         <ref type="application">UnpauseQueueMember</ref>
749                         <ref type="function">QUEUE_VARIABLES</ref>
750                         <ref type="function">QUEUE_MEMBER</ref>
751                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
752                         <ref type="function">QUEUE_EXISTS</ref>
753                         <ref type="function">QUEUE_GET_CHANNEL</ref>
754                         <ref type="function">QUEUE_WAITING_COUNT</ref>
755                         <ref type="function">QUEUE_MEMBER_LIST</ref>
756                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
757                 </see-also>
758         </function>
759         <function name="QUEUE_MEMBER_LIST" language="en_US">
760                 <synopsis>
761                         Returns a list of interfaces on a queue.
762                 </synopsis>
763                 <syntax>
764                         <parameter name="queuename" required="true" />
765                 </syntax>
766                 <description>
767                         <para>Returns a comma-separated list of members associated with the specified <replaceable>queuename</replaceable>.</para>
768                 </description>
769                 <see-also>
770                         <ref type="application">Queue</ref>
771                         <ref type="application">QueueLog</ref>
772                         <ref type="application">AddQueueMember</ref>
773                         <ref type="application">RemoveQueueMember</ref>
774                         <ref type="application">PauseQueueMember</ref>
775                         <ref type="application">UnpauseQueueMember</ref>
776                         <ref type="function">QUEUE_VARIABLES</ref>
777                         <ref type="function">QUEUE_MEMBER</ref>
778                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
779                         <ref type="function">QUEUE_EXISTS</ref>
780                         <ref type="function">QUEUE_GET_CHANNEL</ref>
781                         <ref type="function">QUEUE_WAITING_COUNT</ref>
782                         <ref type="function">QUEUE_MEMBER_LIST</ref>
783                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
784                 </see-also>
785         </function>
786         <function name="QUEUE_MEMBER_PENALTY" language="en_US">
787                 <synopsis>
788                         Gets or sets queue members penalty.
789                 </synopsis>
790                 <syntax>
791                         <parameter name="queuename" required="true" />
792                         <parameter name="interface" required="true" />
793                 </syntax>
794                 <description>
795                         <para>Gets or sets queue members penalty.</para>
796                         <warning><para>This function has been deprecated in favor of the <literal>QUEUE_MEMBER()</literal> function</para></warning>
797                 </description>
798                 <see-also>
799                         <ref type="application">Queue</ref>
800                         <ref type="application">QueueLog</ref>
801                         <ref type="application">AddQueueMember</ref>
802                         <ref type="application">RemoveQueueMember</ref>
803                         <ref type="application">PauseQueueMember</ref>
804                         <ref type="application">UnpauseQueueMember</ref>
805                         <ref type="function">QUEUE_VARIABLES</ref>
806                         <ref type="function">QUEUE_MEMBER</ref>
807                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
808                         <ref type="function">QUEUE_EXISTS</ref>
809                         <ref type="function">QUEUE_GET_CHANNEL</ref>
810                         <ref type="function">QUEUE_WAITING_COUNT</ref>
811                         <ref type="function">QUEUE_MEMBER_LIST</ref>
812                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
813                 </see-also>
814         </function>
815         <manager name="QueueStatus" language="en_US">
816                 <synopsis>
817                         Show queue status.
818                 </synopsis>
819                 <syntax>
820                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
821                         <parameter name="Queue">
822                                 <para>Limit the response to the status of the specified queue.</para>
823                         </parameter>
824                         <parameter name="Member">
825                                 <para>Limit the response to the status of the specified member.</para>
826                         </parameter>
827                 </syntax>
828                 <description>
829                         <para>Check the status of one or more queues.</para>
830                 </description>
831         </manager>
832         <manager name="QueueSummary" language="en_US">
833                 <synopsis>
834                         Show queue summary.
835                 </synopsis>
836                 <syntax>
837                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
838                         <parameter name="Queue">
839                                 <para>Queue for which the summary is requested.</para>
840                         </parameter>
841                 </syntax>
842                 <description>
843                         <para>Request the manager to send a QueueSummary event.</para>
844                 </description>
845         </manager>
846         <manager name="QueueAdd" language="en_US">
847                 <synopsis>
848                         Add interface to queue.
849                 </synopsis>
850                 <syntax>
851                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
852                         <parameter name="Queue" required="true">
853                                 <para>Queue's name.</para>
854                         </parameter>
855                         <parameter name="Interface" required="true">
856                                 <para>The name of the interface (tech/name) to add to the queue.</para>
857                         </parameter>
858                         <parameter name="Penalty">
859                                 <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>
860                         </parameter>
861                         <parameter name="Paused">
862                                 <para>To pause or not the member initially (true/false or 1/0).</para>
863                         </parameter>
864                         <parameter name="MemberName">
865                                 <para>Text alias for the interface.</para>
866                         </parameter>
867                         <parameter name="StateInterface" />
868                 </syntax>
869                 <description>
870                 </description>
871         </manager>
872         <manager name="QueueRemove" language="en_US">
873                 <synopsis>
874                         Remove interface from queue.
875                 </synopsis>
876                 <syntax>
877                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
878                         <parameter name="Queue" required="true">
879                                 <para>The name of the queue to take action on.</para>
880                         </parameter>
881                         <parameter name="Interface" required="true">
882                                 <para>The interface (tech/name) to remove from queue.</para>
883                         </parameter>
884                 </syntax>
885                 <description>
886                 </description>
887         </manager>
888         <manager name="QueuePause" language="en_US">
889                 <synopsis>
890                         Makes a queue member temporarily unavailable.
891                 </synopsis>
892                 <syntax>
893                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
894                         <parameter name="Interface" required="true">
895                                 <para>The name of the interface (tech/name) to pause or unpause.</para>
896                         </parameter>
897                         <parameter name="Paused" required="true">
898                                 <para>Pause or unpause the interface. Set to 'true' to pause the member or 'false' to unpause.</para>
899                         </parameter>
900                         <parameter name="Queue">
901                                 <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>
902                         </parameter>
903                         <parameter name="Reason">
904                                 <para>Text description, returned in the event QueueMemberPaused.</para>
905                         </parameter>
906                 </syntax>
907                 <description>
908                         <para>Pause or unpause a member in a queue.</para>
909                 </description>
910         </manager>
911         <manager name="QueueLog" language="en_US">
912                 <synopsis>
913                         Adds custom entry in queue_log.
914                 </synopsis>
915                 <syntax>
916                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
917                         <parameter name="Queue" required="true" />
918                         <parameter name="Event" required="true" />
919                         <parameter name="Uniqueid" />
920                         <parameter name="Interface" />
921                         <parameter name="Message" />
922                 </syntax>
923                 <description>
924                 </description>
925         </manager>
926         <manager name="QueuePenalty" language="en_US">
927                 <synopsis>
928                         Set the penalty for a queue member.
929                 </synopsis>
930                 <syntax>
931                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
932                         <parameter name="Interface" required="true">
933                                 <para>The interface (tech/name) of the member whose penalty to change.</para>
934                         </parameter>
935                         <parameter name="Penalty" required="true">
936                                 <para>The new penalty (number) for the member. Must be nonnegative.</para>
937                         </parameter>
938                         <parameter name="Queue">
939                                 <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>
940                         </parameter>
941                 </syntax>
942                 <description>
943                         <para>Change the penalty of a queue member</para>
944                 </description>
945         </manager>
946         <manager name="QueueMemberRingInUse" language="en_US">
947                 <synopsis>
948                         Set the ringinuse value for a queue member.
949                 </synopsis>
950                 <syntax>
951                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
952                         <parameter name="Interface" required="true" />
953                         <parameter name="RingInUse" required="true" />
954                         <parameter name="Queue" />
955                 </syntax>
956                 <description>
957                 </description>
958         </manager>
959         <manager name="QueueRule" language="en_US">
960                 <synopsis>
961                         Queue Rules.
962                 </synopsis>
963                 <syntax>
964                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
965                         <parameter name="Rule">
966                                 <para>The name of the rule in queuerules.conf whose contents to list.</para>
967                         </parameter>
968                 </syntax>
969                 <description>
970                         <para>List queue rules defined in queuerules.conf</para>
971                 </description>
972         </manager>
973         <manager name="QueueReload" language="en_US">
974                 <synopsis>
975                         Reload a queue, queues, or any sub-section of a queue or queues.
976                 </synopsis>
977                 <syntax>
978                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
979                         <parameter name="Queue">
980                                 <para>The name of the queue to take action on. If no queue name is specified, then all queues are affected.</para>
981                         </parameter>
982                         <parameter name="Members">
983                                 <para>Whether to reload the queue's members.</para>
984                                 <enumlist>
985                                         <enum name="yes" />
986                                         <enum name="no" />
987                                 </enumlist>
988                         </parameter>
989                         <parameter name="Rules">
990                                 <para>Whether to reload queuerules.conf</para>
991                                 <enumlist>
992                                         <enum name="yes" />
993                                         <enum name="no" />
994                                 </enumlist>
995                         </parameter>
996                         <parameter name="Parameters">
997                                 <para>Whether to reload the other queue options.</para>
998                                 <enumlist>
999                                         <enum name="yes" />
1000                                         <enum name="no" />
1001                                 </enumlist>
1002                         </parameter>
1003                 </syntax>
1004                 <description>
1005                 </description>
1006         </manager>
1007         <manager name="QueueReset" language="en_US">
1008                 <synopsis>
1009                         Reset queue statistics.
1010                 </synopsis>
1011                 <syntax>
1012                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1013                         <parameter name="Queue">
1014                                 <para>The name of the queue on which to reset statistics.</para>
1015                         </parameter>
1016                 </syntax>
1017                 <description>
1018                         <para>Reset the statistics for a queue.</para>
1019                 </description>
1020         </manager>
1021         <manager name="QueueChangePriorityCaller" language="en_US">
1022                 <synopsis>
1023                         Change priority of a caller on queue.
1024                 </synopsis>
1025                 <syntax>
1026                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1027                         <parameter name="Queue" required="true">
1028                                 <para>The name of the queue to take action on.</para>
1029                         </parameter>
1030                         <parameter name="Caller" required="true">
1031                                 <para>The caller (channel) to change priority on queue.</para>
1032                         </parameter>
1033
1034                         <parameter name="Priority" required="true">
1035                                 <para>Priority value for change for caller on queue.</para>
1036                         </parameter>
1037                 </syntax>
1038                 <description>
1039                 </description>
1040         </manager>
1041
1042         <managerEvent language="en_US" name="QueueMemberStatus">
1043                 <managerEventInstance class="EVENT_FLAG_AGENT">
1044                         <synopsis>Raised when a Queue member's status has changed.</synopsis>
1045                         <syntax>
1046                                 <parameter name="Queue">
1047                                         <para>The name of the queue.</para>
1048                                 </parameter>
1049                                 <parameter name="MemberName">
1050                                         <para>The name of the queue member.</para>
1051                                 </parameter>
1052                                 <parameter name="Interface">
1053                                         <para>The queue member's channel technology or location.</para>
1054                                 </parameter>
1055                                 <parameter name="StateInterface">
1056                                         <para>Channel technology or location from which to read device state changes.</para>
1057                                 </parameter>
1058                                 <parameter name="Membership">
1059                                         <enumlist>
1060                                                 <enum name="dynamic"/>
1061                                                 <enum name="realtime"/>
1062                                                 <enum name="static"/>
1063                                         </enumlist>
1064                                 </parameter>
1065                                 <parameter name="Penalty">
1066                                         <para>The penalty associated with the queue member.</para>
1067                                 </parameter>
1068                                 <parameter name="CallsTaken">
1069                                         <para>The number of calls this queue member has serviced.</para>
1070                                 </parameter>
1071                                 <parameter name="LastCall">
1072                                         <para>The time this member last took a call, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1073                                 </parameter>
1074                                 <parameter name="LastPause">
1075                                         <para>The time when started last paused the queue member.</para>
1076                                 </parameter>
1077                                 <parameter name="InCall">
1078                                         <para>Set to 1 if member is in call. Set to 0 after LastCall time is updated.</para>
1079                                         <enumlist>
1080                                                 <enum name="0"/>
1081                                                 <enum name="1"/>
1082                                         </enumlist>
1083                                 </parameter>
1084                                 <parameter name="Status">
1085                                         <para>The numeric device state status of the queue member.</para>
1086                                         <enumlist>
1087                                                 <enum name="0"><para>AST_DEVICE_UNKNOWN</para></enum>
1088                                                 <enum name="1"><para>AST_DEVICE_NOT_INUSE</para></enum>
1089                                                 <enum name="2"><para>AST_DEVICE_INUSE</para></enum>
1090                                                 <enum name="3"><para>AST_DEVICE_BUSY</para></enum>
1091                                                 <enum name="4"><para>AST_DEVICE_INVALID</para></enum>
1092                                                 <enum name="5"><para>AST_DEVICE_UNAVAILABLE</para></enum>
1093                                                 <enum name="6"><para>AST_DEVICE_RINGING</para></enum>
1094                                                 <enum name="7"><para>AST_DEVICE_RINGINUSE</para></enum>
1095                                                 <enum name="8"><para>AST_DEVICE_ONHOLD</para></enum>
1096                                         </enumlist>
1097                                 </parameter>
1098                                 <parameter name="Paused">
1099                                         <enumlist>
1100                                                 <enum name="0"/>
1101                                                 <enum name="1"/>
1102                                         </enumlist>
1103                                 </parameter>
1104                                 <parameter name="PausedReason">
1105                                         <para>If set when paused, the reason the queue member was paused.</para>
1106                                 </parameter>
1107                                 <parameter name="Ringinuse">
1108                                         <enumlist>
1109                                                 <enum name="0"/>
1110                                                 <enum name="1"/>
1111                                         </enumlist>
1112                                 </parameter>
1113                                 <parameter name="Wrapuptime">
1114                                         <para>The Wrapup Time of the queue member. If this value is set will override the wrapup time of queue.</para>
1115                                 </parameter>
1116                         </syntax>
1117                 </managerEventInstance>
1118         </managerEvent>
1119         <managerEvent language="en_US" name="QueueMemberAdded">
1120                 <managerEventInstance class="EVENT_FLAG_AGENT">
1121                         <synopsis>Raised when a member is added to the queue.</synopsis>
1122                         <syntax>
1123                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1124                         </syntax>
1125                         <see-also>
1126                                 <ref type="managerEvent">QueueMemberRemoved</ref>
1127                                 <ref type="application">AddQueueMember</ref>
1128                         </see-also>
1129                 </managerEventInstance>
1130         </managerEvent>
1131         <managerEvent language="en_US" name="QueueMemberRemoved">
1132                 <managerEventInstance class="EVENT_FLAG_AGENT">
1133                         <synopsis>Raised when a member is removed from the queue.</synopsis>
1134                         <syntax>
1135                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1136                         </syntax>
1137                         <see-also>
1138                                 <ref type="managerEvent">QueueMemberAdded</ref>
1139                                 <ref type="application">RemoveQueueMember</ref>
1140                         </see-also>
1141                 </managerEventInstance>
1142         </managerEvent>
1143         <managerEvent language="en_US" name="QueueMemberPause">
1144                 <managerEventInstance class="EVENT_FLAG_AGENT">
1145                         <synopsis>Raised when a member is paused/unpaused in the queue.</synopsis>
1146                         <syntax>
1147                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1148                         </syntax>
1149                         <see-also>
1150                                 <ref type="application">PauseQueueMember</ref>
1151                                 <ref type="application">UnPauseQueueMember</ref>
1152                         </see-also>
1153                 </managerEventInstance>
1154         </managerEvent>
1155         <managerEvent language="en_US" name="QueueMemberPenalty">
1156                 <managerEventInstance class="EVENT_FLAG_AGENT">
1157                         <synopsis>Raised when a member's penalty is changed.</synopsis>
1158                         <syntax>
1159                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1160                         </syntax>
1161                         <see-also>
1162                                 <ref type="function">QUEUE_MEMBER</ref>
1163                         </see-also>
1164                 </managerEventInstance>
1165         </managerEvent>
1166         <managerEvent language="en_US" name="QueueMemberRinginuse">
1167                 <managerEventInstance class="EVENT_FLAG_AGENT">
1168                         <synopsis>Raised when a member's ringinuse setting is changed.</synopsis>
1169                         <syntax>
1170                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1171                         </syntax>
1172                         <see-also>
1173                                 <ref type="function">QUEUE_MEMBER</ref>
1174                         </see-also>
1175                 </managerEventInstance>
1176         </managerEvent>
1177         <managerEvent language="en_US" name="QueueCallerJoin">
1178                 <managerEventInstance class="EVENT_FLAG_AGENT">
1179                         <synopsis>Raised when a caller joins a Queue.</synopsis>
1180                         <syntax>
1181                                 <channel_snapshot/>
1182                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1183                                 <parameter name="Position">
1184                                         <para>This channel's current position in the queue.</para>
1185                                 </parameter>
1186                                 <parameter name="Count">
1187                                         <para>The total number of channels in the queue.</para>
1188                                 </parameter>
1189                         </syntax>
1190                         <see-also>
1191                                 <ref type="managerEvent">QueueCallerLeave</ref>
1192                                 <ref type="application">Queue</ref>
1193                         </see-also>
1194                 </managerEventInstance>
1195         </managerEvent>
1196         <managerEvent language="en_US" name="QueueCallerLeave">
1197                 <managerEventInstance class="EVENT_FLAG_AGENT">
1198                         <synopsis>Raised when a caller leaves a Queue.</synopsis>
1199                         <syntax>
1200                                 <channel_snapshot/>
1201                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1202                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Count'])" />
1203                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Position'])" />
1204                         </syntax>
1205                         <see-also>
1206                                 <ref type="managerEvent">QueueCallerJoin</ref>
1207                         </see-also>
1208                 </managerEventInstance>
1209         </managerEvent>
1210         <managerEvent language="en_US" name="QueueCallerAbandon">
1211                 <managerEventInstance class="EVENT_FLAG_AGENT">
1212                         <synopsis>Raised when a caller abandons the queue.</synopsis>
1213                         <syntax>
1214                                 <channel_snapshot/>
1215                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1216                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Position'])" />
1217                                 <parameter name="OriginalPosition">
1218                                         <para>The channel's original position in the queue.</para>
1219                                 </parameter>
1220                                 <parameter name="HoldTime">
1221                                         <para>The time the channel was in the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1222                                 </parameter>
1223                         </syntax>
1224                 </managerEventInstance>
1225         </managerEvent>
1226         <managerEvent language="en_US" name="AgentCalled">
1227                 <managerEventInstance class="EVENT_FLAG_AGENT">
1228                         <synopsis>Raised when an queue member is notified of a caller in the queue.</synopsis>
1229                         <syntax>
1230                                 <channel_snapshot/>
1231                                 <channel_snapshot prefix="Dest"/>
1232                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1233                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1234                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1235                         </syntax>
1236                         <see-also>
1237                                 <ref type="managerEvent">AgentRingNoAnswer</ref>
1238                                 <ref type="managerEvent">AgentComplete</ref>
1239                                 <ref type="managerEvent">AgentConnect</ref>
1240                         </see-also>
1241                 </managerEventInstance>
1242         </managerEvent>
1243         <managerEvent language="en_US" name="AgentRingNoAnswer">
1244                 <managerEventInstance class="EVENT_FLAG_AGENT">
1245                         <synopsis>Raised when a queue member is notified of a caller in the queue and fails to answer.</synopsis>
1246                         <syntax>
1247                                 <channel_snapshot/>
1248                                 <channel_snapshot prefix="Dest"/>
1249                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1250                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1251                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1252                                 <parameter name="RingTime">
1253                                         <para>The time the queue member was rung, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1254                                 </parameter>
1255                         </syntax>
1256                         <see-also>
1257                                 <ref type="managerEvent">AgentCalled</ref>
1258                         </see-also>
1259                 </managerEventInstance>
1260         </managerEvent>
1261         <managerEvent language="en_US" name="AgentComplete">
1262                 <managerEventInstance class="EVENT_FLAG_AGENT">
1263                         <synopsis>Raised when a queue member has finished servicing a caller in the queue.</synopsis>
1264                         <syntax>
1265                                 <channel_snapshot/>
1266                                 <channel_snapshot prefix="Dest"/>
1267                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1268                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1269                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1270                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerAbandon']/managerEventInstance/syntax/parameter[@name='HoldTime'])" />
1271                                 <parameter name="TalkTime">
1272                                         <para>The time the queue member talked with the caller in the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1273                                 </parameter>
1274                                 <parameter name="Reason">
1275                                         <enumlist>
1276                                                 <enum name="caller"/>
1277                                                 <enum name="agent"/>
1278                                                 <enum name="transfer"/>
1279                                         </enumlist>
1280                                 </parameter>
1281                         </syntax>
1282                         <see-also>
1283                                 <ref type="managerEvent">AgentCalled</ref>
1284                                 <ref type="managerEvent">AgentConnect</ref>
1285                         </see-also>
1286                 </managerEventInstance>
1287         </managerEvent>
1288         <managerEvent language="en_US" name="AgentDump">
1289                 <managerEventInstance class="EVENT_FLAG_AGENT">
1290                         <synopsis>Raised when a queue member hangs up on a caller in the queue.</synopsis>
1291                         <syntax>
1292                                 <channel_snapshot/>
1293                                 <channel_snapshot prefix="Dest"/>
1294                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1295                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1296                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1297                         </syntax>
1298                         <see-also>
1299                                 <ref type="managerEvent">AgentCalled</ref>
1300                                 <ref type="managerEvent">AgentConnect</ref>
1301                         </see-also>
1302                 </managerEventInstance>
1303         </managerEvent>
1304         <managerEvent language="en_US" name="AgentConnect">
1305                 <managerEventInstance class="EVENT_FLAG_AGENT">
1306                         <synopsis>Raised when a queue member answers and is bridged to a caller in the queue.</synopsis>
1307                         <syntax>
1308                                 <channel_snapshot/>
1309                                 <channel_snapshot prefix="Dest"/>
1310                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1311                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1312                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1313                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='AgentRingNoAnswer']/managerEventInstance/syntax/parameter[@name='RingTime'])" />
1314                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerAbandon']/managerEventInstance/syntax/parameter[@name='HoldTime'])" />
1315                         </syntax>
1316                         <see-also>
1317                                 <ref type="managerEvent">AgentCalled</ref>
1318                                 <ref type="managerEvent">AgentComplete</ref>
1319                                 <ref type="managerEvent">AgentDump</ref>
1320                         </see-also>
1321                 </managerEventInstance>
1322         </managerEvent>
1323  ***/
1324
1325 enum {
1326         OPT_MARK_AS_ANSWERED =       (1 << 0),
1327         OPT_GO_ON =                  (1 << 1),
1328         OPT_DATA_QUALITY =           (1 << 2),
1329         OPT_CALLEE_GO_ON =           (1 << 3),
1330         OPT_CALLEE_HANGUP =          (1 << 4),
1331         OPT_CALLER_HANGUP =          (1 << 5),
1332         OPT_IGNORE_CALL_FW =         (1 << 6),
1333         OPT_IGNORE_CONNECTEDLINE =   (1 << 7),
1334         OPT_CALLEE_PARK =            (1 << 8),
1335         OPT_CALLER_PARK =            (1 << 9),
1336         OPT_NO_RETRY =               (1 << 10),
1337         OPT_RINGING =                (1 << 11),
1338         OPT_RING_WHEN_RINGING =      (1 << 12),
1339         OPT_CALLEE_TRANSFER =        (1 << 13),
1340         OPT_CALLER_TRANSFER =        (1 << 14),
1341         OPT_CALLEE_AUTOMIXMON =      (1 << 15),
1342         OPT_CALLER_AUTOMIXMON =      (1 << 16),
1343         OPT_CALLEE_AUTOMON =         (1 << 17),
1344         OPT_CALLER_AUTOMON =         (1 << 18),
1345         OPT_PREDIAL_CALLEE =         (1 << 19),
1346         OPT_PREDIAL_CALLER =         (1 << 20),
1347 };
1348
1349 enum {
1350         OPT_ARG_CALLEE_GO_ON = 0,
1351         OPT_ARG_PREDIAL_CALLEE,
1352         OPT_ARG_PREDIAL_CALLER,
1353         /* note: this entry _MUST_ be the last one in the enum */
1354         OPT_ARG_ARRAY_SIZE
1355 };
1356
1357 AST_APP_OPTIONS(queue_exec_options, BEGIN_OPTIONS
1358         AST_APP_OPTION_ARG('b', OPT_PREDIAL_CALLEE, OPT_ARG_PREDIAL_CALLEE),
1359         AST_APP_OPTION_ARG('B', OPT_PREDIAL_CALLER, OPT_ARG_PREDIAL_CALLER),
1360         AST_APP_OPTION('C', OPT_MARK_AS_ANSWERED),
1361         AST_APP_OPTION('c', OPT_GO_ON),
1362         AST_APP_OPTION('d', OPT_DATA_QUALITY),
1363         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
1364         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
1365         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
1366         AST_APP_OPTION('i', OPT_IGNORE_CALL_FW),
1367         AST_APP_OPTION('I', OPT_IGNORE_CONNECTEDLINE),
1368         AST_APP_OPTION('k', OPT_CALLEE_PARK),
1369         AST_APP_OPTION('K', OPT_CALLER_PARK),
1370         AST_APP_OPTION('n', OPT_NO_RETRY),
1371         AST_APP_OPTION('r', OPT_RINGING),
1372         AST_APP_OPTION('R', OPT_RING_WHEN_RINGING),
1373         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
1374         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
1375         AST_APP_OPTION('x', OPT_CALLEE_AUTOMIXMON),
1376         AST_APP_OPTION('X', OPT_CALLER_AUTOMIXMON),
1377         AST_APP_OPTION('w', OPT_CALLEE_AUTOMON),
1378         AST_APP_OPTION('W', OPT_CALLER_AUTOMON),
1379 END_OPTIONS);
1380
1381 enum {
1382         QUEUE_STRATEGY_RINGALL = 0,
1383         QUEUE_STRATEGY_LEASTRECENT,
1384         QUEUE_STRATEGY_FEWESTCALLS,
1385         QUEUE_STRATEGY_RANDOM,
1386         QUEUE_STRATEGY_RRMEMORY,
1387         QUEUE_STRATEGY_LINEAR,
1388         QUEUE_STRATEGY_WRANDOM,
1389         QUEUE_STRATEGY_RRORDERED,
1390 };
1391
1392 enum {
1393         QUEUE_AUTOPAUSE_OFF = 0,
1394         QUEUE_AUTOPAUSE_ON,
1395         QUEUE_AUTOPAUSE_ALL
1396 };
1397
1398 enum queue_reload_mask {
1399         QUEUE_RELOAD_PARAMETERS = (1 << 0),
1400         QUEUE_RELOAD_MEMBER = (1 << 1),
1401         QUEUE_RELOAD_RULES = (1 << 2),
1402         QUEUE_RESET_STATS = (1 << 3),
1403 };
1404
1405 static const struct strategy {
1406         int strategy;
1407         const char *name;
1408 } strategies[] = {
1409         { QUEUE_STRATEGY_RINGALL, "ringall" },
1410         { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
1411         { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
1412         { QUEUE_STRATEGY_RANDOM, "random" },
1413         { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
1414         { QUEUE_STRATEGY_RRMEMORY, "roundrobin" },
1415         { QUEUE_STRATEGY_LINEAR, "linear" },
1416         { QUEUE_STRATEGY_WRANDOM, "wrandom"},
1417         { QUEUE_STRATEGY_RRORDERED, "rrordered"},
1418 };
1419
1420 static const struct autopause {
1421         int autopause;
1422         const char *name;
1423 } autopausesmodes [] = {
1424         { QUEUE_AUTOPAUSE_OFF,"no" },
1425         { QUEUE_AUTOPAUSE_ON, "yes" },
1426         { QUEUE_AUTOPAUSE_ALL,"all" },
1427 };
1428
1429 #define DEFAULT_RETRY           5
1430 #define DEFAULT_TIMEOUT         15
1431 #define RECHECK                 1               /*!< Recheck every second to see we we're at the top yet */
1432 #define MAX_PERIODIC_ANNOUNCEMENTS 10           /*!< The maximum periodic announcements we can have */
1433 /*!
1434  * \brief The minimum number of seconds between position announcements.
1435  * \note The default value of 15 provides backwards compatibility.
1436  */
1437 #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15
1438
1439 #define MAX_QUEUE_BUCKETS 53
1440
1441 #define RES_OKAY        0               /*!< Action completed */
1442 #define RES_EXISTS      (-1)            /*!< Entry already exists */
1443 #define RES_OUTOFMEMORY (-2)            /*!< Out of memory */
1444 #define RES_NOSUCHQUEUE (-3)            /*!< No such queue */
1445 #define RES_NOT_DYNAMIC (-4)            /*!< Member is not dynamic */
1446 #define RES_NOT_CALLER  (-5)            /*!< Caller not found */
1447
1448 static char *app = "Queue";
1449
1450 static char *app_aqm = "AddQueueMember" ;
1451
1452 static char *app_rqm = "RemoveQueueMember" ;
1453
1454 static char *app_pqm = "PauseQueueMember" ;
1455
1456 static char *app_upqm = "UnpauseQueueMember" ;
1457
1458 static char *app_ql = "QueueLog" ;
1459
1460 static char *app_qupd = "QueueUpdate";
1461
1462 /*! \brief Persistent Members astdb family */
1463 static const char * const pm_family = "Queue/PersistentMembers";
1464
1465 /*! \brief queues.conf [general] option */
1466 static int queue_persistent_members = 0;
1467
1468 /*! \brief queues.conf per-queue weight option */
1469 static int use_weight = 0;
1470
1471 /*! \brief queues.conf [general] option */
1472 static int autofill_default = 1;
1473
1474 /*! \brief queues.conf [general] option */
1475 static int montype_default = 0;
1476
1477 /*! \brief queues.conf [general] option */
1478 static int shared_lastcall = 0;
1479
1480 /*! \brief queuesrules.conf [general] option */
1481 static int realtime_rules = 0;
1482
1483 /*! \brief Subscription to device state change messages */
1484 static struct stasis_subscription *device_state_sub;
1485
1486 /*! \brief queues.conf [general] option */
1487 static int update_cdr = 0;
1488
1489 /*! \brief queues.conf [general] option */
1490 static int negative_penalty_invalid = 0;
1491
1492 /*! \brief queues.conf [general] option */
1493 static int log_membername_as_agent = 0;
1494
1495 /*! \brief name of the ringinuse field in the realtime database */
1496 static char *realtime_ringinuse_field;
1497
1498 enum queue_result {
1499         QUEUE_UNKNOWN = 0,
1500         QUEUE_TIMEOUT = 1,
1501         QUEUE_JOINEMPTY = 2,
1502         QUEUE_LEAVEEMPTY = 3,
1503         QUEUE_JOINUNAVAIL = 4,
1504         QUEUE_LEAVEUNAVAIL = 5,
1505         QUEUE_FULL = 6,
1506         QUEUE_CONTINUE = 7,
1507 };
1508
1509 static const struct {
1510         enum queue_result id;
1511         char *text;
1512 } queue_results[] = {
1513         { QUEUE_UNKNOWN, "UNKNOWN" },
1514         { QUEUE_TIMEOUT, "TIMEOUT" },
1515         { QUEUE_JOINEMPTY,"JOINEMPTY" },
1516         { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
1517         { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
1518         { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
1519         { QUEUE_FULL, "FULL" },
1520         { QUEUE_CONTINUE, "CONTINUE" },
1521 };
1522
1523 enum queue_timeout_priority {
1524         TIMEOUT_PRIORITY_APP,
1525         TIMEOUT_PRIORITY_CONF,
1526 };
1527
1528 /*! \brief We define a custom "local user" structure because we
1529  *  use it not only for keeping track of what is in use but
1530  *  also for keeping track of who we're dialing.
1531  *
1532  *  There are two "links" defined in this structure, q_next and call_next.
1533  *  q_next links ALL defined callattempt structures into a linked list. call_next is
1534  *  a link which allows for a subset of the callattempts to be traversed. This subset
1535  *  is used in wait_for_answer so that irrelevant callattempts are not traversed. This
1536  *  also is helpful so that queue logs are always accurate in the case where a call to
1537  *  a member times out, especially if using the ringall strategy.
1538 */
1539
1540 struct callattempt {
1541         struct callattempt *q_next;
1542         struct callattempt *call_next;
1543         struct ast_channel *chan;
1544         char interface[256];                    /*!< An Asterisk dial string (not a channel name) */
1545         int metric;
1546         time_t lastcall;
1547         struct call_queue *lastqueue;
1548         struct member *member;
1549         /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
1550         struct ast_party_connected_line connected;
1551         /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
1552         unsigned int pending_connected_update:1;
1553         /*! TRUE if the connected line update is blocked. */
1554         unsigned int block_connected_update:1;
1555         /*! TRUE if caller id is not available for connected line */
1556         unsigned int dial_callerid_absent:1;
1557         /*! TRUE if the call is still active */
1558         unsigned int stillgoing:1;
1559         struct ast_aoc_decoded *aoc_s_rate_list;
1560         /*! Original channel name.  Must be freed.  Could be NULL if allocation failed. */
1561         char *orig_chan_name;
1562 };
1563
1564
1565 struct queue_ent {
1566         struct call_queue *parent;             /*!< What queue is our parent */
1567         char moh[MAX_MUSICCLASS];              /*!< Name of musiconhold to be used */
1568         char announce[PATH_MAX];               /*!< Announcement to play for member when call is answered */
1569         char context[AST_MAX_CONTEXT];         /*!< Context when user exits queue */
1570         char digits[AST_MAX_EXTENSION];        /*!< Digits entered while in queue */
1571         const char *predial_callee;            /*!< Gosub app arguments for outgoing calls.  NULL if not supplied. */
1572         int valid_digits;                      /*!< Digits entered correspond to valid extension. Exited */
1573         int pos;                               /*!< Where we are in the queue */
1574         int prio;                              /*!< Our priority */
1575         int last_pos_said;                     /*!< Last position we told the user */
1576         int ring_when_ringing;                 /*!< Should we only use ring indication when a channel is ringing? */
1577         time_t last_periodic_announce_time;    /*!< The last time we played a periodic announcement */
1578         int last_periodic_announce_sound;      /*!< The last periodic announcement we made */
1579         time_t last_pos;                       /*!< Last time we told the user their position */
1580         int opos;                              /*!< Where we started in the queue */
1581         int handled;                           /*!< Whether our call was handled */
1582         int pending;                           /*!< Non-zero if we are attempting to call a member */
1583         int max_penalty;                       /*!< Limit the members that can take this call to this penalty or lower */
1584         int min_penalty;                       /*!< Limit the members that can take this call to this penalty or higher */
1585         int raise_penalty;                     /*!< Float lower penalty mambers to a minimum penalty */
1586         int linpos;                            /*!< If using linear strategy, what position are we at? */
1587         int linwrapped;                        /*!< Is the linpos wrapped? */
1588         time_t start;                          /*!< When we started holding */
1589         time_t expire;                         /*!< When this entry should expire (time out of queue) */
1590         int cancel_answered_elsewhere;         /*!< Whether we should force the CAE flag on this call (C) option*/
1591         struct ast_channel *chan;              /*!< Our channel */
1592         AST_LIST_HEAD_NOLOCK(,penalty_rule) qe_rules; /*!< Local copy of the queue's penalty rules */
1593         struct penalty_rule *pr;               /*!< Pointer to the next penalty rule to implement */
1594         struct queue_ent *next;                /*!< The next queue entry */
1595 };
1596
1597 struct member {
1598         char interface[AST_CHANNEL_NAME];    /*!< Technology/Location to dial to reach this member*/
1599         char state_exten[AST_MAX_EXTENSION]; /*!< Extension to get state from (if using hint) */
1600         char state_context[AST_MAX_CONTEXT]; /*!< Context to use when getting state (if using hint) */
1601         char state_interface[AST_CHANNEL_NAME]; /*!< Technology/Location from which to read devicestate changes */
1602         int state_id;                        /*!< Extension state callback id (if using hint) */
1603         char membername[80];                 /*!< Member name to use in queue logs */
1604         int penalty;                         /*!< Are we a last resort? */
1605         int calls;                           /*!< Number of calls serviced by this member */
1606         int dynamic;                         /*!< Are we dynamically added? */
1607         int realtime;                        /*!< Is this member realtime? */
1608         int status;                          /*!< Status of queue member */
1609         int paused;                          /*!< Are we paused (not accepting calls)? */
1610         char reason_paused[80];              /*!< Reason of paused if member is paused */
1611         int queuepos;                        /*!< In what order (pertains to certain strategies) should this member be called? */
1612         int callcompletedinsl;               /*!< Whether the current call was completed within service level */
1613         int wrapuptime;                      /*!< Wrapup Time */
1614         time_t starttime;                    /*!< The time at which the member answered the current caller. */
1615         time_t lastcall;                     /*!< When last successful call was hungup */
1616         time_t lastpause;                    /*!< When started the last pause */
1617         struct call_queue *lastqueue;        /*!< Last queue we received a call */
1618         unsigned int dead:1;                 /*!< Used to detect members deleted in realtime */
1619         unsigned int delme:1;                /*!< Flag to delete entry on reload */
1620         char rt_uniqueid[80];                /*!< Unique id of realtime member entry */
1621         unsigned int ringinuse:1;            /*!< Flag to ring queue members even if their status is 'inuse' */
1622 };
1623
1624 enum empty_conditions {
1625         QUEUE_EMPTY_PENALTY = (1 << 0),
1626         QUEUE_EMPTY_PAUSED = (1 << 1),
1627         QUEUE_EMPTY_INUSE = (1 << 2),
1628         QUEUE_EMPTY_RINGING = (1 << 3),
1629         QUEUE_EMPTY_UNAVAILABLE = (1 << 4),
1630         QUEUE_EMPTY_INVALID = (1 << 5),
1631         QUEUE_EMPTY_UNKNOWN = (1 << 6),
1632         QUEUE_EMPTY_WRAPUP = (1 << 7),
1633 };
1634
1635 enum member_properties {
1636         MEMBER_PENALTY = 0,
1637         MEMBER_RINGINUSE = 1,
1638 };
1639
1640 /* values used in multi-bit flags in call_queue */
1641 #define ANNOUNCEHOLDTIME_ALWAYS 1
1642 #define ANNOUNCEHOLDTIME_ONCE 2
1643 #define QUEUE_EVENT_VARIABLES 3
1644
1645 struct penalty_rule {
1646         int time;                           /*!< Number of seconds that need to pass before applying this rule */
1647         int max_value;                      /*!< The amount specified in the penalty rule for max penalty */
1648         int min_value;                      /*!< The amount specified in the penalty rule for min penalty */
1649         int raise_value;                      /*!< The amount specified in the penalty rule for min penalty */
1650         int max_relative;                   /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
1651         int min_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1652         int raise_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1653         AST_LIST_ENTRY(penalty_rule) list;  /*!< Next penalty_rule */
1654 };
1655
1656 #define ANNOUNCEPOSITION_YES 1 /*!< We announce position */
1657 #define ANNOUNCEPOSITION_NO 2 /*!< We don't announce position */
1658 #define ANNOUNCEPOSITION_MORE_THAN 3 /*!< We say "Currently there are more than <limit>" */
1659 #define ANNOUNCEPOSITION_LIMIT 4 /*!< We not announce position more than <limit> */
1660
1661 struct call_queue {
1662         AST_DECLARE_STRING_FIELDS(
1663                 /*! Queue name */
1664                 AST_STRING_FIELD(name);
1665                 /*! Music on Hold class */
1666                 AST_STRING_FIELD(moh);
1667                 /*! Announcement to play when call is answered */
1668                 AST_STRING_FIELD(announce);
1669                 /*! Exit context */
1670                 AST_STRING_FIELD(context);
1671                 /*! Macro to run upon member connection */
1672                 AST_STRING_FIELD(membermacro);
1673                 /*! Gosub to run upon member connection */
1674                 AST_STRING_FIELD(membergosub);
1675                 /*! Default rule to use if none specified in call to Queue() */
1676                 AST_STRING_FIELD(defaultrule);
1677                 /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
1678                 AST_STRING_FIELD(sound_next);
1679                 /*! Sound file: "There are currently" (def. queue-thereare) */
1680                 AST_STRING_FIELD(sound_thereare);
1681                 /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
1682                 AST_STRING_FIELD(sound_calls);
1683                 /*! Sound file: "Currently there are more than" (def. queue-quantity1) */
1684                 AST_STRING_FIELD(queue_quantity1);
1685                 /*! Sound file: "callers waiting to speak with a representative" (def. queue-quantity2) */
1686                 AST_STRING_FIELD(queue_quantity2);
1687                 /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
1688                 AST_STRING_FIELD(sound_holdtime);
1689                 /*! Sound file: "minutes." (def. queue-minutes) */
1690                 AST_STRING_FIELD(sound_minutes);
1691                 /*! Sound file: "minute." (def. queue-minute) */
1692                 AST_STRING_FIELD(sound_minute);
1693                 /*! Sound file: "seconds." (def. queue-seconds) */
1694                 AST_STRING_FIELD(sound_seconds);
1695                 /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
1696                 AST_STRING_FIELD(sound_thanks);
1697                 /*! Sound file: Custom announce for caller, no default */
1698                 AST_STRING_FIELD(sound_callerannounce);
1699                 /*! Sound file: "Hold time" (def. queue-reporthold) */
1700                 AST_STRING_FIELD(sound_reporthold);
1701         );
1702         /*! Sound files: Custom announce, no default */
1703         struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
1704         unsigned int dead:1;
1705         unsigned int ringinuse:1;
1706         unsigned int announce_to_first_user:1; /*!< Whether or not we announce to the first user in a queue */
1707         unsigned int setinterfacevar:1;
1708         unsigned int setqueuevar:1;
1709         unsigned int setqueueentryvar:1;
1710         unsigned int reportholdtime:1;
1711         unsigned int wrapped:1;
1712         unsigned int timeoutrestart:1;
1713         unsigned int announceholdtime:2;
1714         unsigned int announceposition:3;
1715         unsigned int announceposition_only_up:1; /*!< Only announce position if it has improved */
1716         int strategy:4;
1717         unsigned int realtime:1;
1718         unsigned int found:1;
1719         unsigned int relativeperiodicannounce:1;
1720         unsigned int autopausebusy:1;
1721         unsigned int autopauseunavail:1;
1722         enum empty_conditions joinempty;
1723         enum empty_conditions leavewhenempty;
1724         int announcepositionlimit;          /*!< How many positions we announce? */
1725         int announcefrequency;              /*!< How often to announce their position */
1726         int minannouncefrequency;           /*!< The minimum number of seconds between position announcements (def. 15) */
1727         int periodicannouncefrequency;      /*!< How often to play periodic announcement */
1728         int numperiodicannounce;            /*!< The number of periodic announcements configured */
1729         int randomperiodicannounce;         /*!< Are periodic announcments randomly chosen */
1730         int roundingseconds;                /*!< How many seconds do we round to? */
1731         int holdtime;                       /*!< Current avg holdtime, based on an exponential average */
1732         int talktime;                       /*!< Current avg talktime, based on the same exponential average */
1733         int callscompleted;                 /*!< Number of queue calls completed */
1734         int callsabandoned;                 /*!< Number of queue calls abandoned */
1735         int callsabandonedinsl;             /*!< Number of queue calls abandoned in servicelevel */
1736         int servicelevel;                   /*!< seconds setting for servicelevel*/
1737         int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
1738         char monfmt[8];                     /*!< Format to use when recording calls */
1739         int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
1740         int count;                          /*!< How many entries */
1741         int maxlen;                         /*!< Max number of entries */
1742         int wrapuptime;                     /*!< Wrapup Time */
1743         int penaltymemberslimit;            /*!< Disregard penalty when queue has fewer than this many members */
1744
1745         int retry;                          /*!< Retry calling everyone after this amount of time */
1746         int timeout;                        /*!< How long to wait for an answer */
1747         int weight;                         /*!< Respective weight */
1748         int autopause;                      /*!< Auto pause queue members if they fail to answer */
1749         int autopausedelay;                 /*!< Delay auto pause for autopausedelay seconds since last call */
1750         int timeoutpriority;                /*!< Do we allow a fraction of the timeout to occur for a ring? */
1751
1752         /* Queue strategy things */
1753         int rrpos;                          /*!< Round Robin - position */
1754         int memberdelay;                    /*!< Seconds to delay connecting member to caller */
1755         int autofill;                       /*!< Ignore the head call status and ring an available agent */
1756
1757         struct ao2_container *members;      /*!< Head of the list of members */
1758         struct queue_ent *head;             /*!< Head of the list of callers */
1759         AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
1760         AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
1761 };
1762
1763 struct rule_list {
1764         char name[80];
1765         AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
1766         AST_LIST_ENTRY(rule_list) list;
1767 };
1768
1769 static AST_LIST_HEAD_STATIC(rule_lists, rule_list);
1770
1771 static struct ao2_container *queues;
1772
1773 static void update_realtime_members(struct call_queue *q);
1774 static struct member *interface_exists(struct call_queue *q, const char *interface);
1775 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
1776 static int update_queue(struct call_queue *q, struct member *member, int callcompletedinsl, time_t starttime);
1777
1778 static struct member *find_member_by_queuename_and_interface(const char *queuename, const char *interface);
1779 /*! \brief sets the QUEUESTATUS channel variable */
1780 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
1781 {
1782         int i;
1783
1784         for (i = 0; i < ARRAY_LEN(queue_results); i++) {
1785                 if (queue_results[i].id == res) {
1786                         pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
1787                         return;
1788                 }
1789         }
1790 }
1791
1792 static const char *int2strat(int strategy)
1793 {
1794         int x;
1795
1796         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1797                 if (strategy == strategies[x].strategy) {
1798                         return strategies[x].name;
1799                 }
1800         }
1801
1802         return "<unknown>";
1803 }
1804
1805 static int strat2int(const char *strategy)
1806 {
1807         int x;
1808
1809         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1810                 if (!strcasecmp(strategy, strategies[x].name)) {
1811                         return strategies[x].strategy;
1812                 }
1813         }
1814
1815         return -1;
1816 }
1817
1818 static int autopause2int(const char *autopause)
1819 {
1820         int x;
1821         /*This 'double check' that default value is OFF */
1822         if (ast_strlen_zero(autopause)) {
1823                 return QUEUE_AUTOPAUSE_OFF;
1824         }
1825
1826         /*This 'double check' is to ensure old values works */
1827         if(ast_true(autopause)) {
1828                 return QUEUE_AUTOPAUSE_ON;
1829         }
1830
1831         for (x = 0; x < ARRAY_LEN(autopausesmodes); x++) {
1832                 if (!strcasecmp(autopause, autopausesmodes[x].name)) {
1833                         return autopausesmodes[x].autopause;
1834                 }
1835         }
1836
1837         /*This 'double check' that default value is OFF */
1838         return QUEUE_AUTOPAUSE_OFF;
1839 }
1840
1841 static int queue_hash_cb(const void *obj, const int flags)
1842 {
1843         const struct call_queue *q = obj;
1844
1845         return ast_str_case_hash(q->name);
1846 }
1847
1848 static int queue_cmp_cb(void *obj, void *arg, int flags)
1849 {
1850         struct call_queue *q = obj, *q2 = arg;
1851         return !strcasecmp(q->name, q2->name) ? CMP_MATCH | CMP_STOP : 0;
1852 }
1853
1854 /*!
1855  * \brief Return wrapuptime
1856  *
1857  * This function checks if wrapuptime in member is set and return this value.
1858  * Otherwise return value the wrapuptime in the queue configuration
1859  * \return integer value
1860  */
1861 static int get_wrapuptime(struct call_queue *q, struct member *member)
1862 {
1863         if (member->wrapuptime) {
1864                 return member->wrapuptime;
1865         }
1866         return q->wrapuptime;
1867 }
1868
1869 /*! \internal
1870  * \brief ao2_callback, Decreases queuepos of all followers with a queuepos greater than arg.
1871  * \param obj the member being acted on
1872  * \param arg pointer to an integer containing the position value that was removed and requires reduction for anything above
1873  */
1874 static int queue_member_decrement_followers(void *obj, void *arg, int flag)
1875 {
1876         struct member *mem = obj;
1877         int *decrement_followers_after = arg;
1878
1879         if (mem->queuepos > *decrement_followers_after) {
1880                 mem->queuepos--;
1881         }
1882
1883         return 0;
1884 }
1885
1886 /*! \internal
1887  * \brief ao2_callback, finds members in a queue marked for deletion and in a cascading fashion runs queue_member_decrement_followers
1888  *        on them. This callback should always be ran before performing mass unlinking of delmarked members from queues.
1889  * \param obj member being acted on
1890  * \param arg pointer to the queue members are being removed from
1891  */
1892 static int queue_delme_members_decrement_followers(void *obj, void *arg, int flag)
1893 {
1894         struct member *mem = obj;
1895         struct call_queue *queue = arg;
1896         int rrpos = mem->queuepos;
1897
1898         if (mem->delme) {
1899                 ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &rrpos);
1900         }
1901
1902         return 0;
1903 }
1904
1905 /*! \internal
1906  * \brief Use this to decrement followers during removal of a member
1907  * \param queue which queue the member is being removed from
1908  * \param mem which member is being removed from the queue
1909  */
1910 static void queue_member_follower_removal(struct call_queue *queue, struct member *mem)
1911 {
1912         int pos = mem->queuepos;
1913
1914         /* 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
1915          * who would have been next otherwise. */
1916         if (pos < queue->rrpos) {
1917                 queue->rrpos--;
1918         }
1919
1920         ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &pos);
1921 }
1922
1923 #define queue_ref(q)                            ao2_bump(q)
1924 #define queue_unref(q)                          ({ ao2_cleanup(q); NULL; })
1925 #define queue_t_ref(q, tag)                     ao2_t_bump(q, tag)
1926 #define queue_t_unref(q, tag)           ({ ao2_t_cleanup(q, tag); NULL; })
1927 #define queues_t_link(c, q, tag)        ao2_t_link(c, q, tag)
1928 #define queues_t_unlink(c, q, tag)      ao2_t_unlink(c, q, tag)
1929
1930 /*! \brief Set variables of queue */
1931 static void set_queue_variables(struct call_queue *q, struct ast_channel *chan)
1932 {
1933         char interfacevar[256]="";
1934         float sl = 0;
1935
1936         ao2_lock(q);
1937
1938         if (q->setqueuevar) {
1939                 sl = 0;
1940                 if (q->callscompleted > 0) {
1941                         sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
1942                 }
1943
1944                 snprintf(interfacevar, sizeof(interfacevar),
1945                         "QUEUENAME=%s,QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
1946                         q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned,  q->servicelevel, sl);
1947
1948                 ao2_unlock(q);
1949
1950                 pbx_builtin_setvar_multiple(chan, interfacevar);
1951         } else {
1952                 ao2_unlock(q);
1953         }
1954 }
1955
1956 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
1957 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
1958 {
1959         struct queue_ent *cur;
1960
1961         if (!q || !new)
1962                 return;
1963         if (prev) {
1964                 cur = prev->next;
1965                 prev->next = new;
1966         } else {
1967                 cur = q->head;
1968                 q->head = new;
1969         }
1970         new->next = cur;
1971
1972         /* every queue_ent must have a reference to it's parent call_queue, this
1973          * reference does not go away until the end of the queue_ent's life, meaning
1974          * that even when the queue_ent leaves the call_queue this ref must remain. */
1975         queue_ref(q);
1976         new->parent = q;
1977         new->pos = ++(*pos);
1978         new->opos = *pos;
1979 }
1980
1981 static struct ast_manager_event_blob *queue_channel_to_ami(const char *type, struct stasis_message *message)
1982 {
1983         struct ast_channel_blob *obj = stasis_message_data(message);
1984         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
1985         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
1986
1987         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
1988         event_string = ast_manager_str_from_json_object(obj->blob, NULL);
1989         if (!channel_string || !event_string) {
1990                 return NULL;
1991         }
1992
1993         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
1994                 "%s"
1995                 "%s",
1996                 ast_str_buffer(channel_string),
1997                 ast_str_buffer(event_string));
1998 }
1999
2000 static struct ast_manager_event_blob *queue_caller_join_to_ami(struct stasis_message *message)
2001 {
2002         return queue_channel_to_ami("QueueCallerJoin", message);
2003 }
2004
2005 static struct ast_manager_event_blob *queue_caller_leave_to_ami(struct stasis_message *message)
2006 {
2007         return queue_channel_to_ami("QueueCallerLeave", message);
2008 }
2009
2010 static struct ast_manager_event_blob *queue_caller_abandon_to_ami(struct stasis_message *message)
2011 {
2012         return queue_channel_to_ami("QueueCallerAbandon", message);
2013 }
2014
2015 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_join_type,
2016         .to_ami = queue_caller_join_to_ami,
2017         );
2018 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_leave_type,
2019         .to_ami = queue_caller_leave_to_ami,
2020         );
2021 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_abandon_type,
2022         .to_ami = queue_caller_abandon_to_ami,
2023         );
2024
2025 static struct ast_manager_event_blob *queue_member_to_ami(const char *type, struct stasis_message *message)
2026 {
2027         struct ast_json_payload *payload = stasis_message_data(message);
2028         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
2029
2030         event_string = ast_manager_str_from_json_object(payload->json, NULL);
2031         if (!event_string) {
2032                 return NULL;
2033         }
2034
2035         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
2036                 "%s",
2037                 ast_str_buffer(event_string));
2038 }
2039
2040 static struct ast_manager_event_blob *queue_member_status_to_ami(struct stasis_message *message)
2041 {
2042         return queue_member_to_ami("QueueMemberStatus", message);
2043 }
2044
2045 static struct ast_manager_event_blob *queue_member_added_to_ami(struct stasis_message *message)
2046 {
2047         return queue_member_to_ami("QueueMemberAdded", message);
2048 }
2049
2050 static struct ast_manager_event_blob *queue_member_removed_to_ami(struct stasis_message *message)
2051 {
2052         return queue_member_to_ami("QueueMemberRemoved", message);
2053 }
2054
2055 static struct ast_manager_event_blob *queue_member_pause_to_ami(struct stasis_message *message)
2056 {
2057         return queue_member_to_ami("QueueMemberPause", message);
2058 }
2059
2060 static struct ast_manager_event_blob *queue_member_penalty_to_ami(struct stasis_message *message)
2061 {
2062         return queue_member_to_ami("QueueMemberPenalty", message);
2063 }
2064
2065 static struct ast_manager_event_blob *queue_member_ringinuse_to_ami(struct stasis_message *message)
2066 {
2067         return queue_member_to_ami("QueueMemberRinginuse", message);
2068 }
2069
2070 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_status_type,
2071         .to_ami = queue_member_status_to_ami,
2072         );
2073 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_added_type,
2074         .to_ami = queue_member_added_to_ami,
2075         );
2076 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_removed_type,
2077         .to_ami = queue_member_removed_to_ami,
2078         );
2079 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_pause_type,
2080         .to_ami = queue_member_pause_to_ami,
2081         );
2082 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_penalty_type,
2083         .to_ami = queue_member_penalty_to_ami,
2084         );
2085 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_ringinuse_type,
2086         .to_ami = queue_member_ringinuse_to_ami,
2087         );
2088
2089 static struct ast_manager_event_blob *queue_multi_channel_to_ami(const char *type, struct stasis_message *message)
2090 {
2091         struct ast_multi_channel_blob *obj = stasis_message_data(message);
2092         struct ast_channel_snapshot *caller;
2093         struct ast_channel_snapshot *agent;
2094         RAII_VAR(struct ast_str *, caller_event_string, NULL, ast_free);
2095         RAII_VAR(struct ast_str *, agent_event_string, NULL, ast_free);
2096         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
2097
2098         caller = ast_multi_channel_blob_get_channel(obj, "caller");
2099         if (caller) {
2100                 caller_event_string = ast_manager_build_channel_state_string(caller);
2101                 if (!caller_event_string) {
2102                         ast_log(LOG_NOTICE, "No caller event string, bailing\n");
2103                         return NULL;
2104                 }
2105         }
2106
2107         agent = ast_multi_channel_blob_get_channel(obj, "agent");
2108         if (agent) {
2109                 agent_event_string = ast_manager_build_channel_state_string_prefix(agent, "Dest");
2110                 if (!agent_event_string) {
2111                         ast_log(LOG_NOTICE, "No agent event string, bailing\n");
2112                         return NULL;
2113                 }
2114         }
2115
2116         event_string = ast_manager_str_from_json_object(ast_multi_channel_blob_get_json(obj), NULL);
2117         if (!event_string) {
2118                 return NULL;
2119         }
2120
2121         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
2122                 "%s"
2123                 "%s"
2124                 "%s",
2125                 caller_event_string ? ast_str_buffer(caller_event_string) : "",
2126                 agent_event_string ? ast_str_buffer(agent_event_string) : "",
2127                 ast_str_buffer(event_string));
2128 }
2129
2130 static struct ast_manager_event_blob *queue_agent_called_to_ami(struct stasis_message *message)
2131 {
2132         return queue_multi_channel_to_ami("AgentCalled", message);
2133 }
2134
2135 static struct ast_manager_event_blob *queue_agent_connect_to_ami(struct stasis_message *message)
2136 {
2137         return queue_multi_channel_to_ami("AgentConnect", message);
2138 }
2139
2140 static struct ast_manager_event_blob *queue_agent_complete_to_ami(struct stasis_message *message)
2141 {
2142         return queue_multi_channel_to_ami("AgentComplete", message);
2143 }
2144
2145 static struct ast_manager_event_blob *queue_agent_dump_to_ami(struct stasis_message *message)
2146 {
2147         return queue_multi_channel_to_ami("AgentDump", message);
2148 }
2149
2150 static struct ast_manager_event_blob *queue_agent_ringnoanswer_to_ami(struct stasis_message *message)
2151 {
2152         return queue_multi_channel_to_ami("AgentRingNoAnswer", message);
2153 }
2154
2155 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_called_type,
2156         .to_ami = queue_agent_called_to_ami,
2157         );
2158 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_connect_type,
2159         .to_ami = queue_agent_connect_to_ami,
2160         );
2161 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_complete_type,
2162         .to_ami = queue_agent_complete_to_ami,
2163         );
2164 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_dump_type,
2165         .to_ami = queue_agent_dump_to_ami,
2166         );
2167 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_ringnoanswer_type,
2168         .to_ami = queue_agent_ringnoanswer_to_ami,
2169         );
2170
2171 static void queue_publish_multi_channel_snapshot_blob(struct stasis_topic *topic,
2172                 struct ast_channel_snapshot *caller_snapshot,
2173                 struct ast_channel_snapshot *agent_snapshot,
2174                 struct stasis_message_type *type, struct ast_json *blob)
2175 {
2176         RAII_VAR(struct ast_multi_channel_blob *, payload, NULL, ao2_cleanup);
2177         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2178
2179         if (!type) {
2180                 return;
2181         }
2182
2183         payload = ast_multi_channel_blob_create(blob);
2184         if (!payload) {
2185                 return;
2186         }
2187
2188         if (caller_snapshot) {
2189                 ast_multi_channel_blob_add_channel(payload, "caller", caller_snapshot);
2190         } else {
2191                 ast_debug(1, "Empty caller_snapshot; sending incomplete event\n");
2192         }
2193
2194         if (agent_snapshot) {
2195                 ast_multi_channel_blob_add_channel(payload, "agent", agent_snapshot);
2196         }
2197
2198         msg = stasis_message_create(type, payload);
2199         if (!msg) {
2200                 return;
2201         }
2202
2203         stasis_publish(topic, msg);
2204 }
2205
2206 static void queue_publish_multi_channel_blob(struct ast_channel *caller, struct ast_channel *agent,
2207                 struct stasis_message_type *type, struct ast_json *blob)
2208 {
2209         RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
2210         RAII_VAR(struct ast_channel_snapshot *, agent_snapshot, NULL, ao2_cleanup);
2211
2212         ast_channel_lock(caller);
2213         caller_snapshot = ast_channel_snapshot_create(caller);
2214         ast_channel_unlock(caller);
2215         ast_channel_lock(agent);
2216         agent_snapshot = ast_channel_snapshot_create(agent);
2217         ast_channel_unlock(agent);
2218
2219         if (!caller_snapshot || !agent_snapshot) {
2220                 return;
2221         }
2222
2223         queue_publish_multi_channel_snapshot_blob(ast_channel_topic(caller), caller_snapshot,
2224                         agent_snapshot, type, blob);
2225 }
2226
2227 /*!
2228  * \internal
2229  * \brief Publish the member blob.
2230  * \since 12.0.0
2231  *
2232  * \param type Stasis message type to publish.
2233  * \param blob The information being published.
2234  *
2235  * \note The json blob reference is passed to this function.
2236  *
2237  * \return Nothing
2238  */
2239 static void queue_publish_member_blob(struct stasis_message_type *type, struct ast_json *blob)
2240 {
2241         RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
2242         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2243
2244         if (!blob || !type) {
2245                 ast_json_unref(blob);
2246                 return;
2247         }
2248
2249         payload = ast_json_payload_create(blob);
2250         ast_json_unref(blob);
2251         if (!payload) {
2252                 return;
2253         }
2254
2255         msg = stasis_message_create(type, payload);
2256         if (!msg) {
2257                 return;
2258         }
2259
2260         stasis_publish(ast_manager_get_topic(), msg);
2261 }
2262
2263 static struct ast_json *queue_member_blob_create(struct call_queue *q, struct member *mem)
2264 {
2265         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, s: i, s: s, s: i, s: i}",
2266                 "Queue", q->name,
2267                 "MemberName", mem->membername,
2268                 "Interface", mem->interface,
2269                 "StateInterface", mem->state_interface,
2270                 "Membership", (mem->dynamic ? "dynamic" : (mem->realtime ? "realtime" : "static")),
2271                 "Penalty", mem->penalty,
2272                 "CallsTaken", mem->calls,
2273                 "LastCall", (int)mem->lastcall,
2274                 "LastPause", (int)mem->lastpause,
2275                 "InCall", mem->starttime ? 1 : 0,
2276                 "Status", mem->status,
2277                 "Paused", mem->paused,
2278                 "PausedReason", mem->reason_paused,
2279                 "Ringinuse", mem->ringinuse,
2280                 "Wrapuptime", mem->wrapuptime);
2281 }
2282
2283 /*! \brief Check if members are available
2284  *
2285  * This function checks to see if members are available to be called. If any member
2286  * is available, the function immediately returns 0. If no members are available,
2287  * then -1 is returned.
2288  */
2289 static int get_member_status(struct call_queue *q, int max_penalty, int min_penalty, int raise_penalty, enum empty_conditions conditions, int devstate)
2290 {
2291         struct member *member;
2292         struct ao2_iterator mem_iter;
2293
2294         ao2_lock(q);
2295         mem_iter = ao2_iterator_init(q->members, 0);
2296         for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
2297                 int penalty = member->penalty;
2298                 if (raise_penalty != INT_MAX && penalty < raise_penalty) {
2299                         ast_debug(4, "%s is having his penalty raised up from %d to %d\n", member->membername, penalty, raise_penalty);
2300                         penalty = raise_penalty;
2301                 }
2302                 if ((max_penalty != INT_MAX && penalty > max_penalty) || (min_penalty != INT_MAX && penalty < min_penalty)) {
2303                         if (conditions & QUEUE_EMPTY_PENALTY) {
2304                                 ast_debug(4, "%s is unavailable because his penalty is not between %d and %d\n", member->membername, min_penalty, max_penalty);
2305                                 continue;
2306                         }
2307                 }
2308
2309                 switch (devstate ? ast_device_state(member->state_interface) : member->status) {
2310                 case AST_DEVICE_INVALID:
2311                         if (conditions & QUEUE_EMPTY_INVALID) {
2312                                 ast_debug(4, "%s is unavailable because his device state is 'invalid'\n", member->membername);
2313                                 break;
2314                         }
2315                         goto default_case;
2316                 case AST_DEVICE_UNAVAILABLE:
2317                         if (conditions & QUEUE_EMPTY_UNAVAILABLE) {
2318                                 ast_debug(4, "%s is unavailable because his device state is 'unavailable'\n", member->membername);
2319                                 break;
2320                         }
2321                         goto default_case;
2322                 case AST_DEVICE_INUSE:
2323                         if (conditions & QUEUE_EMPTY_INUSE) {
2324                                 ast_debug(4, "%s is unavailable because his device state is 'inuse'\n", member->membername);
2325                                 break;
2326                         }
2327                         goto default_case;
2328                 case AST_DEVICE_RINGING:
2329                         if (conditions & QUEUE_EMPTY_RINGING) {
2330                                 ast_debug(4, "%s is unavailable because his device state is 'ringing'\n", member->membername);
2331                                 break;
2332                         }
2333                         goto default_case;
2334                 case AST_DEVICE_UNKNOWN:
2335                         if (conditions & QUEUE_EMPTY_UNKNOWN) {
2336                                 ast_debug(4, "%s is unavailable because his device state is 'unknown'\n", member->membername);
2337                                 break;
2338                         }
2339                         /* Fall-through */
2340                 default:
2341                 default_case:
2342                         if (member->paused && (conditions & QUEUE_EMPTY_PAUSED)) {
2343                                 ast_debug(4, "%s is unavailable because he is paused'\n", member->membername);
2344                                 break;
2345                         } else if ((conditions & QUEUE_EMPTY_WRAPUP)
2346                                 && member->lastcall
2347                                 && get_wrapuptime(q, member)
2348                                 && (time(NULL) - get_wrapuptime(q, member) < member->lastcall)) {
2349                                 ast_debug(4, "%s is unavailable because it has only been %d seconds since his last call (wrapup time is %d)\n",
2350                                         member->membername, (int) (time(NULL) - member->lastcall), get_wrapuptime(q, member));
2351                                 break;
2352                         } else {
2353                                 ao2_ref(member, -1);
2354                                 ao2_iterator_destroy(&mem_iter);
2355                                 ao2_unlock(q);
2356                                 ast_debug(4, "%s is available.\n", member->membername);
2357                                 return 0;
2358                         }
2359                         break;
2360                 }
2361         }
2362         ao2_iterator_destroy(&mem_iter);
2363         ao2_unlock(q);
2364
2365         if (!devstate && (conditions & QUEUE_EMPTY_RINGING)) {
2366                 /* member state still may be RINGING due to lag in event message - check again with device state */
2367                 return get_member_status(q, max_penalty, min_penalty, raise_penalty, conditions, 1);
2368         }
2369         return -1;
2370 }
2371
2372 /*
2373  * A "pool" of member objects that calls are currently pending on. If an
2374  * agent is a member of multiple queues it's possible for that agent to be
2375  * called by each of the queues at the same time. This happens because device
2376  * state is slow to notify the queue app of one of it's member's being rung.
2377  * This "pool" allows us to track which members are currently being rung while
2378  * we wait on the device state change.
2379  */
2380 static struct ao2_container *pending_members;
2381 #define MAX_CALL_ATTEMPT_BUCKETS 353
2382
2383 static int pending_members_hash(const void *obj, const int flags)
2384 {
2385         const struct member *object;
2386         const char *key;
2387
2388         switch (flags & OBJ_SEARCH_MASK) {
2389         case OBJ_SEARCH_KEY:
2390                 key = obj;
2391                 break;
2392         case OBJ_SEARCH_OBJECT:
2393                 object = obj;
2394                 key = object->interface;
2395                 break;
2396         default:
2397                 ast_assert(0);
2398                 return 0;
2399         }
2400         return ast_str_case_hash(key);
2401 }
2402
2403 static int pending_members_cmp(void *obj, void *arg, int flags)
2404 {
2405         const struct member *object_left = obj;
2406         const struct member *object_right = arg;
2407         const char *right_key = arg;
2408         int cmp;
2409
2410         switch (flags & OBJ_SEARCH_MASK) {
2411         case OBJ_SEARCH_OBJECT:
2412                 right_key = object_right->interface;
2413                 /* Fall through */
2414         case OBJ_SEARCH_KEY:
2415                 cmp = strcasecmp(object_left->interface, right_key);
2416                 break;
2417         case OBJ_SEARCH_PARTIAL_KEY:
2418                 /* Not supported by container. */
2419                 ast_assert(0);
2420                 return 0;
2421         default:
2422                 cmp = 0;
2423                 break;
2424         }
2425         if (cmp) {
2426                 return 0;
2427         }
2428         return CMP_MATCH;
2429 }
2430
2431 static void pending_members_remove(struct member *mem)
2432 {
2433         ast_debug(3, "Removed %s from pending_members\n", mem->membername);
2434         ao2_find(pending_members, mem, OBJ_POINTER | OBJ_NODATA | OBJ_UNLINK);
2435 }
2436
2437 /*! \brief set a member's status based on device state of that member's state_interface.
2438  *
2439  * Lock interface list find sc, iterate through each queues queue_member list for member to
2440  * update state inside queues
2441 */
2442 static void update_status(struct call_queue *q, struct member *m, const int status)
2443 {
2444         if (m->status != status) {
2445                 /* If this member has transitioned to being available then update their queue
2446                  * information. If they are currently in a call then the leg to the agent will be
2447                  * considered done and the call finished.
2448                  */
2449                 if (status == AST_DEVICE_NOT_INUSE) {
2450                         update_queue(q, m, m->callcompletedinsl, m->starttime);
2451                 }
2452
2453                 m->status = status;
2454
2455                 /* Remove the member from the pending members pool only when the status changes.
2456                  * This is not done unconditionally because we can occasionally see multiple
2457                  * device state notifications of not in use after a previous call has ended,
2458                  * including after we have initiated a new call. This is more likely to
2459                  * happen when there is latency in the connection to the member.
2460                  */
2461                 pending_members_remove(m);
2462         }
2463
2464         queue_publish_member_blob(queue_member_status_type(), queue_member_blob_create(q, m));
2465 }
2466
2467 /*!
2468  * \internal
2469  * \brief Determine if a queue member is available
2470  * \retval 1 if the member is available
2471  * \retval 0 if the member is not available
2472  */
2473 static int is_member_available(struct call_queue *q, struct member *mem)
2474 {
2475         int available = 0;
2476         int wrapuptime;
2477
2478         switch (mem->status) {
2479                 case AST_DEVICE_INVALID:
2480                 case AST_DEVICE_UNAVAILABLE:
2481                         break;
2482                 case AST_DEVICE_INUSE:
2483                 case AST_DEVICE_BUSY:
2484                 case AST_DEVICE_RINGING:
2485                 case AST_DEVICE_RINGINUSE:
2486                 case AST_DEVICE_ONHOLD:
2487                         if (!mem->ringinuse) {
2488                                 break;
2489                         }
2490                         /* else fall through */
2491                 case AST_DEVICE_NOT_INUSE:
2492                 case AST_DEVICE_UNKNOWN:
2493                         if (!mem->paused) {
2494                                 available = 1;
2495                         }
2496                         break;
2497         }
2498
2499         /* Let wrapuptimes override device state availability */
2500         wrapuptime = get_wrapuptime(q, mem);
2501         if (mem->lastcall && wrapuptime && (time(NULL) - wrapuptime < mem->lastcall)) {
2502                 available = 0;
2503         }
2504         return available;
2505 }
2506
2507 /*! \brief set a member's status based on device state of that member's interface*/
2508 static void device_state_cb(void *unused, struct stasis_subscription *sub, struct stasis_message *msg)
2509 {
2510         struct ao2_iterator miter, qiter;
2511         struct ast_device_state_message *dev_state;
2512         struct member *m;
2513         struct call_queue *q;
2514         char interface[80], *slash_pos;
2515         int found = 0;                  /* Found this member in any queue */
2516         int found_member;               /* Found this member in this queue */
2517         int avail = 0;                  /* Found an available member in this queue */
2518
2519         if (ast_device_state_message_type() != stasis_message_type(msg)) {
2520                 return;
2521         }
2522
2523         dev_state = stasis_message_data(msg);
2524         if (dev_state->eid) {
2525                 /* ignore non-aggregate states */
2526                 return;
2527         }
2528
2529         qiter = ao2_iterator_init(queues, 0);
2530         while ((q = ao2_t_iterator_next(&qiter, "Iterate over queues"))) {
2531                 ao2_lock(q);
2532
2533                 avail = 0;
2534                 found_member = 0;
2535                 miter = ao2_iterator_init(q->members, 0);
2536                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
2537                         if (!found_member) {
2538                                 ast_copy_string(interface, m->state_interface, sizeof(interface));
2539
2540                                 if ((slash_pos = strchr(interface, '/'))) {
2541                                         if (!strncasecmp(interface, "Local/", 6) && (slash_pos = strchr(slash_pos + 1, '/'))) {
2542                                                 *slash_pos = '\0';
2543                                         }
2544                                 }
2545
2546                                 if (!strcasecmp(interface, dev_state->device)) {
2547                                         found_member = 1;
2548                                         update_status(q, m, dev_state->state);
2549                                 }
2550                         }
2551
2552                         /* check every member until we find one NOT_INUSE */
2553                         if (!avail) {
2554                                 avail = is_member_available(q, m);
2555                         }
2556                         if (avail && found_member) {
2557                                 /* early exit as we've found an available member and the member of interest */
2558                                 ao2_ref(m, -1);
2559                                 break;
2560                         }
2561                 }
2562
2563                 if (found_member) {
2564                         found = 1;
2565                         if (avail) {
2566                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2567                         } else {
2568                                 ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2569                         }
2570                 }
2571
2572                 ao2_iterator_destroy(&miter);
2573
2574                 ao2_unlock(q);
2575                 queue_t_unref(q, "Done with iterator");
2576         }
2577         ao2_iterator_destroy(&qiter);
2578
2579         if (found) {
2580                 ast_debug(1, "Device '%s' changed to state '%u' (%s)\n",
2581                         dev_state->device,
2582                         dev_state->state,
2583                         ast_devstate2str(dev_state->state));
2584         } else {
2585                 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",
2586                         dev_state->device,
2587                         dev_state->state,
2588                         ast_devstate2str(dev_state->state));
2589         }
2590
2591         return;
2592 }
2593
2594 /*! \brief Helper function which converts from extension state to device state values */
2595 static int extensionstate2devicestate(int state)
2596 {
2597         switch (state) {
2598         case AST_EXTENSION_NOT_INUSE:
2599                 state = AST_DEVICE_NOT_INUSE;
2600                 break;
2601         case AST_EXTENSION_INUSE:
2602                 state = AST_DEVICE_INUSE;
2603                 break;
2604         case AST_EXTENSION_BUSY:
2605                 state = AST_DEVICE_BUSY;
2606                 break;
2607         case AST_EXTENSION_RINGING:
2608                 state = AST_DEVICE_RINGING;
2609                 break;
2610         case AST_EXTENSION_ONHOLD:
2611                 state = AST_DEVICE_ONHOLD;
2612                 break;
2613         case AST_EXTENSION_UNAVAILABLE:
2614                 state = AST_DEVICE_UNAVAILABLE;
2615                 break;
2616         case AST_EXTENSION_REMOVED:
2617         case AST_EXTENSION_DEACTIVATED:
2618         default:
2619                 state = AST_DEVICE_INVALID;
2620                 break;
2621         }
2622
2623         return state;
2624 }
2625
2626 static int extension_state_cb(const char *context, const char *exten, struct ast_state_cb_info *info, void *data)
2627 {
2628         struct ao2_iterator miter, qiter;
2629         struct member *m;
2630         struct call_queue *q;
2631         int state = info->exten_state;
2632         int found = 0, device_state = extensionstate2devicestate(state);
2633
2634         /* only interested in extension state updates involving device states */
2635         if (info->reason != AST_HINT_UPDATE_DEVICE) {
2636                 return 0;
2637         }
2638
2639         qiter = ao2_iterator_init(queues, 0);
2640         while ((q = ao2_t_iterator_next(&qiter, "Iterate through queues"))) {
2641                 ao2_lock(q);
2642
2643                 miter = ao2_iterator_init(q->members, 0);
2644                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
2645                         if (!strcmp(m->state_context, context) && !strcmp(m->state_exten, exten)) {
2646                                 update_status(q, m, device_state);
2647                                 ao2_ref(m, -1);
2648                                 found = 1;
2649                                 break;
2650                         }
2651                 }
2652                 ao2_iterator_destroy(&miter);
2653
2654                 ao2_unlock(q);
2655                 queue_t_unref(q, "Done with iterator");
2656         }
2657         ao2_iterator_destroy(&qiter);
2658
2659         if (found) {
2660                 ast_debug(1, "Extension '%s@%s' changed to state '%d' (%s)\n", exten, context, device_state, ast_devstate2str(device_state));
2661         } else {
2662                 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",
2663                           exten, context, device_state, ast_devstate2str(device_state));
2664         }
2665
2666         return 0;
2667 }
2668
2669 /*! \brief Return the current state of a member */
2670 static int get_queue_member_status(struct member *cur)
2671 {
2672         return ast_strlen_zero(cur->state_exten) ? ast_device_state(cur->state_interface) : extensionstate2devicestate(ast_extension_state(NULL, cur->state_context, cur->state_exten));
2673 }
2674
2675 static void destroy_queue_member_cb(void *obj)
2676 {
2677         struct member *mem = obj;
2678
2679         if (mem->state_id != -1) {
2680                 ast_extension_state_del(mem->state_id, extension_state_cb);
2681         }
2682 }
2683
2684 /*! \brief allocate space for new queue member and set fields based on parameters passed */
2685 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused, const char *state_interface, int ringinuse, int wrapuptime)
2686 {
2687         struct member *cur;
2688
2689         if ((cur = ao2_alloc(sizeof(*cur), destroy_queue_member_cb))) {
2690                 cur->ringinuse = ringinuse;
2691                 cur->penalty = penalty;
2692                 cur->paused = paused;
2693                 cur->wrapuptime = wrapuptime;
2694                 if (paused) {
2695                         time(&cur->lastpause); /* Update time of last pause */
2696                 }
2697                 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
2698                 if (!ast_strlen_zero(state_interface)) {
2699                         ast_copy_string(cur->state_interface, state_interface, sizeof(cur->state_interface));
2700                 } else {
2701                         ast_copy_string(cur->state_interface, interface, sizeof(cur->state_interface));
2702                 }
2703                 if (!ast_strlen_zero(membername)) {
2704                         ast_copy_string(cur->membername, membername, sizeof(cur->membername));
2705                 } else {
2706                         ast_copy_string(cur->membername, interface, sizeof(cur->membername));
2707                 }
2708                 if (!strchr(cur->interface, '/')) {
2709                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
2710                 }
2711                 if (!strncmp(cur->state_interface, "hint:", 5)) {
2712                         char *tmp = ast_strdupa(cur->state_interface), *context = tmp;
2713                         char *exten = strsep(&context, "@") + 5;
2714
2715                         ast_copy_string(cur->state_exten, exten, sizeof(cur->state_exten));
2716                         ast_copy_string(cur->state_context, S_OR(context, "default"), sizeof(cur->state_context));
2717
2718                         cur->state_id = ast_extension_state_add(cur->state_context, cur->state_exten, extension_state_cb, NULL);
2719                 } else {
2720                         cur->state_id = -1;
2721                 }
2722                 cur->status = get_queue_member_status(cur);
2723         }
2724
2725         return cur;
2726 }
2727
2728
2729 static int compress_char(const char c)
2730 {
2731         if (c < 32) {
2732                 return 0;
2733         } else if (c > 96) {
2734                 return c - 64;
2735         }
2736         return c - 32;
2737 }
2738
2739 static int member_hash_fn(const void *obj, const int flags)
2740 {
2741         const struct member *mem = obj;
2742         const char *interface = (flags & OBJ_KEY) ? obj : mem->interface;
2743         const char *chname = strchr(interface, '/');
2744         int ret = 0, i;
2745
2746         if (!chname) {
2747                 chname = interface;
2748         }
2749         for (i = 0; i < 5 && chname[i]; i++) {
2750                 ret += compress_char(chname[i]) << (i * 6);
2751         }
2752         return ret;
2753 }
2754
2755 static int member_cmp_fn(void *obj1, void *obj2, int flags)
2756 {
2757         struct member *mem1 = obj1;
2758         struct member *mem2 = obj2;
2759         const char *interface = (flags & OBJ_KEY) ? obj2 : mem2->interface;
2760
2761         return strcasecmp(mem1->interface, interface) ? 0 : CMP_MATCH | CMP_STOP;
2762 }
2763
2764 /*!
2765  * \brief Initialize Queue default values.
2766  * \note the queue's lock  must be held before executing this function
2767 */
2768 static void init_queue(struct call_queue *q)
2769 {
2770         int i;
2771         struct penalty_rule *pr_iter;
2772
2773         q->dead = 0;
2774         q->retry = DEFAULT_RETRY;
2775         q->timeout = DEFAULT_TIMEOUT;
2776         q->maxlen = 0;
2777
2778         ast_string_field_set(q, context, "");
2779
2780         q->announcefrequency = 0;
2781         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
2782         q->announceholdtime = 1;
2783         q->announceposition_only_up = 0;
2784         q->announcepositionlimit = 10; /* Default 10 positions */
2785         q->announceposition = ANNOUNCEPOSITION_YES; /* Default yes */
2786         q->roundingseconds = 0; /* Default - don't announce seconds */
2787         q->servicelevel = 0;
2788         q->ringinuse = 1;
2789         q->announce_to_first_user = 0;
2790         q->setinterfacevar = 0;
2791         q->setqueuevar = 0;
2792         q->setqueueentryvar = 0;
2793         q->autofill = autofill_default;
2794         q->montype = montype_default;
2795         q->monfmt[0] = '\0';
2796         q->reportholdtime = 0;
2797         q->wrapuptime = 0;
2798         q->penaltymemberslimit = 0;
2799         q->joinempty = 0;
2800         q->leavewhenempty = 0;
2801         q->memberdelay = 0;
2802         q->weight = 0;
2803         q->timeoutrestart = 0;
2804         q->periodicannouncefrequency = 0;
2805         q->randomperiodicannounce = 0;
2806         q->numperiodicannounce = 0;
2807         q->autopause = QUEUE_AUTOPAUSE_OFF;
2808         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
2809         q->autopausedelay = 0;
2810         if (!q->members) {
2811            &