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