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