app_queue.c: remove include for core_unreal.h not used in code.
[asterisk/asterisk.git] / apps / app_queue.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2015, 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="InCall">
1026                                         <para>Set to 1 if member is in call. Set to 0 after LastCall time is updated.</para>
1027                                         <enumlist>
1028                                                 <enum name="0"/>
1029                                                 <enum name="1"/>
1030                                         </enumlist>
1031                                 </parameter>
1032                                 <parameter name="Status">
1033                                         <para>The numeric device state status of the queue member.</para>
1034                                         <enumlist>
1035                                                 <enum name="0"><para>AST_DEVICE_UNKNOWN</para></enum>
1036                                                 <enum name="1"><para>AST_DEVICE_NOT_INUSE</para></enum>
1037                                                 <enum name="2"><para>AST_DEVICE_INUSE</para></enum>
1038                                                 <enum name="3"><para>AST_DEVICE_BUSY</para></enum>
1039                                                 <enum name="4"><para>AST_DEVICE_INVALID</para></enum>
1040                                                 <enum name="5"><para>AST_DEVICE_UNAVAILABLE</para></enum>
1041                                                 <enum name="6"><para>AST_DEVICE_RINGING</para></enum>
1042                                                 <enum name="7"><para>AST_DEVICE_RINGINUSE</para></enum>
1043                                                 <enum name="8"><para>AST_DEVICE_ONHOLD</para></enum>
1044                                         </enumlist>
1045                                 </parameter>
1046                                 <parameter name="Paused">
1047                                         <enumlist>
1048                                                 <enum name="0"/>
1049                                                 <enum name="1"/>
1050                                         </enumlist>
1051                                 </parameter>
1052                                 <parameter name="PausedReason">
1053                                         <para>If set when paused, the reason the queue member was paused.</para>
1054                                 </parameter>
1055                                 <parameter name="Ringinuse">
1056                                         <enumlist>
1057                                                 <enum name="0"/>
1058                                                 <enum name="1"/>
1059                                         </enumlist>
1060                                 </parameter>
1061                         </syntax>
1062                 </managerEventInstance>
1063         </managerEvent>
1064         <managerEvent language="en_US" name="QueueMemberAdded">
1065                 <managerEventInstance class="EVENT_FLAG_AGENT">
1066                         <synopsis>Raised when a member is added to the queue.</synopsis>
1067                         <syntax>
1068                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1069                         </syntax>
1070                         <see-also>
1071                                 <ref type="managerEvent">QueueMemberRemoved</ref>
1072                                 <ref type="application">AddQueueMember</ref>
1073                         </see-also>
1074                 </managerEventInstance>
1075         </managerEvent>
1076         <managerEvent language="en_US" name="QueueMemberRemoved">
1077                 <managerEventInstance class="EVENT_FLAG_AGENT">
1078                         <synopsis>Raised when a member is removed from the queue.</synopsis>
1079                         <syntax>
1080                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1081                         </syntax>
1082                         <see-also>
1083                                 <ref type="managerEvent">QueueMemberAdded</ref>
1084                                 <ref type="application">RemoveQueueMember</ref>
1085                         </see-also>
1086                 </managerEventInstance>
1087         </managerEvent>
1088         <managerEvent language="en_US" name="QueueMemberPause">
1089                 <managerEventInstance class="EVENT_FLAG_AGENT">
1090                         <synopsis>Raised when a member is paused/unpaused in the queue.</synopsis>
1091                         <syntax>
1092                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1093                                 <parameter name="Reason">
1094                                         <para>The reason a member was paused.</para>
1095                                 </parameter>
1096                         </syntax>
1097                         <see-also>
1098                                 <ref type="application">PauseQueueMember</ref>
1099                                 <ref type="application">UnPauseQueueMember</ref>
1100                         </see-also>
1101                 </managerEventInstance>
1102         </managerEvent>
1103         <managerEvent language="en_US" name="QueueMemberPenalty">
1104                 <managerEventInstance class="EVENT_FLAG_AGENT">
1105                         <synopsis>Raised when a member's penalty is changed.</synopsis>
1106                         <syntax>
1107                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1108                         </syntax>
1109                         <see-also>
1110                                 <ref type="function">QUEUE_MEMBER</ref>
1111                         </see-also>
1112                 </managerEventInstance>
1113         </managerEvent>
1114         <managerEvent language="en_US" name="QueueMemberRinginuse">
1115                 <managerEventInstance class="EVENT_FLAG_AGENT">
1116                         <synopsis>Raised when a member's ringinuse setting is changed.</synopsis>
1117                         <syntax>
1118                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1119                         </syntax>
1120                         <see-also>
1121                                 <ref type="function">QUEUE_MEMBER</ref>
1122                         </see-also>
1123                 </managerEventInstance>
1124         </managerEvent>
1125         <managerEvent language="en_US" name="QueueCallerJoin">
1126                 <managerEventInstance class="EVENT_FLAG_AGENT">
1127                         <synopsis>Raised when a caller joins a Queue.</synopsis>
1128                         <syntax>
1129                                 <channel_snapshot/>
1130                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1131                                 <parameter name="Position">
1132                                         <para>This channel's current position in the queue.</para>
1133                                 </parameter>
1134                                 <parameter name="Count">
1135                                         <para>The total number of channels in the queue.</para>
1136                                 </parameter>
1137                         </syntax>
1138                         <see-also>
1139                                 <ref type="managerEvent">QueueCallerLeave</ref>
1140                                 <ref type="application">Queue</ref>
1141                         </see-also>
1142                 </managerEventInstance>
1143         </managerEvent>
1144         <managerEvent language="en_US" name="QueueCallerLeave">
1145                 <managerEventInstance class="EVENT_FLAG_AGENT">
1146                         <synopsis>Raised when a caller leaves a Queue.</synopsis>
1147                         <syntax>
1148                                 <channel_snapshot/>
1149                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1150                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Count'])" />
1151                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Position'])" />
1152                         </syntax>
1153                         <see-also>
1154                                 <ref type="managerEvent">QueueCallerJoin</ref>
1155                         </see-also>
1156                 </managerEventInstance>
1157         </managerEvent>
1158         <managerEvent language="en_US" name="QueueCallerAbandon">
1159                 <managerEventInstance class="EVENT_FLAG_AGENT">
1160                         <synopsis>Raised when a caller abandons the queue.</synopsis>
1161                         <syntax>
1162                                 <channel_snapshot/>
1163                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1164                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Position'])" />
1165                                 <parameter name="OriginalPosition">
1166                                         <para>The channel's original position in the queue.</para>
1167                                 </parameter>
1168                                 <parameter name="HoldTime">
1169                                         <para>The time the channel was in the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1170                                 </parameter>
1171                         </syntax>
1172                 </managerEventInstance>
1173         </managerEvent>
1174         <managerEvent language="en_US" name="AgentCalled">
1175                 <managerEventInstance class="EVENT_FLAG_AGENT">
1176                         <synopsis>Raised when an queue member is notified of a caller in the queue.</synopsis>
1177                         <syntax>
1178                                 <channel_snapshot/>
1179                                 <channel_snapshot prefix="Dest"/>
1180                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1181                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1182                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1183                         </syntax>
1184                         <see-also>
1185                                 <ref type="managerEvent">AgentRingNoAnswer</ref>
1186                                 <ref type="managerEvent">AgentComplete</ref>
1187                                 <ref type="managerEvent">AgentConnect</ref>
1188                         </see-also>
1189                 </managerEventInstance>
1190         </managerEvent>
1191         <managerEvent language="en_US" name="AgentRingNoAnswer">
1192                 <managerEventInstance class="EVENT_FLAG_AGENT">
1193                         <synopsis>Raised when a queue member is notified of a caller in the queue and fails to answer.</synopsis>
1194                         <syntax>
1195                                 <channel_snapshot/>
1196                                 <channel_snapshot prefix="Dest"/>
1197                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1198                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1199                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1200                                 <parameter name="RingTime">
1201                                         <para>The time the queue member was rung, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1202                                 </parameter>
1203                         </syntax>
1204                         <see-also>
1205                                 <ref type="managerEvent">AgentCalled</ref>
1206                         </see-also>
1207                 </managerEventInstance>
1208         </managerEvent>
1209         <managerEvent language="en_US" name="AgentComplete">
1210                 <managerEventInstance class="EVENT_FLAG_AGENT">
1211                         <synopsis>Raised when a queue member has finished servicing a caller in the queue.</synopsis>
1212                         <syntax>
1213                                 <channel_snapshot/>
1214                                 <channel_snapshot prefix="Dest"/>
1215                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1216                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1217                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1218                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerAbandon']/managerEventInstance/syntax/parameter[@name='HoldTime'])" />
1219                                 <parameter name="TalkTime">
1220                                         <para>The time the queue member talked with the caller in the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1221                                 </parameter>
1222                                 <parameter name="Reason">
1223                                         <enumlist>
1224                                                 <enum name="caller"/>
1225                                                 <enum name="agent"/>
1226                                                 <enum name="transfer"/>
1227                                         </enumlist>
1228                                 </parameter>
1229                         </syntax>
1230                         <see-also>
1231                                 <ref type="managerEvent">AgentCalled</ref>
1232                                 <ref type="managerEvent">AgentConnect</ref>
1233                         </see-also>
1234                 </managerEventInstance>
1235         </managerEvent>
1236         <managerEvent language="en_US" name="AgentDump">
1237                 <managerEventInstance class="EVENT_FLAG_AGENT">
1238                         <synopsis>Raised when a queue member hangs up on a caller in the queue.</synopsis>
1239                         <syntax>
1240                                 <channel_snapshot/>
1241                                 <channel_snapshot prefix="Dest"/>
1242                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1243                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1244                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1245                         </syntax>
1246                         <see-also>
1247                                 <ref type="managerEvent">AgentCalled</ref>
1248                                 <ref type="managerEvent">AgentConnect</ref>
1249                         </see-also>
1250                 </managerEventInstance>
1251         </managerEvent>
1252         <managerEvent language="en_US" name="AgentConnect">
1253                 <managerEventInstance class="EVENT_FLAG_AGENT">
1254                         <synopsis>Raised when a queue member answers and is bridged to a caller in the queue.</synopsis>
1255                         <syntax>
1256                                 <channel_snapshot/>
1257                                 <channel_snapshot prefix="Dest"/>
1258                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1259                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1260                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1261                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='AgentRingNoAnswer']/managerEventInstance/syntax/parameter[@name='RingTime'])" />
1262                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerAbandon']/managerEventInstance/syntax/parameter[@name='HoldTime'])" />
1263                         </syntax>
1264                         <see-also>
1265                                 <ref type="managerEvent">AgentCalled</ref>
1266                                 <ref type="managerEvent">AgentComplete</ref>
1267                                 <ref type="managerEvent">AgentDump</ref>
1268                         </see-also>
1269                 </managerEventInstance>
1270         </managerEvent>
1271  ***/
1272
1273 enum {
1274         OPT_MARK_AS_ANSWERED =       (1 << 0),
1275         OPT_GO_ON =                  (1 << 1),
1276         OPT_DATA_QUALITY =           (1 << 2),
1277         OPT_CALLEE_GO_ON =           (1 << 3),
1278         OPT_CALLEE_HANGUP =          (1 << 4),
1279         OPT_CALLER_HANGUP =          (1 << 5),
1280         OPT_IGNORE_CALL_FW =         (1 << 6),
1281         OPT_IGNORE_CONNECTEDLINE =   (1 << 7),
1282         OPT_CALLEE_PARK =            (1 << 8),
1283         OPT_CALLER_PARK =            (1 << 9),
1284         OPT_NO_RETRY =               (1 << 10),
1285         OPT_RINGING =                (1 << 11),
1286         OPT_RING_WHEN_RINGING =      (1 << 12),
1287         OPT_CALLEE_TRANSFER =        (1 << 13),
1288         OPT_CALLER_TRANSFER =        (1 << 14),
1289         OPT_CALLEE_AUTOMIXMON =      (1 << 15),
1290         OPT_CALLER_AUTOMIXMON =      (1 << 16),
1291         OPT_CALLEE_AUTOMON =         (1 << 17),
1292         OPT_CALLER_AUTOMON =         (1 << 18),
1293 };
1294
1295 enum {
1296         OPT_ARG_CALLEE_GO_ON = 0,
1297         /* note: this entry _MUST_ be the last one in the enum */
1298         OPT_ARG_ARRAY_SIZE
1299 };
1300
1301 AST_APP_OPTIONS(queue_exec_options, BEGIN_OPTIONS
1302         AST_APP_OPTION('C', OPT_MARK_AS_ANSWERED),
1303         AST_APP_OPTION('c', OPT_GO_ON),
1304         AST_APP_OPTION('d', OPT_DATA_QUALITY),
1305         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
1306         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
1307         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
1308         AST_APP_OPTION('i', OPT_IGNORE_CALL_FW),
1309         AST_APP_OPTION('I', OPT_IGNORE_CONNECTEDLINE),
1310         AST_APP_OPTION('k', OPT_CALLEE_PARK),
1311         AST_APP_OPTION('K', OPT_CALLER_PARK),
1312         AST_APP_OPTION('n', OPT_NO_RETRY),
1313         AST_APP_OPTION('r', OPT_RINGING),
1314         AST_APP_OPTION('R', OPT_RING_WHEN_RINGING),
1315         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
1316         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
1317         AST_APP_OPTION('x', OPT_CALLEE_AUTOMIXMON),
1318         AST_APP_OPTION('X', OPT_CALLER_AUTOMIXMON),
1319         AST_APP_OPTION('w', OPT_CALLEE_AUTOMON),
1320         AST_APP_OPTION('W', OPT_CALLER_AUTOMON),
1321 END_OPTIONS);
1322
1323 enum {
1324         QUEUE_STRATEGY_RINGALL = 0,
1325         QUEUE_STRATEGY_LEASTRECENT,
1326         QUEUE_STRATEGY_FEWESTCALLS,
1327         QUEUE_STRATEGY_RANDOM,
1328         QUEUE_STRATEGY_RRMEMORY,
1329         QUEUE_STRATEGY_LINEAR,
1330         QUEUE_STRATEGY_WRANDOM,
1331         QUEUE_STRATEGY_RRORDERED,
1332 };
1333
1334 enum {
1335      QUEUE_AUTOPAUSE_OFF = 0,
1336      QUEUE_AUTOPAUSE_ON,
1337      QUEUE_AUTOPAUSE_ALL
1338 };
1339
1340 enum queue_reload_mask {
1341         QUEUE_RELOAD_PARAMETERS = (1 << 0),
1342         QUEUE_RELOAD_MEMBER = (1 << 1),
1343         QUEUE_RELOAD_RULES = (1 << 2),
1344         QUEUE_RESET_STATS = (1 << 3),
1345 };
1346
1347 static const struct strategy {
1348         int strategy;
1349         const char *name;
1350 } strategies[] = {
1351         { QUEUE_STRATEGY_RINGALL, "ringall" },
1352         { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
1353         { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
1354         { QUEUE_STRATEGY_RANDOM, "random" },
1355         { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
1356         { QUEUE_STRATEGY_RRMEMORY, "roundrobin" },
1357         { QUEUE_STRATEGY_LINEAR, "linear" },
1358         { QUEUE_STRATEGY_WRANDOM, "wrandom"},
1359         { QUEUE_STRATEGY_RRORDERED, "rrordered"},
1360 };
1361
1362 static const struct autopause {
1363         int autopause;
1364         const char *name;
1365 } autopausesmodes [] = {
1366         { QUEUE_AUTOPAUSE_OFF,"no" },
1367         { QUEUE_AUTOPAUSE_ON, "yes" },
1368         { QUEUE_AUTOPAUSE_ALL,"all" },
1369 };
1370
1371 #define DEFAULT_RETRY           5
1372 #define DEFAULT_TIMEOUT         15
1373 #define RECHECK                 1               /*!< Recheck every second to see we we're at the top yet */
1374 #define MAX_PERIODIC_ANNOUNCEMENTS 10           /*!< The maximum periodic announcements we can have */
1375 /*!
1376  * \brief The minimum number of seconds between position announcements.
1377  * \note The default value of 15 provides backwards compatibility.
1378  */
1379 #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15
1380
1381 #define MAX_QUEUE_BUCKETS 53
1382
1383 #define RES_OKAY        0               /*!< Action completed */
1384 #define RES_EXISTS      (-1)            /*!< Entry already exists */
1385 #define RES_OUTOFMEMORY (-2)            /*!< Out of memory */
1386 #define RES_NOSUCHQUEUE (-3)            /*!< No such queue */
1387 #define RES_NOT_DYNAMIC (-4)            /*!< Member is not dynamic */
1388
1389 static char *app = "Queue";
1390
1391 static char *app_aqm = "AddQueueMember" ;
1392
1393 static char *app_rqm = "RemoveQueueMember" ;
1394
1395 static char *app_pqm = "PauseQueueMember" ;
1396
1397 static char *app_upqm = "UnpauseQueueMember" ;
1398
1399 static char *app_ql = "QueueLog" ;
1400
1401 /*! \brief Persistent Members astdb family */
1402 static const char * const pm_family = "Queue/PersistentMembers";
1403
1404 /*! \brief queues.conf [general] option */
1405 static int queue_persistent_members = 0;
1406
1407 /*! \brief queues.conf per-queue weight option */
1408 static int use_weight = 0;
1409
1410 /*! \brief queues.conf [general] option */
1411 static int autofill_default = 1;
1412
1413 /*! \brief queues.conf [general] option */
1414 static int montype_default = 0;
1415
1416 /*! \brief queues.conf [general] option */
1417 static int shared_lastcall = 1;
1418
1419 /*! \brief queuesrules.conf [general] option */
1420 static int realtime_rules = 0;
1421
1422 /*! \brief Subscription to device state change messages */
1423 static struct stasis_subscription *device_state_sub;
1424
1425 /*! \brief queues.conf [general] option */
1426 static int update_cdr = 0;
1427
1428 /*! \brief queues.conf [general] option */
1429 static int negative_penalty_invalid = 0;
1430
1431 /*! \brief queues.conf [general] option */
1432 static int log_membername_as_agent = 0;
1433
1434 /*! \brief name of the ringinuse field in the realtime database */
1435 static char *realtime_ringinuse_field;
1436
1437 enum queue_result {
1438         QUEUE_UNKNOWN = 0,
1439         QUEUE_TIMEOUT = 1,
1440         QUEUE_JOINEMPTY = 2,
1441         QUEUE_LEAVEEMPTY = 3,
1442         QUEUE_JOINUNAVAIL = 4,
1443         QUEUE_LEAVEUNAVAIL = 5,
1444         QUEUE_FULL = 6,
1445         QUEUE_CONTINUE = 7,
1446 };
1447
1448 static const struct {
1449         enum queue_result id;
1450         char *text;
1451 } queue_results[] = {
1452         { QUEUE_UNKNOWN, "UNKNOWN" },
1453         { QUEUE_TIMEOUT, "TIMEOUT" },
1454         { QUEUE_JOINEMPTY,"JOINEMPTY" },
1455         { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
1456         { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
1457         { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
1458         { QUEUE_FULL, "FULL" },
1459         { QUEUE_CONTINUE, "CONTINUE" },
1460 };
1461
1462 enum queue_timeout_priority {
1463         TIMEOUT_PRIORITY_APP,
1464         TIMEOUT_PRIORITY_CONF,
1465 };
1466
1467 /*! \brief We define a custom "local user" structure because we
1468  *  use it not only for keeping track of what is in use but
1469  *  also for keeping track of who we're dialing.
1470  *
1471  *  There are two "links" defined in this structure, q_next and call_next.
1472  *  q_next links ALL defined callattempt structures into a linked list. call_next is
1473  *  a link which allows for a subset of the callattempts to be traversed. This subset
1474  *  is used in wait_for_answer so that irrelevant callattempts are not traversed. This
1475  *  also is helpful so that queue logs are always accurate in the case where a call to
1476  *  a member times out, especially if using the ringall strategy.
1477 */
1478
1479 struct callattempt {
1480         struct callattempt *q_next;
1481         struct callattempt *call_next;
1482         struct ast_channel *chan;
1483         char interface[256];                    /*!< An Asterisk dial string (not a channel name) */
1484         int metric;
1485         time_t lastcall;
1486         struct call_queue *lastqueue;
1487         struct member *member;
1488         /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
1489         struct ast_party_connected_line connected;
1490         /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
1491         unsigned int pending_connected_update:1;
1492         /*! TRUE if the connected line update is blocked. */
1493         unsigned int block_connected_update:1;
1494         /*! TRUE if caller id is not available for connected line */
1495         unsigned int dial_callerid_absent:1;
1496         /*! TRUE if the call is still active */
1497         unsigned int stillgoing:1;
1498         struct ast_aoc_decoded *aoc_s_rate_list;
1499         /*! Original channel name.  Must be freed.  Could be NULL if allocation failed. */
1500         char *orig_chan_name;
1501 };
1502
1503
1504 struct queue_ent {
1505         struct call_queue *parent;             /*!< What queue is our parent */
1506         char moh[MAX_MUSICCLASS];              /*!< Name of musiconhold to be used */
1507         char announce[PATH_MAX];               /*!< Announcement to play for member when call is answered */
1508         char context[AST_MAX_CONTEXT];         /*!< Context when user exits queue */
1509         char digits[AST_MAX_EXTENSION];        /*!< Digits entered while in queue */
1510         int valid_digits;                      /*!< Digits entered correspond to valid extension. Exited */
1511         int pos;                               /*!< Where we are in the queue */
1512         int prio;                              /*!< Our priority */
1513         int last_pos_said;                     /*!< Last position we told the user */
1514         int ring_when_ringing;                 /*!< Should we only use ring indication when a channel is ringing? */
1515         time_t last_periodic_announce_time;    /*!< The last time we played a periodic announcement */
1516         int last_periodic_announce_sound;      /*!< The last periodic announcement we made */
1517         time_t last_pos;                       /*!< Last time we told the user their position */
1518         int opos;                              /*!< Where we started in the queue */
1519         int handled;                           /*!< Whether our call was handled */
1520         int pending;                           /*!< Non-zero if we are attempting to call a member */
1521         int max_penalty;                       /*!< Limit the members that can take this call to this penalty or lower */
1522         int min_penalty;                       /*!< Limit the members that can take this call to this penalty or higher */
1523         int linpos;                            /*!< If using linear strategy, what position are we at? */
1524         int linwrapped;                        /*!< Is the linpos wrapped? */
1525         time_t start;                          /*!< When we started holding */
1526         time_t expire;                         /*!< When this entry should expire (time out of queue) */
1527         int cancel_answered_elsewhere;         /*!< Whether we should force the CAE flag on this call (C) option*/
1528         struct ast_channel *chan;              /*!< Our channel */
1529         AST_LIST_HEAD_NOLOCK(,penalty_rule) qe_rules; /*!< Local copy of the queue's penalty rules */
1530         struct penalty_rule *pr;               /*!< Pointer to the next penalty rule to implement */
1531         struct queue_ent *next;                /*!< The next queue entry */
1532 };
1533
1534 struct member {
1535         char interface[AST_CHANNEL_NAME];    /*!< Technology/Location to dial to reach this member*/
1536         char state_exten[AST_MAX_EXTENSION]; /*!< Extension to get state from (if using hint) */
1537         char state_context[AST_MAX_CONTEXT]; /*!< Context to use when getting state (if using hint) */
1538         char state_interface[AST_CHANNEL_NAME]; /*!< Technology/Location from which to read devicestate changes */
1539         char membername[80];                 /*!< Member name to use in queue logs */
1540         int penalty;                         /*!< Are we a last resort? */
1541         int calls;                           /*!< Number of calls serviced by this member */
1542         int dynamic;                         /*!< Are we dynamically added? */
1543         int realtime;                        /*!< Is this member realtime? */
1544         int status;                          /*!< Status of queue member */
1545         int paused;                          /*!< Are we paused (not accepting calls)? */
1546         char reason_paused[80];              /*!< Reason of paused if member is paused */
1547         int queuepos;                        /*!< In what order (pertains to certain strategies) should this member be called? */
1548         time_t lastcall;                     /*!< When last successful call was hungup */
1549         unsigned int in_call:1;              /*!< True if member is still in call. (so lastcall is not actual) */
1550         struct call_queue *lastqueue;        /*!< Last queue we received a call */
1551         unsigned int dead:1;                 /*!< Used to detect members deleted in realtime */
1552         unsigned int delme:1;                /*!< Flag to delete entry on reload */
1553         unsigned int call_pending:1;         /*!< TRUE if the Q is attempting to place a call to the member. */
1554         char rt_uniqueid[80];                /*!< Unique id of realtime member entry */
1555         unsigned int ringinuse:1;            /*!< Flag to ring queue members even if their status is 'inuse' */
1556 };
1557
1558 enum empty_conditions {
1559         QUEUE_EMPTY_PENALTY = (1 << 0),
1560         QUEUE_EMPTY_PAUSED = (1 << 1),
1561         QUEUE_EMPTY_INUSE = (1 << 2),
1562         QUEUE_EMPTY_RINGING = (1 << 3),
1563         QUEUE_EMPTY_UNAVAILABLE = (1 << 4),
1564         QUEUE_EMPTY_INVALID = (1 << 5),
1565         QUEUE_EMPTY_UNKNOWN = (1 << 6),
1566         QUEUE_EMPTY_WRAPUP = (1 << 7),
1567 };
1568
1569 enum member_properties {
1570         MEMBER_PENALTY = 0,
1571         MEMBER_RINGINUSE = 1,
1572 };
1573
1574 /* values used in multi-bit flags in call_queue */
1575 #define ANNOUNCEHOLDTIME_ALWAYS 1
1576 #define ANNOUNCEHOLDTIME_ONCE 2
1577 #define QUEUE_EVENT_VARIABLES 3
1578
1579 struct penalty_rule {
1580         int time;                           /*!< Number of seconds that need to pass before applying this rule */
1581         int max_value;                      /*!< The amount specified in the penalty rule for max penalty */
1582         int min_value;                      /*!< The amount specified in the penalty rule for min penalty */
1583         int max_relative;                   /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
1584         int min_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1585         AST_LIST_ENTRY(penalty_rule) list;  /*!< Next penalty_rule */
1586 };
1587
1588 #define ANNOUNCEPOSITION_YES 1 /*!< We announce position */
1589 #define ANNOUNCEPOSITION_NO 2 /*!< We don't announce position */
1590 #define ANNOUNCEPOSITION_MORE_THAN 3 /*!< We say "Currently there are more than <limit>" */
1591 #define ANNOUNCEPOSITION_LIMIT 4 /*!< We not announce position more than <limit> */
1592
1593 struct call_queue {
1594         AST_DECLARE_STRING_FIELDS(
1595                 /*! Queue name */
1596                 AST_STRING_FIELD(name);
1597                 /*! Music on Hold class */
1598                 AST_STRING_FIELD(moh);
1599                 /*! Announcement to play when call is answered */
1600                 AST_STRING_FIELD(announce);
1601                 /*! Exit context */
1602                 AST_STRING_FIELD(context);
1603                 /*! Macro to run upon member connection */
1604                 AST_STRING_FIELD(membermacro);
1605                 /*! Gosub to run upon member connection */
1606                 AST_STRING_FIELD(membergosub);
1607                 /*! Default rule to use if none specified in call to Queue() */
1608                 AST_STRING_FIELD(defaultrule);
1609                 /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
1610                 AST_STRING_FIELD(sound_next);
1611                 /*! Sound file: "There are currently" (def. queue-thereare) */
1612                 AST_STRING_FIELD(sound_thereare);
1613                 /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
1614                 AST_STRING_FIELD(sound_calls);
1615                 /*! Sound file: "Currently there are more than" (def. queue-quantity1) */
1616                 AST_STRING_FIELD(queue_quantity1);
1617                 /*! Sound file: "callers waiting to speak with a representative" (def. queue-quantity2) */
1618                 AST_STRING_FIELD(queue_quantity2);
1619                 /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
1620                 AST_STRING_FIELD(sound_holdtime);
1621                 /*! Sound file: "minutes." (def. queue-minutes) */
1622                 AST_STRING_FIELD(sound_minutes);
1623                 /*! Sound file: "minute." (def. queue-minute) */
1624                 AST_STRING_FIELD(sound_minute);
1625                 /*! Sound file: "seconds." (def. queue-seconds) */
1626                 AST_STRING_FIELD(sound_seconds);
1627                 /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
1628                 AST_STRING_FIELD(sound_thanks);
1629                 /*! Sound file: Custom announce for caller, no default */
1630                 AST_STRING_FIELD(sound_callerannounce);
1631                 /*! Sound file: "Hold time" (def. queue-reporthold) */
1632                 AST_STRING_FIELD(sound_reporthold);
1633         );
1634         /*! Sound files: Custom announce, no default */
1635         struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
1636         unsigned int dead:1;
1637         unsigned int ringinuse:1;
1638         unsigned int announce_to_first_user:1; /*!< Whether or not we announce to the first user in a queue */
1639         unsigned int setinterfacevar:1;
1640         unsigned int setqueuevar:1;
1641         unsigned int setqueueentryvar:1;
1642         unsigned int reportholdtime:1;
1643         unsigned int wrapped:1;
1644         unsigned int timeoutrestart:1;
1645         unsigned int announceholdtime:2;
1646         unsigned int announceposition:3;
1647         int strategy:4;
1648         unsigned int realtime:1;
1649         unsigned int found:1;
1650         unsigned int relativeperiodicannounce:1;
1651         unsigned int autopausebusy:1;
1652         unsigned int autopauseunavail:1;
1653         enum empty_conditions joinempty;
1654         enum empty_conditions leavewhenempty;
1655         int announcepositionlimit;          /*!< How many positions we announce? */
1656         int announcefrequency;              /*!< How often to announce their position */
1657         int minannouncefrequency;           /*!< The minimum number of seconds between position announcements (def. 15) */
1658         int periodicannouncefrequency;      /*!< How often to play periodic announcement */
1659         int numperiodicannounce;            /*!< The number of periodic announcements configured */
1660         int randomperiodicannounce;         /*!< Are periodic announcments randomly chosen */
1661         int roundingseconds;                /*!< How many seconds do we round to? */
1662         int holdtime;                       /*!< Current avg holdtime, based on an exponential average */
1663         int talktime;                       /*!< Current avg talktime, based on the same exponential average */
1664         int callscompleted;                 /*!< Number of queue calls completed */
1665         int callsabandoned;                 /*!< Number of queue calls abandoned */
1666         int servicelevel;                   /*!< seconds setting for servicelevel*/
1667         int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
1668         char monfmt[8];                     /*!< Format to use when recording calls */
1669         int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
1670         int count;                          /*!< How many entries */
1671         int maxlen;                         /*!< Max number of entries */
1672         int wrapuptime;                     /*!< Wrapup Time */
1673         int penaltymemberslimit;            /*!< Disregard penalty when queue has fewer than this many members */
1674
1675         int retry;                          /*!< Retry calling everyone after this amount of time */
1676         int timeout;                        /*!< How long to wait for an answer */
1677         int weight;                         /*!< Respective weight */
1678         int autopause;                      /*!< Auto pause queue members if they fail to answer */
1679         int autopausedelay;                 /*!< Delay auto pause for autopausedelay seconds since last call */
1680         int timeoutpriority;                /*!< Do we allow a fraction of the timeout to occur for a ring? */
1681
1682         /* Queue strategy things */
1683         int rrpos;                          /*!< Round Robin - position */
1684         int memberdelay;                    /*!< Seconds to delay connecting member to caller */
1685         int autofill;                       /*!< Ignore the head call status and ring an available agent */
1686
1687         struct ao2_container *members;             /*!< Head of the list of members */
1688         struct queue_ent *head;             /*!< Head of the list of callers */
1689         AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
1690         AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
1691 };
1692
1693 struct rule_list {
1694         char name[80];
1695         AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
1696         AST_LIST_ENTRY(rule_list) list;
1697 };
1698
1699 static AST_LIST_HEAD_STATIC(rule_lists, rule_list);
1700
1701 static struct ao2_container *queues;
1702
1703 static void update_realtime_members(struct call_queue *q);
1704 static struct member *interface_exists(struct call_queue *q, const char *interface);
1705 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
1706
1707 static struct member *find_member_by_queuename_and_interface(const char *queuename, const char *interface);
1708 /*! \brief sets the QUEUESTATUS channel variable */
1709 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
1710 {
1711         int i;
1712
1713         for (i = 0; i < ARRAY_LEN(queue_results); i++) {
1714                 if (queue_results[i].id == res) {
1715                         pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
1716                         return;
1717                 }
1718         }
1719 }
1720
1721 static const char *int2strat(int strategy)
1722 {
1723         int x;
1724
1725         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1726                 if (strategy == strategies[x].strategy) {
1727                         return strategies[x].name;
1728                 }
1729         }
1730
1731         return "<unknown>";
1732 }
1733
1734 static int strat2int(const char *strategy)
1735 {
1736         int x;
1737
1738         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1739                 if (!strcasecmp(strategy, strategies[x].name)) {
1740                         return strategies[x].strategy;
1741                 }
1742         }
1743
1744         return -1;
1745 }
1746
1747 static int autopause2int(const char *autopause)
1748 {
1749         int x;
1750         /*This 'double check' that default value is OFF */
1751         if (ast_strlen_zero(autopause)) {
1752                 return QUEUE_AUTOPAUSE_OFF;
1753         }
1754
1755         /*This 'double check' is to ensure old values works */
1756         if(ast_true(autopause)) {
1757                 return QUEUE_AUTOPAUSE_ON;
1758         }
1759
1760         for (x = 0; x < ARRAY_LEN(autopausesmodes); x++) {
1761                 if (!strcasecmp(autopause, autopausesmodes[x].name)) {
1762                         return autopausesmodes[x].autopause;
1763                 }
1764         }
1765
1766         /*This 'double check' that default value is OFF */
1767         return QUEUE_AUTOPAUSE_OFF;
1768 }
1769
1770 static int queue_hash_cb(const void *obj, const int flags)
1771 {
1772         const struct call_queue *q = obj;
1773
1774         return ast_str_case_hash(q->name);
1775 }
1776
1777 static int queue_cmp_cb(void *obj, void *arg, int flags)
1778 {
1779         struct call_queue *q = obj, *q2 = arg;
1780         return !strcasecmp(q->name, q2->name) ? CMP_MATCH | CMP_STOP : 0;
1781 }
1782
1783 /*! \internal
1784  * \brief ao2_callback, Decreases queuepos of all followers with a queuepos greater than arg.
1785  * \param obj the member being acted on
1786  * \param arg pointer to an integer containing the position value that was removed and requires reduction for anything above
1787  */
1788 static int queue_member_decrement_followers(void *obj, void *arg, int flag)
1789 {
1790         struct member *mem = obj;
1791         int *decrement_followers_after = arg;
1792
1793         if (mem->queuepos > *decrement_followers_after) {
1794                 mem->queuepos--;
1795         }
1796
1797         return 0;
1798 }
1799
1800 /*! \internal
1801  * \brief ao2_callback, finds members in a queue marked for deletion and in a cascading fashion runs queue_member_decrement_followers
1802  *        on them. This callback should always be ran before performing mass unlinking of delmarked members from queues.
1803  * \param obj member being acted on
1804  * \param arg pointer to the queue members are being removed from
1805  */
1806 static int queue_delme_members_decrement_followers(void *obj, void *arg, int flag)
1807 {
1808         struct member *mem = obj;
1809         struct call_queue *queue = arg;
1810         int rrpos = mem->queuepos;
1811
1812         if (mem->delme) {
1813                 ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &rrpos);
1814         }
1815
1816         return 0;
1817 }
1818
1819 /*! \internal
1820  * \brief Use this to decrement followers during removal of a member
1821  * \param queue which queue the member is being removed from
1822  * \param mem which member is being removed from the queue
1823  */
1824 static void queue_member_follower_removal(struct call_queue *queue, struct member *mem)
1825 {
1826         int pos = mem->queuepos;
1827
1828         /* 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
1829          * who would have been next otherwise. */
1830         if (pos < queue->rrpos) {
1831                 queue->rrpos--;
1832         }
1833
1834         ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &pos);
1835 }
1836
1837 #define queue_ref(q)                            _queue_ref(q, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1838 #define queue_unref(q)                          _queue_unref(q, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1839 #define queue_t_ref(q, tag)                     _queue_ref(q, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1840 #define queue_t_unref(q, tag)           _queue_unref(q, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1841 #define queues_t_link(c, q, tag)        ao2_t_link(c, q, tag)
1842 #define queues_t_unlink(c, q, tag)      ao2_t_unlink(c, q, tag)
1843
1844 static inline struct call_queue *_queue_ref(struct call_queue *q, const char *tag, const char *file, int line, const char *filename)
1845 {
1846         __ao2_ref(q, 1, tag, file, line, filename);
1847         return q;
1848 }
1849
1850 static inline struct call_queue *_queue_unref(struct call_queue *q, const char *tag, const char *file, int line, const char *filename)
1851 {
1852         if (q) {
1853                 __ao2_ref(q, -1, tag, file, line, filename);
1854         }
1855         return NULL;
1856 }
1857
1858 /*! \brief Set variables of queue */
1859 static void set_queue_variables(struct call_queue *q, struct ast_channel *chan)
1860 {
1861         char interfacevar[256]="";
1862         float sl = 0;
1863
1864         ao2_lock(q);
1865
1866         if (q->setqueuevar) {
1867                 sl = 0;
1868                 if (q->callscompleted > 0) {
1869                         sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
1870                 }
1871
1872                 snprintf(interfacevar, sizeof(interfacevar),
1873                         "QUEUENAME=%s,QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
1874                         q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned,  q->servicelevel, sl);
1875
1876                 ao2_unlock(q);
1877
1878                 pbx_builtin_setvar_multiple(chan, interfacevar);
1879         } else {
1880                 ao2_unlock(q);
1881         }
1882 }
1883
1884 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
1885 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
1886 {
1887         struct queue_ent *cur;
1888
1889         if (!q || !new)
1890                 return;
1891         if (prev) {
1892                 cur = prev->next;
1893                 prev->next = new;
1894         } else {
1895                 cur = q->head;
1896                 q->head = new;
1897         }
1898         new->next = cur;
1899
1900         /* every queue_ent must have a reference to it's parent call_queue, this
1901          * reference does not go away until the end of the queue_ent's life, meaning
1902          * that even when the queue_ent leaves the call_queue this ref must remain. */
1903         queue_ref(q);
1904         new->parent = q;
1905         new->pos = ++(*pos);
1906         new->opos = *pos;
1907 }
1908
1909 static struct ast_manager_event_blob *queue_channel_to_ami(const char *type, struct stasis_message *message)
1910 {
1911         struct ast_channel_blob *obj = stasis_message_data(message);
1912         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
1913         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
1914
1915         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
1916         event_string = ast_manager_str_from_json_object(obj->blob, NULL);
1917         if (!channel_string || !event_string) {
1918                 return NULL;
1919         }
1920
1921         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
1922                 "%s"
1923                 "%s",
1924                 ast_str_buffer(channel_string),
1925                 ast_str_buffer(event_string));
1926 }
1927
1928 static struct ast_manager_event_blob *queue_caller_join_to_ami(struct stasis_message *message)
1929 {
1930         return queue_channel_to_ami("QueueCallerJoin", message);
1931 }
1932
1933 static struct ast_manager_event_blob *queue_caller_leave_to_ami(struct stasis_message *message)
1934 {
1935         return queue_channel_to_ami("QueueCallerLeave", message);
1936 }
1937
1938 static struct ast_manager_event_blob *queue_caller_abandon_to_ami(struct stasis_message *message)
1939 {
1940         return queue_channel_to_ami("QueueCallerAbandon", message);
1941 }
1942
1943 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_join_type,
1944         .to_ami = queue_caller_join_to_ami,
1945         );
1946 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_leave_type,
1947         .to_ami = queue_caller_leave_to_ami,
1948         );
1949 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_abandon_type,
1950         .to_ami = queue_caller_abandon_to_ami,
1951         );
1952
1953 static struct ast_manager_event_blob *queue_member_to_ami(const char *type, struct stasis_message *message)
1954 {
1955         struct ast_json_payload *payload = stasis_message_data(message);
1956         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
1957
1958         event_string = ast_manager_str_from_json_object(payload->json, NULL);
1959         if (!event_string) {
1960                 return NULL;
1961         }
1962
1963         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
1964                 "%s",
1965                 ast_str_buffer(event_string));
1966 }
1967
1968 static struct ast_manager_event_blob *queue_member_status_to_ami(struct stasis_message *message)
1969 {
1970         return queue_member_to_ami("QueueMemberStatus", message);
1971 }
1972
1973 static struct ast_manager_event_blob *queue_member_added_to_ami(struct stasis_message *message)
1974 {
1975         return queue_member_to_ami("QueueMemberAdded", message);
1976 }
1977
1978 static struct ast_manager_event_blob *queue_member_removed_to_ami(struct stasis_message *message)
1979 {
1980         return queue_member_to_ami("QueueMemberRemoved", message);
1981 }
1982
1983 static struct ast_manager_event_blob *queue_member_pause_to_ami(struct stasis_message *message)
1984 {
1985         return queue_member_to_ami("QueueMemberPause", message);
1986 }
1987
1988 static struct ast_manager_event_blob *queue_member_penalty_to_ami(struct stasis_message *message)
1989 {
1990         return queue_member_to_ami("QueueMemberPenalty", message);
1991 }
1992
1993 static struct ast_manager_event_blob *queue_member_ringinuse_to_ami(struct stasis_message *message)
1994 {
1995         return queue_member_to_ami("QueueMemberRinginuse", message);
1996 }
1997
1998 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_status_type,
1999         .to_ami = queue_member_status_to_ami,
2000         );
2001 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_added_type,
2002         .to_ami = queue_member_added_to_ami,
2003         );
2004 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_removed_type,
2005         .to_ami = queue_member_removed_to_ami,
2006         );
2007 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_pause_type,
2008         .to_ami = queue_member_pause_to_ami,
2009         );
2010 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_penalty_type,
2011         .to_ami = queue_member_penalty_to_ami,
2012         );
2013 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_ringinuse_type,
2014         .to_ami = queue_member_ringinuse_to_ami,
2015         );
2016
2017 static struct ast_manager_event_blob *queue_multi_channel_to_ami(const char *type, struct stasis_message *message)
2018 {
2019         struct ast_multi_channel_blob *obj = stasis_message_data(message);
2020         struct ast_channel_snapshot *caller;
2021         struct ast_channel_snapshot *agent;
2022         RAII_VAR(struct ast_str *, caller_event_string, NULL, ast_free);
2023         RAII_VAR(struct ast_str *, agent_event_string, NULL, ast_free);
2024         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
2025
2026         caller = ast_multi_channel_blob_get_channel(obj, "caller");
2027         if (caller) {
2028                 caller_event_string = ast_manager_build_channel_state_string(caller);
2029                 if (!caller_event_string) {
2030                         ast_log(LOG_NOTICE, "No caller event string, bailing\n");
2031                         return NULL;
2032                 }
2033         }
2034
2035         agent = ast_multi_channel_blob_get_channel(obj, "agent");
2036         if (agent) {
2037                 agent_event_string = ast_manager_build_channel_state_string_prefix(agent, "Dest");
2038                 if (!agent_event_string) {
2039                         ast_log(LOG_NOTICE, "No agent event string, bailing\n");
2040                         return NULL;
2041                 }
2042         }
2043
2044         event_string = ast_manager_str_from_json_object(ast_multi_channel_blob_get_json(obj), NULL);
2045         if (!event_string) {
2046                 return NULL;
2047         }
2048
2049         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
2050                 "%s"
2051                 "%s"
2052                 "%s",
2053                 caller_event_string ? ast_str_buffer(caller_event_string) : "",
2054                 agent_event_string ? ast_str_buffer(agent_event_string) : "",
2055                 ast_str_buffer(event_string));
2056 }
2057
2058 static struct ast_manager_event_blob *queue_agent_called_to_ami(struct stasis_message *message)
2059 {
2060         return queue_multi_channel_to_ami("AgentCalled", message);
2061 }
2062
2063 static struct ast_manager_event_blob *queue_agent_connect_to_ami(struct stasis_message *message)
2064 {
2065         return queue_multi_channel_to_ami("AgentConnect", message);
2066 }
2067
2068 static struct ast_manager_event_blob *queue_agent_complete_to_ami(struct stasis_message *message)
2069 {
2070         return queue_multi_channel_to_ami("AgentComplete", message);
2071 }
2072
2073 static struct ast_manager_event_blob *queue_agent_dump_to_ami(struct stasis_message *message)
2074 {
2075         return queue_multi_channel_to_ami("AgentDump", message);
2076 }
2077
2078 static struct ast_manager_event_blob *queue_agent_ringnoanswer_to_ami(struct stasis_message *message)
2079 {
2080         return queue_multi_channel_to_ami("AgentRingNoAnswer", message);
2081 }
2082
2083 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_called_type,
2084         .to_ami = queue_agent_called_to_ami,
2085         );
2086 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_connect_type,
2087         .to_ami = queue_agent_connect_to_ami,
2088         );
2089 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_complete_type,
2090         .to_ami = queue_agent_complete_to_ami,
2091         );
2092 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_dump_type,
2093         .to_ami = queue_agent_dump_to_ami,
2094         );
2095 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_ringnoanswer_type,
2096         .to_ami = queue_agent_ringnoanswer_to_ami,
2097         );
2098
2099 static void queue_publish_multi_channel_snapshot_blob(struct stasis_topic *topic,
2100                 struct ast_channel_snapshot *caller_snapshot,
2101                 struct ast_channel_snapshot *agent_snapshot,
2102                 struct stasis_message_type *type, struct ast_json *blob)
2103 {
2104         RAII_VAR(struct ast_multi_channel_blob *, payload, NULL, ao2_cleanup);
2105         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2106
2107         if (!type) {
2108                 return;
2109         }
2110
2111         payload = ast_multi_channel_blob_create(blob);
2112         if (!payload) {
2113                 return;
2114         }
2115
2116         ast_multi_channel_blob_add_channel(payload, "caller", caller_snapshot);
2117         if (agent_snapshot) {
2118                 ast_multi_channel_blob_add_channel(payload, "agent", agent_snapshot);
2119         }
2120
2121         msg = stasis_message_create(type, payload);
2122         if (!msg) {
2123                 return;
2124         }
2125
2126         stasis_publish(topic, msg);
2127 }
2128
2129 static void queue_publish_multi_channel_blob(struct ast_channel *caller, struct ast_channel *agent,
2130                 struct stasis_message_type *type, struct ast_json *blob)
2131 {
2132         RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
2133         RAII_VAR(struct ast_channel_snapshot *, agent_snapshot, NULL, ao2_cleanup);
2134
2135         ast_channel_lock(caller);
2136         caller_snapshot = ast_channel_snapshot_create(caller);
2137         ast_channel_unlock(caller);
2138         ast_channel_lock(agent);
2139         agent_snapshot = ast_channel_snapshot_create(agent);
2140         ast_channel_unlock(agent);
2141
2142         if (!caller_snapshot || !agent_snapshot) {
2143                 return;
2144         }
2145
2146         queue_publish_multi_channel_snapshot_blob(ast_channel_topic(caller), caller_snapshot,
2147                         agent_snapshot, type, blob);
2148 }
2149
2150 /*!
2151  * \internal
2152  * \brief Publish the member blob.
2153  * \since 12.0.0
2154  *
2155  * \param type Stasis message type to publish.
2156  * \param blob The information being published.
2157  *
2158  * \note The json blob reference is passed to this function.
2159  *
2160  * \return Nothing
2161  */
2162 static void queue_publish_member_blob(struct stasis_message_type *type, struct ast_json *blob)
2163 {
2164         RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
2165         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2166
2167         if (!blob || !type) {
2168                 return;
2169         }
2170
2171         payload = ast_json_payload_create(blob);
2172         ast_json_unref(blob);
2173         if (!payload) {
2174                 return;
2175         }
2176
2177         msg = stasis_message_create(type, payload);
2178         if (!msg) {
2179                 return;
2180         }
2181
2182         stasis_publish(ast_manager_get_topic(), msg);
2183 }
2184
2185 static struct ast_json *queue_member_blob_create(struct call_queue *q, struct member *mem)
2186 {
2187         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: s, s: i}",
2188                 "Queue", q->name,
2189                 "MemberName", mem->membername,
2190                 "Interface", mem->interface,
2191                 "StateInterface", mem->state_interface,
2192                 "Membership", (mem->dynamic ? "dynamic" : (mem->realtime ? "realtime" : "static")),
2193                 "Penalty", mem->penalty,
2194                 "CallsTaken", mem->calls,
2195                 "LastCall", (int)mem->lastcall,
2196                 "InCall", mem->in_call,
2197                 "Status", mem->status,
2198                 "Paused", mem->paused,
2199                 "PausedReason", mem->reason_paused,
2200                 "Ringinuse", mem->ringinuse);
2201 }
2202
2203 /*! \brief Check if members are available
2204  *
2205  * This function checks to see if members are available to be called. If any member
2206  * is available, the function immediately returns 0. If no members are available,
2207  * then -1 is returned.
2208  */
2209 static int get_member_status(struct call_queue *q, int max_penalty, int min_penalty, enum empty_conditions conditions, int devstate)
2210 {
2211         struct member *member;
2212         struct ao2_iterator mem_iter;
2213
2214         ao2_lock(q);
2215         mem_iter = ao2_iterator_init(q->members, 0);
2216         for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
2217                 if ((max_penalty != INT_MAX && member->penalty > max_penalty) || (min_penalty != INT_MAX && member->penalty < min_penalty)) {
2218                         if (conditions & QUEUE_EMPTY_PENALTY) {
2219                                 ast_debug(4, "%s is unavailable because his penalty is not between %d and %d\n", member->membername, min_penalty, max_penalty);
2220                                 continue;
2221                         }
2222                 }
2223
2224                 switch (devstate ? ast_device_state(member->state_interface) : member->status) {
2225                 case AST_DEVICE_INVALID:
2226                         if (conditions & QUEUE_EMPTY_INVALID) {
2227                                 ast_debug(4, "%s is unavailable because his device state is 'invalid'\n", member->membername);
2228                                 break;
2229                         }
2230                         goto default_case;
2231                 case AST_DEVICE_UNAVAILABLE:
2232                         if (conditions & QUEUE_EMPTY_UNAVAILABLE) {
2233                                 ast_debug(4, "%s is unavailable because his device state is 'unavailable'\n", member->membername);
2234                                 break;
2235                         }
2236                         goto default_case;
2237                 case AST_DEVICE_INUSE:
2238                         if (conditions & QUEUE_EMPTY_INUSE) {
2239                                 ast_debug(4, "%s is unavailable because his device state is 'inuse'\n", member->membername);
2240                                 break;
2241                         }
2242                         goto default_case;
2243                 case AST_DEVICE_RINGING:
2244                         if (conditions & QUEUE_EMPTY_RINGING) {
2245                                 ast_debug(4, "%s is unavailable because his device state is 'ringing'\n", member->membername);
2246                                 break;
2247                         }
2248                         goto default_case;
2249                 case AST_DEVICE_UNKNOWN:
2250                         if (conditions & QUEUE_EMPTY_UNKNOWN) {
2251                                 ast_debug(4, "%s is unavailable because his device state is 'unknown'\n", member->membername);
2252                                 break;
2253                         }
2254                         /* Fall-through */
2255                 default:
2256                 default_case:
2257                         if (member->paused && (conditions & QUEUE_EMPTY_PAUSED)) {
2258                                 ast_debug(4, "%s is unavailable because he is paused'\n", member->membername);
2259                                 break;
2260                         } else if ((conditions & QUEUE_EMPTY_WRAPUP) && member->in_call && q->wrapuptime) {
2261                                 ast_debug(4, "%s is unavailable because still in call, so we can`t check "
2262                                         "wrapuptime (%d)\n", member->membername, q->wrapuptime);
2263                                 break;
2264                         } else if ((conditions & QUEUE_EMPTY_WRAPUP) && member->lastcall && q->wrapuptime && (time(NULL) - q->wrapuptime < member->lastcall)) {
2265                                 ast_debug(4, "%s is unavailable because it has only been %d seconds since his last call (wrapup time is %d)\n", member->membername, (int) (time(NULL) - member->lastcall), q->wrapuptime);
2266                                 break;
2267                         } else {
2268                                 ao2_ref(member, -1);
2269                                 ao2_iterator_destroy(&mem_iter);
2270                                 ao2_unlock(q);
2271                                 ast_debug(4, "%s is available.\n", member->membername);
2272                                 return 0;
2273                         }
2274                         break;
2275                 }
2276         }
2277         ao2_iterator_destroy(&mem_iter);
2278         ao2_unlock(q);
2279
2280         if (!devstate && (conditions & QUEUE_EMPTY_RINGING)) {
2281                 /* member state still may be RINGING due to lag in event message - check again with device state */
2282                 return get_member_status(q, max_penalty, min_penalty, conditions, 1);
2283         }
2284         return -1;
2285 }
2286
2287 /*! \brief set a member's status based on device state of that member's state_interface.
2288  *
2289  * Lock interface list find sc, iterate through each queues queue_member list for member to
2290  * update state inside queues
2291 */
2292 static void update_status(struct call_queue *q, struct member *m, const int status)
2293 {
2294         m->status = status;
2295
2296         queue_publish_member_blob(queue_member_status_type(), queue_member_blob_create(q, m));
2297 }
2298
2299 /*!
2300  * \internal
2301  * \brief Determine if a queue member is available
2302  * \retval 1 if the member is available
2303  * \retval 0 if the member is not available
2304  */
2305 static int is_member_available(struct call_queue *q, struct member *mem)
2306 {
2307         int available = 0;
2308
2309         switch (mem->status) {
2310                 case AST_DEVICE_INVALID:
2311                 case AST_DEVICE_UNAVAILABLE:
2312                         break;
2313                 case AST_DEVICE_INUSE:
2314                 case AST_DEVICE_BUSY:
2315                 case AST_DEVICE_RINGING:
2316                 case AST_DEVICE_RINGINUSE:
2317                 case AST_DEVICE_ONHOLD:
2318                         if (!mem->ringinuse) {
2319                                 break;
2320                         }
2321                         /* else fall through */
2322                 case AST_DEVICE_NOT_INUSE:
2323                 case AST_DEVICE_UNKNOWN:
2324                         if (!mem->paused) {
2325                                 available = 1;
2326                         }
2327                         break;
2328         }
2329
2330         /* Let wrapuptimes override device state availability */
2331         if (q->wrapuptime && mem->in_call) {
2332                 available = 0; /* member is still in call, cant check wrapuptime to lastcall time */
2333         }
2334         if (mem->lastcall && q->wrapuptime && (time(NULL) - q->wrapuptime < mem->lastcall)) {
2335                 available = 0;
2336         }
2337         return available;
2338 }
2339
2340 /*! \brief set a member's status based on device state of that member's interface*/
2341 static void device_state_cb(void *unused, struct stasis_subscription *sub, struct stasis_message *msg)
2342 {
2343         struct ao2_iterator miter, qiter;
2344         struct ast_device_state_message *dev_state;
2345         struct member *m;
2346         struct call_queue *q;
2347         char interface[80], *slash_pos;
2348         int found = 0;                  /* Found this member in any queue */
2349         int found_member;               /* Found this member in this queue */
2350         int avail = 0;                  /* Found an available member in this queue */
2351
2352         if (ast_device_state_message_type() != stasis_message_type(msg)) {
2353                 return;
2354         }
2355
2356         dev_state = stasis_message_data(msg);
2357         if (dev_state->eid) {
2358                 /* ignore non-aggregate states */
2359                 return;
2360         }
2361
2362         qiter = ao2_iterator_init(queues, 0);
2363         while ((q = ao2_t_iterator_next(&qiter, "Iterate over queues"))) {
2364                 ao2_lock(q);
2365
2366                 avail = 0;
2367                 found_member = 0;
2368                 miter = ao2_iterator_init(q->members, 0);
2369                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
2370                         if (!found_member) {
2371                                 ast_copy_string(interface, m->state_interface, sizeof(interface));
2372
2373                                 if ((slash_pos = strchr(interface, '/'))) {
2374                                         if (!strncasecmp(interface, "Local/", 6) && (slash_pos = strchr(slash_pos + 1, '/'))) {
2375                                                 *slash_pos = '\0';
2376                                         }
2377                                 }
2378
2379                                 if (!strcasecmp(interface, dev_state->device)) {
2380                                         found_member = 1;
2381                                         update_status(q, m, dev_state->state);
2382                                 }
2383                         }
2384
2385                         /* check every member until we find one NOT_INUSE */
2386                         if (!avail) {
2387                                 avail = is_member_available(q, m);
2388                         }
2389                         if (avail && found_member) {
2390                                 /* early exit as we've found an available member and the member of interest */
2391                                 ao2_ref(m, -1);
2392                                 break;
2393                         }
2394                 }
2395
2396                 if (found_member) {
2397                         found = 1;
2398                         if (avail) {
2399                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2400                         } else {
2401                                 ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2402                         }
2403                 }
2404
2405                 ao2_iterator_destroy(&miter);
2406
2407                 ao2_unlock(q);
2408                 queue_t_unref(q, "Done with iterator");
2409         }
2410         ao2_iterator_destroy(&qiter);
2411
2412         if (found) {
2413                 ast_debug(1, "Device '%s' changed to state '%u' (%s)\n",
2414                         dev_state->device,
2415                         dev_state->state,
2416                         ast_devstate2str(dev_state->state));
2417         } else {
2418                 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",
2419                         dev_state->device,
2420                         dev_state->state,
2421                         ast_devstate2str(dev_state->state));
2422         }
2423
2424         return;
2425 }
2426
2427 /*! \brief Helper function which converts from extension state to device state values */
2428 static int extensionstate2devicestate(int state)
2429 {
2430         switch (state) {
2431         case AST_EXTENSION_NOT_INUSE:
2432                 state = AST_DEVICE_NOT_INUSE;
2433                 break;
2434         case AST_EXTENSION_INUSE:
2435                 state = AST_DEVICE_INUSE;
2436                 break;
2437         case AST_EXTENSION_BUSY:
2438                 state = AST_DEVICE_BUSY;
2439                 break;
2440         case AST_EXTENSION_RINGING:
2441                 state = AST_DEVICE_RINGING;
2442                 break;
2443         case AST_EXTENSION_ONHOLD:
2444                 state = AST_DEVICE_ONHOLD;
2445                 break;
2446         case AST_EXTENSION_UNAVAILABLE:
2447                 state = AST_DEVICE_UNAVAILABLE;
2448                 break;
2449         case AST_EXTENSION_REMOVED:
2450         case AST_EXTENSION_DEACTIVATED:
2451         default:
2452                 state = AST_DEVICE_INVALID;
2453                 break;
2454         }
2455
2456         return state;
2457 }
2458
2459 static int extension_state_cb(char *context, char *exten, struct ast_state_cb_info *info, void *data)
2460 {
2461         struct ao2_iterator miter, qiter;
2462         struct member *m;
2463         struct call_queue *q;
2464         int state = info->exten_state;
2465         int found = 0, device_state = extensionstate2devicestate(state);
2466
2467         /* only interested in extension state updates involving device states */
2468         if (info->reason != AST_HINT_UPDATE_DEVICE) {
2469                 return 0;
2470         }
2471
2472         qiter = ao2_iterator_init(queues, 0);
2473         while ((q = ao2_t_iterator_next(&qiter, "Iterate through queues"))) {
2474                 ao2_lock(q);
2475
2476                 miter = ao2_iterator_init(q->members, 0);
2477                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
2478                         if (!strcmp(m->state_context, context) && !strcmp(m->state_exten, exten)) {
2479                                 update_status(q, m, device_state);
2480                                 ao2_ref(m, -1);
2481                                 found = 1;
2482                                 break;
2483                         }
2484                 }
2485                 ao2_iterator_destroy(&miter);
2486
2487                 ao2_unlock(q);
2488                 queue_t_unref(q, "Done with iterator");
2489         }
2490         ao2_iterator_destroy(&qiter);
2491
2492         if (found) {
2493                 ast_debug(1, "Extension '%s@%s' changed to state '%d' (%s)\n", exten, context, device_state, ast_devstate2str(device_state));
2494         } else {
2495                 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",
2496                           exten, context, device_state, ast_devstate2str(device_state));
2497         }
2498
2499         return 0;
2500 }
2501
2502 /*! \brief Return the current state of a member */
2503 static int get_queue_member_status(struct member *cur)
2504 {
2505         return ast_strlen_zero(cur->state_exten) ? ast_device_state(cur->state_interface) : extensionstate2devicestate(ast_extension_state(NULL, cur->state_context, cur->state_exten));
2506 }
2507
2508 /*! \brief allocate space for new queue member and set fields based on parameters passed */
2509 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused, const char *state_interface, int ringinuse)
2510 {
2511         struct member *cur;
2512
2513         if ((cur = ao2_alloc(sizeof(*cur), NULL))) {
2514                 cur->ringinuse = ringinuse;
2515                 cur->penalty = penalty;
2516                 cur->paused = paused;
2517                 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
2518                 if (!ast_strlen_zero(state_interface)) {
2519                         ast_copy_string(cur->state_interface, state_interface, sizeof(cur->state_interface));
2520                 } else {
2521                         ast_copy_string(cur->state_interface, interface, sizeof(cur->state_interface));
2522                 }
2523                 if (!ast_strlen_zero(membername)) {
2524                         ast_copy_string(cur->membername, membername, sizeof(cur->membername));
2525                 } else {
2526                         ast_copy_string(cur->membername, interface, sizeof(cur->membername));
2527                 }
2528                 if (!strchr(cur->interface, '/')) {
2529                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
2530                 }
2531                 if (!strncmp(cur->state_interface, "hint:", 5)) {
2532                         char *tmp = ast_strdupa(cur->state_interface), *context = tmp;
2533                         char *exten = strsep(&context, "@") + 5;
2534
2535                         ast_copy_string(cur->state_exten, exten, sizeof(cur->state_exten));
2536                         ast_copy_string(cur->state_context, S_OR(context, "default"), sizeof(cur->state_context));
2537                 }
2538                 cur->status = get_queue_member_status(cur);
2539         }
2540
2541         return cur;
2542 }
2543
2544
2545 static int compress_char(const char c)
2546 {
2547         if (c < 32) {
2548                 return 0;
2549         } else if (c > 96) {
2550                 return c - 64;
2551         }
2552         return c - 32;
2553 }
2554
2555 static int member_hash_fn(const void *obj, const int flags)
2556 {
2557         const struct member *mem = obj;
2558         const char *interface = (flags & OBJ_KEY) ? obj : mem->interface;
2559         const char *chname = strchr(interface, '/');
2560         int ret = 0, i;
2561
2562         if (!chname) {
2563                 chname = interface;
2564         }
2565         for (i = 0; i < 5 && chname[i]; i++) {
2566                 ret += compress_char(chname[i]) << (i * 6);
2567         }
2568         return ret;
2569 }
2570
2571 static int member_cmp_fn(void *obj1, void *obj2, int flags)
2572 {
2573         struct member *mem1 = obj1;
2574         struct member *mem2 = obj2;
2575         const char *interface = (flags & OBJ_KEY) ? obj2 : mem2->interface;
2576
2577         return strcasecmp(mem1->interface, interface) ? 0 : CMP_MATCH | CMP_STOP;
2578 }
2579
2580 /*!
2581  * \brief Initialize Queue default values.
2582  * \note the queue's lock  must be held before executing this function
2583 */
2584 static void init_queue(struct call_queue *q)
2585 {
2586         int i;
2587         struct penalty_rule *pr_iter;
2588
2589         q->dead = 0;
2590         q->retry = DEFAULT_RETRY;
2591         q->timeout = DEFAULT_TIMEOUT;
2592         q->maxlen = 0;
2593         q->announcefrequency = 0;
2594         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
2595         q->announceholdtime = 1;
2596         q->announcepositionlimit = 10; /* Default 10 positions */
2597         q->announceposition = ANNOUNCEPOSITION_YES; /* Default yes */
2598         q->roundingseconds = 0; /* Default - don't announce seconds */
2599         q->servicelevel = 0;
2600         q->ringinuse = 1;
2601         q->announce_to_first_user = 0;
2602         q->setinterfacevar = 0;
2603         q->setqueuevar = 0;
2604         q->setqueueentryvar = 0;
2605         q->autofill = autofill_default;
2606         q->montype = montype_default;
2607         q->monfmt[0] = '\0';
2608         q->reportholdtime = 0;
2609         q->wrapuptime = 0;
2610         q->penaltymemberslimit = 0;
2611         q->joinempty = 0;
2612         q->leavewhenempty = 0;
2613         q->memberdelay = 0;
2614         q->weight = 0;
2615         q->timeoutrestart = 0;
2616         q->periodicannouncefrequency = 0;
2617         q->randomperiodicannounce = 0;
2618         q->numperiodicannounce = 0;
2619         q->autopause = QUEUE_AUTOPAUSE_OFF;
2620         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
2621         q->autopausedelay = 0;
2622         if (!q->members) {
2623                 if (q->strategy == QUEUE_STRATEGY_LINEAR || q->strategy == QUEUE_STRATEGY_RRORDERED) {
2624                         /* linear strategy depends on order, so we have to place all members in a single bucket */
2625                         q->members = ao2_container_alloc(1, member_hash_fn, member_cmp_fn);
2626                 } else {
2627                         q->members = ao2_container_alloc(37, member_hash_fn, member_cmp_fn);
2628                 }
2629         }
2630         q->found = 1;
2631
2632         ast_string_field_set(q, sound_next, "queue-youarenext");
2633         ast_string_field_set(q, sound_thereare, "queue-thereare");
2634         ast_string_field_set(q, sound_calls, "queue-callswaiting");
2635         ast_string_field_set(q, queue_quantity1, "queue-quantity1");
2636         ast_string_field_set(q, queue_quantity2, "queue-quantity2");
2637         ast_string_field_set(q, sound_holdtime, "queue-holdtime");
2638         ast_string_field_set(q, sound_minutes, "queue-minutes");
2639         ast_string_field_set(q, sound_minute, "queue-minute");
2640         ast_string_field_set(q, sound_seconds, "queue-seconds");
2641         ast_string_field_set(q, sound_thanks, "queue-thankyou");
2642         ast_string_field_set(q, sound_reporthold, "queue-reporthold");
2643
2644         if (!q->sound_periodicannounce[0]) {
2645                 q->sound_periodicannounce[0] = ast_str_create(32);
2646         }
2647
2648         if (q->sound_periodicannounce[0]) {
2649                 ast_str_set(&q->sound_periodicannounce[0], 0, "queue-periodic-announce");
2650         }
2651
2652         for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
2653                 if (q->sound_periodicannounce[i]) {
2654                         ast_str_set(&q->sound_periodicannounce[i], 0, "%s", "");
2655                 }
2656         }
2657
2658         while ((pr_iter = AST_LIST_REMOVE_HEAD(&q->rules,list))) {
2659                 ast_free(pr_iter);
2660         }
2661
2662         /* On restart assume no members are available.
2663          * The queue_avail hint is a boolean state to indicate whether a member is available or not.
2664          *
2665          * This seems counter intuitive, but is required to light a BLF
2666          * AST_DEVICE_INUSE indicates no members are available.
2667          * AST_DEVICE_NOT_INUSE indicates a member is available.
2668          */
2669         ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2670 }
2671
2672 static void clear_queue(struct call_queue *q)
2673 {
2674         q->holdtime = 0;
2675         q->callscompleted = 0;
2676         q->callsabandoned = 0;
2677         q->callscompletedinsl = 0;
2678         q->talktime = 0;
2679
2680         if (q->members) {
2681                 struct member *mem;
2682                 struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
2683                 while ((mem = ao2_iterator_next(&mem_iter))) {
2684                         mem->calls = 0;
2685                         mem->lastcall = 0;
2686                         mem->in_call = 0;
2687                         ao2_ref(mem, -1);
2688                 }
2689                 ao2_iterator_destroy(&mem_iter);
2690         }
2691 }
2692
2693 /*!
2694  * \brief Change queue penalty by adding rule.
2695  *
2696  * Check rule for errors with time or fomatting, see if rule is relative to rest
2697  * of queue, iterate list of rules to find correct insertion point, insert and return.
2698  * \retval -1 on failure
2699  * \retval 0 on success
2700  * \note Call this with the rule_lists locked
2701 */
2702 static int insert_penaltychange(const char *list_name, const char *content, const int linenum)
2703 {
2704         char *timestr, *maxstr, *minstr, *contentdup;
2705         struct penalty_rule *rule = NULL, *rule_iter;
2706         struct rule_list *rl_iter;
2707         int penaltychangetime, inserted = 0;
2708
2709         if (!(rule = ast_calloc(1, sizeof(*rule)))) {
2710                 return -1;
2711         }
2712
2713         contentdup = ast_strdupa(content);
2714
2715         if (!(maxstr = strchr(contentdup, ','))) {
2716                 ast_log(LOG_WARNING, "Improperly formatted penaltychange rule at line %d. Ignoring.\n", linenum);
2717                 ast_free(rule);
2718                 return -1;
2719         }
2720
2721         *maxstr++ = '\0';
2722         timestr = contentdup;
2723
2724         if ((penaltychangetime = atoi(timestr)) < 0) {
2725                 ast_log(LOG_WARNING, "Improper time parameter specified for penaltychange rule at line %d. Ignoring.\n", linenum);
2726                 ast_free(rule);
2727                 return -1;
2728         }
2729
2730         rule->time = penaltychangetime;
2731
2732         if ((minstr = strchr(maxstr,','))) {
2733                 *minstr++ = '\0';
2734         }
2735
2736         /* The last check will evaluate true if either no penalty change is indicated for a given rule
2737          * OR if a min penalty change is indicated but no max penalty change is */
2738         if (*maxstr == '+' || *maxstr == '-' || *maxstr == '\0') {
2739                 rule->max_relative = 1;
2740         }
2741
2742         rule->max_value = atoi(maxstr);
2743
2744         if (!ast_strlen_zero(minstr)) {
2745                 if (*minstr == '+' || *minstr == '-') {
2746                         rule->min_relative = 1;
2747                 }
2748                 rule->min_value = atoi(minstr);
2749         } else { /*there was no minimum specified, so assume this means no change*/
2750                 rule->min_relative = 1;
2751         }
2752
2753         /*We have the rule made, now we need to insert it where it belongs*/
2754         AST_LIST_TRAVERSE(&rule_lists, rl_iter, list){
2755                 if (strcasecmp(rl_iter->name, list_name)) {
2756                         continue;
2757                 }
2758
2759                 AST_LIST_TRAVERSE_SAFE_BEGIN(&rl_iter->rules, rule_iter, list) {
2760                         if (rule->time < rule_iter->time) {
2761                                 AST_LIST_INSERT_BEFORE_CURRENT(rule, list);
2762                                 inserted = 1;
2763                                 break;
2764                         }
2765                 }
2766                 AST_LIST_TRAVERSE_SAFE_END;
2767
2768                 if (!inserted) {
2769                         AST_LIST_INSERT_TAIL(&rl_iter->rules, rule, list);
2770                         inserted = 1;
2771                 }
2772
2773                 break;
2774         }
2775
2776         if (!inserted) {
2777                 ast_log(LOG_WARNING, "Unknown rule list name %s; ignoring.\n", list_name);
2778                 ast_free(rule);
2779                 return -1;
2780         }
2781         return 0;
2782 }
2783
2784 /*!
2785  * \brief Load queue rules from realtime.
2786  *
2787  * Check rule for errors with time or fomatting, see if rule is relative to rest
2788  * of queue, iterate list of rules to find correct insertion point, insert and return.
2789  * \retval -1 on failure
2790  * \retval 0 on success
2791  * \note Call this with the rule_lists locked
2792 */
2793 static int load_realtime_rules(void)
2794 {
2795         struct ast_config *cfg;
2796         struct rule_list *rl_iter, *new_rl;
2797         struct penalty_rule *pr_iter;
2798         char *rulecat = NULL;
2799
2800         if (!ast_check_realtime("queue_rules")) {
2801                 ast_log(LOG_WARNING, "Missing \"queue_rules\" in extconfig.conf\n");
2802                 return 0;
2803         }
2804         if (!(cfg = ast_load_realtime_multientry("queue_rules", "rule_name LIKE", "%", SENTINEL))) {
2805                 ast_log(LOG_WARNING, "Failed to load queue rules from realtime\n");
2806                 return 0;
2807         }
2808         while ((rulecat = ast_category_browse(cfg, rulecat)) && !ast_strlen_zero(rulecat)) {
2809                 const char *timestr, *maxstr, *minstr;
2810                 int penaltychangetime, rule_exists = 0, inserted = 0;
2811                 int max_penalty = 0, min_penalty = 0, min_relative = 0, max_relative = 0;
2812                 struct penalty_rule *new_penalty_rule = NULL;
2813                 AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
2814                         if (!(strcasecmp(rl_iter->name, rulecat))) {
2815                                 rule_exists = 1;
2816                                 new_rl = rl_iter;
2817                                 break;
2818                         }
2819                 }
2820                 if (!rule_exists) {
2821                         if (!(new_rl = ast_calloc(1, sizeof(*new_rl)))) {
2822                                 ast_config_destroy(cfg);
2823                                 return -1;
2824                         }
2825                         ast_copy_string(new_rl->name, rulecat, sizeof(new_rl->name));
2826                         AST_LIST_INSERT_TAIL(&rule_lists, new_rl, list);
2827                 }
2828                 timestr = ast_variable_retrieve(cfg, rulecat, "time");
2829                 if (!(timestr) || sscanf(timestr, "%30d", &penaltychangetime) != 1) {
2830                         ast_log(LOG_NOTICE, "Failed to parse time (%s) for one of the %s rules, skipping it\n",
2831                                 (ast_strlen_zero(timestr) ? "invalid value" : timestr), rulecat);
2832                         continue;
2833                 }
2834                 if (!(new_penalty_rule = ast_calloc(1, sizeof(*new_penalty_rule)))) {
2835                         ast_config_destroy(cfg);
2836                         return -1;