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