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