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