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