res_rtp_asterisk: Avoid close the rtp/rtcp fd twice.
[asterisk/asterisk.git] / apps / app_queue.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2016, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief True call queues with optional send URL on answer
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \par Development notes
26  * \note 2004-11-25: Persistent Dynamic Members added by:
27  *             NetNation Communications (www.netnation.com)
28  *             Kevin Lindsay <kevinl@netnation.com>
29  *
30  *             Each dynamic agent in each queue is now stored in the astdb.
31  *             When asterisk is restarted, each agent will be automatically
32  *             readded into their recorded queues. This feature can be
33  *             configured with the 'persistent_members=<1|0>' setting in the
34  *             '[general]' category in queues.conf. The default is on.
35  *
36  * \note 2004-06-04: Priorities in queues added by inAccess Networks (work funded by Hellas On Line (HOL) www.hol.gr).
37  *
38  * \note These features added by David C. Troy <dave@toad.net>:
39  *    - Per-queue holdtime calculation
40  *    - Estimated holdtime announcement
41  *    - Position announcement
42  *    - Abandoned/completed call counters
43  *    - Failout timer passed as optional app parameter
44  *    - Optional monitoring of calls, started when call is answered
45  *
46  * Patch Version 1.07 2003-12-24 01
47  *
48  * Added servicelevel statistic by Michiel Betel <michiel@betel.nl>
49  * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <asterisk@doilooklikeicare.com>
50  *
51  * Fixed to work with CVS as of 2004-02-25 and released as 1.07a
52  * by Matthew Enger <m.enger@xi.com.au>
53  *
54  * \ingroup applications
55  */
56
57 /*! \li \ref app_queues.c uses configuration file \ref queues.conf
58  * \addtogroup configuration_file
59  */
60
61 /*! \page queues.conf queues.conf
62  * \verbinclude queues.conf.sample
63  */
64
65 /*** MODULEINFO
66         <use type="module">res_monitor</use>
67         <support_level>core</support_level>
68  ***/
69
70 #include "asterisk.h"
71
72 #include <sys/time.h>
73 #include <signal.h>
74 #include <netinet/in.h>
75 #include <ctype.h>
76
77 #include "asterisk/lock.h"
78 #include "asterisk/file.h"
79 #include "asterisk/channel.h"
80 #include "asterisk/pbx.h"
81 #include "asterisk/app.h"
82 #include "asterisk/linkedlists.h"
83 #include "asterisk/module.h"
84 #include "asterisk/translate.h"
85 #include "asterisk/say.h"
86 #include "asterisk/features.h"
87 #include "asterisk/musiconhold.h"
88 #include "asterisk/cli.h"
89 #include "asterisk/manager.h"
90 #include "asterisk/config.h"
91 #include "asterisk/monitor.h"
92 #include "asterisk/utils.h"
93 #include "asterisk/causes.h"
94 #include "asterisk/astdb.h"
95 #include "asterisk/devicestate.h"
96 #include "asterisk/stringfields.h"
97 #include "asterisk/astobj2.h"
98 #include "asterisk/strings.h"
99 #include "asterisk/taskprocessor.h"
100 #include "asterisk/aoc.h"
101 #include "asterisk/callerid.h"
102 #include "asterisk/term.h"
103 #include "asterisk/dial.h"
104 #include "asterisk/stasis_channels.h"
105 #include "asterisk/stasis_message_router.h"
106 #include "asterisk/bridge_after.h"
107 #include "asterisk/stasis_bridges.h"
108 #include "asterisk/core_local.h"
109 #include "asterisk/mixmonitor.h"
110 #include "asterisk/bridge_basic.h"
111 #include "asterisk/max_forwards.h"
112
113 /*!
114  * \par Please read before modifying this file.
115  * There are three locks which are regularly used
116  * throughout this file, the queue list lock, the lock
117  * for each individual queue, and the interface list lock.
118  * Please be extra careful to always lock in the following order
119  * 1) queue list lock
120  * 2) individual queue lock
121  * 3) interface list lock
122  * This order has sort of "evolved" over the lifetime of this
123  * application, but it is now in place this way, so please adhere
124  * to this order!
125  */
126
127 /*** DOCUMENTATION
128         <application name="Queue" language="en_US">
129                 <synopsis>
130                         Queue a call for a call queue.
131                 </synopsis>
132                 <syntax>
133                         <parameter name="queuename" required="true" />
134                         <parameter name="options">
135                                 <optionlist>
136                                         <option name="C">
137                                                 <para>Mark all calls as "answered elsewhere" when cancelled.</para>
138                                         </option>
139                                         <option name="c">
140                                                 <para>Continue in the dialplan if the callee hangs up.</para>
141                                         </option>
142                                         <option name="d">
143                                                 <para>data-quality (modem) call (minimum delay).</para>
144                                         </option>
145                                         <option name="F" argsep="^">
146                                                 <argument name="context" required="false" />
147                                                 <argument name="exten" required="false" />
148                                                 <argument name="priority" required="true" />
149                                                 <para>When the caller hangs up, transfer the <emphasis>called member</emphasis>
150                                                 to the specified destination and <emphasis>start</emphasis> execution at that location.</para>
151                                                 <note>
152                                                         <para>Any channel variables you want the called channel to inherit from the caller channel must be
153                                                         prefixed with one or two underbars ('_').</para>
154                                                 </note>
155                                         </option>
156                                         <option name="F">
157                                                 <para>When the caller hangs up, transfer the <emphasis>called member</emphasis> to the next priority of
158                                                 the current extension and <emphasis>start</emphasis> execution at that location.</para>
159                                                 <note>
160                                                         <para>Any channel variables you want the called channel to inherit from the caller channel must be
161                                                         prefixed with one or two underbars ('_').</para>
162                                                 </note>
163                                                 <note>
164                                                         <para>Using this option from a Macro() or GoSub() might not make sense as there would be no return points.</para>
165                                                 </note>
166                                         </option>
167                                         <option name="h">
168                                                 <para>Allow <emphasis>callee</emphasis> to hang up by pressing <literal>*</literal>.</para>
169                                         </option>
170                                         <option name="H">
171                                                 <para>Allow <emphasis>caller</emphasis> to hang up by pressing <literal>*</literal>.</para>
172                                         </option>
173                                         <option name="n">
174                                                 <para>No retries on the timeout; will exit this application and
175                                                 go to the next step.</para>
176                                         </option>
177                                         <option name="i">
178                                                 <para>Ignore call forward requests from queue members and do nothing
179                                                 when they are requested.</para>
180                                         </option>
181                                         <option name="I">
182                                                 <para>Asterisk will ignore any connected line update requests or any redirecting party
183                                                 update requests it may receive on this dial attempt.</para>
184                                         </option>
185                                         <option name="r">
186                                                 <para>Ring instead of playing MOH. Periodic Announcements are still made, if applicable.</para>
187                                         </option>
188                                         <option name="R">
189                                                 <para>Ring instead of playing MOH when a member channel is actually ringing.</para>
190                                         </option>
191                                         <option name="t">
192                                                 <para>Allow the <emphasis>called</emphasis> user to transfer the calling user.</para>
193                                         </option>
194                                         <option name="T">
195                                                 <para>Allow the <emphasis>calling</emphasis> user to transfer the call.</para>
196                                         </option>
197                                         <option name="w">
198                                                 <para>Allow the <emphasis>called</emphasis> user to write the conversation to
199                                                 disk via Monitor.</para>
200                                         </option>
201                                         <option name="W">
202                                                 <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
203                                                 disk via Monitor.</para>
204                                         </option>
205                                         <option name="k">
206                                                 <para>Allow the <emphasis>called</emphasis> party to enable parking of the call by sending
207                                                 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
208                                         </option>
209                                         <option name="K">
210                                                 <para>Allow the <emphasis>calling</emphasis> party to enable parking of the call by sending
211                                                 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
212                                         </option>
213                                         <option name="x">
214                                                 <para>Allow the <emphasis>called</emphasis> user to write the conversation
215                                                 to disk via MixMonitor.</para>
216                                         </option>
217                                         <option name="X">
218                                                 <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
219                                                 disk via MixMonitor.</para>
220                                         </option>
221                                 </optionlist>
222                         </parameter>
223                         <parameter name="URL">
224                                 <para><replaceable>URL</replaceable> will be sent to the called party if the channel supports it.</para>
225                         </parameter>
226                         <parameter name="announceoverride" />
227                         <parameter name="timeout">
228                                 <para>Will cause the queue to fail out after a specified number of
229                                 seconds, checked between each <filename>queues.conf</filename> <replaceable>timeout</replaceable> and
230                                 <replaceable>retry</replaceable> cycle.</para>
231                         </parameter>
232                         <parameter name="AGI">
233                                 <para>Will setup an AGI script to be executed on the calling party's channel once they are
234                                 connected to a queue member.</para>
235                         </parameter>
236                         <parameter name="macro">
237                                 <para>Will run a macro on the called party's channel (the queue member) once the parties are connected.</para>
238                                 <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         time_t starttime;                    /*!< The time at which the member answered the current caller. */
1590         time_t lastcall;                     /*!< When last successful call was hungup */
1591         time_t lastpause;                    /*!< When started the last pause */
1592         struct call_queue *lastqueue;        /*!< Last queue we received a call */
1593         unsigned int dead:1;                 /*!< Used to detect members deleted in realtime */
1594         unsigned int delme:1;                /*!< Flag to delete entry on reload */
1595         char rt_uniqueid[80];                /*!< Unique id of realtime member entry */
1596         unsigned int ringinuse:1;            /*!< Flag to ring queue members even if their status is 'inuse' */
1597 };
1598
1599 enum empty_conditions {
1600         QUEUE_EMPTY_PENALTY = (1 << 0),
1601         QUEUE_EMPTY_PAUSED = (1 << 1),
1602         QUEUE_EMPTY_INUSE = (1 << 2),
1603         QUEUE_EMPTY_RINGING = (1 << 3),
1604         QUEUE_EMPTY_UNAVAILABLE = (1 << 4),
1605         QUEUE_EMPTY_INVALID = (1 << 5),
1606         QUEUE_EMPTY_UNKNOWN = (1 << 6),
1607         QUEUE_EMPTY_WRAPUP = (1 << 7),
1608 };
1609
1610 enum member_properties {
1611         MEMBER_PENALTY = 0,
1612         MEMBER_RINGINUSE = 1,
1613 };
1614
1615 /* values used in multi-bit flags in call_queue */
1616 #define ANNOUNCEHOLDTIME_ALWAYS 1
1617 #define ANNOUNCEHOLDTIME_ONCE 2
1618 #define QUEUE_EVENT_VARIABLES 3
1619
1620 struct penalty_rule {
1621         int time;                           /*!< Number of seconds that need to pass before applying this rule */
1622         int max_value;                      /*!< The amount specified in the penalty rule for max penalty */
1623         int min_value;                      /*!< The amount specified in the penalty rule for min penalty */
1624         int raise_value;                      /*!< The amount specified in the penalty rule for min penalty */
1625         int max_relative;                   /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
1626         int min_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1627         int raise_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1628         AST_LIST_ENTRY(penalty_rule) list;  /*!< Next penalty_rule */
1629 };
1630
1631 #define ANNOUNCEPOSITION_YES 1 /*!< We announce position */
1632 #define ANNOUNCEPOSITION_NO 2 /*!< We don't announce position */
1633 #define ANNOUNCEPOSITION_MORE_THAN 3 /*!< We say "Currently there are more than <limit>" */
1634 #define ANNOUNCEPOSITION_LIMIT 4 /*!< We not announce position more than <limit> */
1635
1636 struct call_queue {
1637         AST_DECLARE_STRING_FIELDS(
1638                 /*! Queue name */
1639                 AST_STRING_FIELD(name);
1640                 /*! Music on Hold class */
1641                 AST_STRING_FIELD(moh);
1642                 /*! Announcement to play when call is answered */
1643                 AST_STRING_FIELD(announce);
1644                 /*! Exit context */
1645                 AST_STRING_FIELD(context);
1646                 /*! Macro to run upon member connection */
1647                 AST_STRING_FIELD(membermacro);
1648                 /*! Gosub to run upon member connection */
1649                 AST_STRING_FIELD(membergosub);
1650                 /*! Default rule to use if none specified in call to Queue() */
1651                 AST_STRING_FIELD(defaultrule);
1652                 /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
1653                 AST_STRING_FIELD(sound_next);
1654                 /*! Sound file: "There are currently" (def. queue-thereare) */
1655                 AST_STRING_FIELD(sound_thereare);
1656                 /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
1657                 AST_STRING_FIELD(sound_calls);
1658                 /*! Sound file: "Currently there are more than" (def. queue-quantity1) */
1659                 AST_STRING_FIELD(queue_quantity1);
1660                 /*! Sound file: "callers waiting to speak with a representative" (def. queue-quantity2) */
1661                 AST_STRING_FIELD(queue_quantity2);
1662                 /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
1663                 AST_STRING_FIELD(sound_holdtime);
1664                 /*! Sound file: "minutes." (def. queue-minutes) */
1665                 AST_STRING_FIELD(sound_minutes);
1666                 /*! Sound file: "minute." (def. queue-minute) */
1667                 AST_STRING_FIELD(sound_minute);
1668                 /*! Sound file: "seconds." (def. queue-seconds) */
1669                 AST_STRING_FIELD(sound_seconds);
1670                 /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
1671                 AST_STRING_FIELD(sound_thanks);
1672                 /*! Sound file: Custom announce for caller, no default */
1673                 AST_STRING_FIELD(sound_callerannounce);
1674                 /*! Sound file: "Hold time" (def. queue-reporthold) */
1675                 AST_STRING_FIELD(sound_reporthold);
1676         );
1677         /*! Sound files: Custom announce, no default */
1678         struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
1679         unsigned int dead:1;
1680         unsigned int ringinuse:1;
1681         unsigned int announce_to_first_user:1; /*!< Whether or not we announce to the first user in a queue */
1682         unsigned int setinterfacevar:1;
1683         unsigned int setqueuevar:1;
1684         unsigned int setqueueentryvar:1;
1685         unsigned int reportholdtime:1;
1686         unsigned int wrapped:1;
1687         unsigned int timeoutrestart:1;
1688         unsigned int announceholdtime:2;
1689         unsigned int announceposition:3;
1690         unsigned int announceposition_only_up:1; /*!< Only announce position if it has improved */
1691         int strategy:4;
1692         unsigned int realtime:1;
1693         unsigned int found:1;
1694         unsigned int relativeperiodicannounce:1;
1695         unsigned int autopausebusy:1;
1696         unsigned int autopauseunavail:1;
1697         enum empty_conditions joinempty;
1698         enum empty_conditions leavewhenempty;
1699         int announcepositionlimit;          /*!< How many positions we announce? */
1700         int announcefrequency;              /*!< How often to announce their position */
1701         int minannouncefrequency;           /*!< The minimum number of seconds between position announcements (def. 15) */
1702         int periodicannouncefrequency;      /*!< How often to play periodic announcement */
1703         int numperiodicannounce;            /*!< The number of periodic announcements configured */
1704         int randomperiodicannounce;         /*!< Are periodic announcments randomly chosen */
1705         int roundingseconds;                /*!< How many seconds do we round to? */
1706         int holdtime;                       /*!< Current avg holdtime, based on an exponential average */
1707         int talktime;                       /*!< Current avg talktime, based on the same exponential average */
1708         int callscompleted;                 /*!< Number of queue calls completed */
1709         int callsabandoned;                 /*!< Number of queue calls abandoned */
1710         int callsabandonedinsl;             /*!< Number of queue calls abandoned in servicelevel */
1711         int servicelevel;                   /*!< seconds setting for servicelevel*/
1712         int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
1713         char monfmt[8];                     /*!< Format to use when recording calls */
1714         int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
1715         int count;                          /*!< How many entries */
1716         int maxlen;                         /*!< Max number of entries */
1717         int wrapuptime;                     /*!< Wrapup Time */
1718         int penaltymemberslimit;            /*!< Disregard penalty when queue has fewer than this many members */
1719
1720         int retry;                          /*!< Retry calling everyone after this amount of time */
1721         int timeout;                        /*!< How long to wait for an answer */
1722         int weight;                         /*!< Respective weight */
1723         int autopause;                      /*!< Auto pause queue members if they fail to answer */
1724         int autopausedelay;                 /*!< Delay auto pause for autopausedelay seconds since last call */
1725         int timeoutpriority;                /*!< Do we allow a fraction of the timeout to occur for a ring? */
1726
1727         /* Queue strategy things */
1728         int rrpos;                          /*!< Round Robin - position */
1729         int memberdelay;                    /*!< Seconds to delay connecting member to caller */
1730         int autofill;                       /*!< Ignore the head call status and ring an available agent */
1731
1732         struct ao2_container *members;      /*!< Head of the list of members */
1733         struct queue_ent *head;             /*!< Head of the list of callers */
1734         AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
1735         AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
1736 };
1737
1738 struct rule_list {
1739         char name[80];
1740         AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
1741         AST_LIST_ENTRY(rule_list) list;
1742 };
1743
1744 static AST_LIST_HEAD_STATIC(rule_lists, rule_list);
1745
1746 static struct ao2_container *queues;
1747
1748 static void update_realtime_members(struct call_queue *q);
1749 static struct member *interface_exists(struct call_queue *q, const char *interface);
1750 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
1751 static int update_queue(struct call_queue *q, struct member *member, int callcompletedinsl, time_t starttime);
1752
1753 static struct member *find_member_by_queuename_and_interface(const char *queuename, const char *interface);
1754 /*! \brief sets the QUEUESTATUS channel variable */
1755 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
1756 {
1757         int i;
1758
1759         for (i = 0; i < ARRAY_LEN(queue_results); i++) {
1760                 if (queue_results[i].id == res) {
1761                         pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
1762                         return;
1763                 }
1764         }
1765 }
1766
1767 static const char *int2strat(int strategy)
1768 {
1769         int x;
1770
1771         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1772                 if (strategy == strategies[x].strategy) {
1773                         return strategies[x].name;
1774                 }
1775         }
1776
1777         return "<unknown>";
1778 }
1779
1780 static int strat2int(const char *strategy)
1781 {
1782         int x;
1783
1784         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1785                 if (!strcasecmp(strategy, strategies[x].name)) {
1786                         return strategies[x].strategy;
1787                 }
1788         }
1789
1790         return -1;
1791 }
1792
1793 static int autopause2int(const char *autopause)
1794 {
1795         int x;
1796         /*This 'double check' that default value is OFF */
1797         if (ast_strlen_zero(autopause)) {
1798                 return QUEUE_AUTOPAUSE_OFF;
1799         }
1800
1801         /*This 'double check' is to ensure old values works */
1802         if(ast_true(autopause)) {
1803                 return QUEUE_AUTOPAUSE_ON;
1804         }
1805
1806         for (x = 0; x < ARRAY_LEN(autopausesmodes); x++) {
1807                 if (!strcasecmp(autopause, autopausesmodes[x].name)) {
1808                         return autopausesmodes[x].autopause;
1809                 }
1810         }
1811
1812         /*This 'double check' that default value is OFF */
1813         return QUEUE_AUTOPAUSE_OFF;
1814 }
1815
1816 static int queue_hash_cb(const void *obj, const int flags)
1817 {
1818         const struct call_queue *q = obj;
1819
1820         return ast_str_case_hash(q->name);
1821 }
1822
1823 static int queue_cmp_cb(void *obj, void *arg, int flags)
1824 {
1825         struct call_queue *q = obj, *q2 = arg;
1826         return !strcasecmp(q->name, q2->name) ? CMP_MATCH | CMP_STOP : 0;
1827 }
1828
1829 /*! \internal
1830  * \brief ao2_callback, Decreases queuepos of all followers with a queuepos greater than arg.
1831  * \param obj the member being acted on
1832  * \param arg pointer to an integer containing the position value that was removed and requires reduction for anything above
1833  */
1834 static int queue_member_decrement_followers(void *obj, void *arg, int flag)
1835 {
1836         struct member *mem = obj;
1837         int *decrement_followers_after = arg;
1838
1839         if (mem->queuepos > *decrement_followers_after) {
1840                 mem->queuepos--;
1841         }
1842
1843         return 0;
1844 }
1845
1846 /*! \internal
1847  * \brief ao2_callback, finds members in a queue marked for deletion and in a cascading fashion runs queue_member_decrement_followers
1848  *        on them. This callback should always be ran before performing mass unlinking of delmarked members from queues.
1849  * \param obj member being acted on
1850  * \param arg pointer to the queue members are being removed from
1851  */
1852 static int queue_delme_members_decrement_followers(void *obj, void *arg, int flag)
1853 {
1854         struct member *mem = obj;
1855         struct call_queue *queue = arg;
1856         int rrpos = mem->queuepos;
1857
1858         if (mem->delme) {
1859                 ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &rrpos);
1860         }
1861
1862         return 0;
1863 }
1864
1865 /*! \internal
1866  * \brief Use this to decrement followers during removal of a member
1867  * \param queue which queue the member is being removed from
1868  * \param mem which member is being removed from the queue
1869  */
1870 static void queue_member_follower_removal(struct call_queue *queue, struct member *mem)
1871 {
1872         int pos = mem->queuepos;
1873
1874         /* 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
1875          * who would have been next otherwise. */
1876         if (pos < queue->rrpos) {
1877                 queue->rrpos--;
1878         }
1879
1880         ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &pos);
1881 }
1882
1883 #define queue_ref(q)                            _queue_ref(q, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1884 #define queue_unref(q)                          _queue_unref(q, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1885 #define queue_t_ref(q, tag)                     _queue_ref(q, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1886 #define queue_t_unref(q, tag)           _queue_unref(q, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1887 #define queues_t_link(c, q, tag)        ao2_t_link(c, q, tag)
1888 #define queues_t_unlink(c, q, tag)      ao2_t_unlink(c, q, tag)
1889
1890 static inline struct call_queue *_queue_ref(struct call_queue *q, const char *tag, const char *file, int line, const char *filename)
1891 {
1892         __ao2_ref(q, 1, tag, file, line, filename);
1893         return q;
1894 }
1895
1896 static inline struct call_queue *_queue_unref(struct call_queue *q, const char *tag, const char *file, int line, const char *filename)
1897 {
1898         if (q) {
1899                 __ao2_ref(q, -1, tag, file, line, filename);
1900         }
1901         return NULL;
1902 }
1903
1904 /*! \brief Set variables of queue */
1905 static void set_queue_variables(struct call_queue *q, struct ast_channel *chan)
1906 {
1907         char interfacevar[256]="";
1908         float sl = 0;
1909
1910         ao2_lock(q);
1911
1912         if (q->setqueuevar) {
1913                 sl = 0;
1914                 if (q->callscompleted > 0) {
1915                         sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
1916                 }
1917
1918                 snprintf(interfacevar, sizeof(interfacevar),
1919                         "QUEUENAME=%s,QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
1920                         q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned,  q->servicelevel, sl);
1921
1922                 ao2_unlock(q);
1923
1924                 pbx_builtin_setvar_multiple(chan, interfacevar);
1925         } else {
1926                 ao2_unlock(q);
1927         }
1928 }
1929
1930 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
1931 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
1932 {
1933         struct queue_ent *cur;
1934
1935         if (!q || !new)
1936                 return;
1937         if (prev) {
1938                 cur = prev->next;
1939                 prev->next = new;
1940         } else {
1941                 cur = q->head;
1942                 q->head = new;
1943         }
1944         new->next = cur;
1945
1946         /* every queue_ent must have a reference to it's parent call_queue, this
1947          * reference does not go away until the end of the queue_ent's life, meaning
1948          * that even when the queue_ent leaves the call_queue this ref must remain. */
1949         queue_ref(q);
1950         new->parent = q;
1951         new->pos = ++(*pos);
1952         new->opos = *pos;
1953 }
1954
1955 static struct ast_manager_event_blob *queue_channel_to_ami(const char *type, struct stasis_message *message)
1956 {
1957         struct ast_channel_blob *obj = stasis_message_data(message);
1958         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
1959         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
1960
1961         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
1962         event_string = ast_manager_str_from_json_object(obj->blob, NULL);
1963         if (!channel_string || !event_string) {
1964                 return NULL;
1965         }
1966
1967         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
1968                 "%s"
1969                 "%s",
1970                 ast_str_buffer(channel_string),
1971                 ast_str_buffer(event_string));
1972 }
1973
1974 static struct ast_manager_event_blob *queue_caller_join_to_ami(struct stasis_message *message)
1975 {
1976         return queue_channel_to_ami("QueueCallerJoin", message);
1977 }
1978
1979 static struct ast_manager_event_blob *queue_caller_leave_to_ami(struct stasis_message *message)
1980 {
1981         return queue_channel_to_ami("QueueCallerLeave", message);
1982 }
1983
1984 static struct ast_manager_event_blob *queue_caller_abandon_to_ami(struct stasis_message *message)
1985 {
1986         return queue_channel_to_ami("QueueCallerAbandon", message);
1987 }
1988
1989 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_join_type,
1990         .to_ami = queue_caller_join_to_ami,
1991         );
1992 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_leave_type,
1993         .to_ami = queue_caller_leave_to_ami,
1994         );
1995 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_abandon_type,
1996         .to_ami = queue_caller_abandon_to_ami,
1997         );
1998
1999 static struct ast_manager_event_blob *queue_member_to_ami(const char *type, struct stasis_message *message)
2000 {
2001         struct ast_json_payload *payload = stasis_message_data(message);
2002         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
2003
2004         event_string = ast_manager_str_from_json_object(payload->json, NULL);
2005         if (!event_string) {
2006                 return NULL;
2007         }
2008
2009         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
2010                 "%s",
2011                 ast_str_buffer(event_string));
2012 }
2013
2014 static struct ast_manager_event_blob *queue_member_status_to_ami(struct stasis_message *message)
2015 {
2016         return queue_member_to_ami("QueueMemberStatus", message);
2017 }
2018
2019 static struct ast_manager_event_blob *queue_member_added_to_ami(struct stasis_message *message)
2020 {
2021         return queue_member_to_ami("QueueMemberAdded", message);
2022 }
2023
2024 static struct ast_manager_event_blob *queue_member_removed_to_ami(struct stasis_message *message)
2025 {
2026         return queue_member_to_ami("QueueMemberRemoved", message);
2027 }
2028
2029 static struct ast_manager_event_blob *queue_member_pause_to_ami(struct stasis_message *message)
2030 {
2031         return queue_member_to_ami("QueueMemberPause", message);
2032 }
2033
2034 static struct ast_manager_event_blob *queue_member_penalty_to_ami(struct stasis_message *message)
2035 {
2036         return queue_member_to_ami("QueueMemberPenalty", message);
2037 }
2038
2039 static struct ast_manager_event_blob *queue_member_ringinuse_to_ami(struct stasis_message *message)
2040 {
2041         return queue_member_to_ami("QueueMemberRinginuse", message);
2042 }
2043
2044 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_status_type,
2045         .to_ami = queue_member_status_to_ami,
2046         );
2047 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_added_type,
2048         .to_ami = queue_member_added_to_ami,
2049         );
2050 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_removed_type,
2051         .to_ami = queue_member_removed_to_ami,
2052         );
2053 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_pause_type,
2054         .to_ami = queue_member_pause_to_ami,
2055         );
2056 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_penalty_type,
2057         .to_ami = queue_member_penalty_to_ami,
2058         );
2059 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_ringinuse_type,
2060         .to_ami = queue_member_ringinuse_to_ami,
2061         );
2062
2063 static struct ast_manager_event_blob *queue_multi_channel_to_ami(const char *type, struct stasis_message *message)
2064 {
2065         struct ast_multi_channel_blob *obj = stasis_message_data(message);
2066         struct ast_channel_snapshot *caller;
2067         struct ast_channel_snapshot *agent;
2068         RAII_VAR(struct ast_str *, caller_event_string, NULL, ast_free);
2069         RAII_VAR(struct ast_str *, agent_event_string, NULL, ast_free);
2070         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
2071
2072         caller = ast_multi_channel_blob_get_channel(obj, "caller");
2073         if (caller) {
2074                 caller_event_string = ast_manager_build_channel_state_string(caller);
2075                 if (!caller_event_string) {
2076                         ast_log(LOG_NOTICE, "No caller event string, bailing\n");
2077                         return NULL;
2078                 }
2079         }
2080
2081         agent = ast_multi_channel_blob_get_channel(obj, "agent");
2082         if (agent) {
2083                 agent_event_string = ast_manager_build_channel_state_string_prefix(agent, "Dest");
2084                 if (!agent_event_string) {
2085                         ast_log(LOG_NOTICE, "No agent event string, bailing\n");
2086                         return NULL;
2087                 }
2088         }
2089
2090         event_string = ast_manager_str_from_json_object(ast_multi_channel_blob_get_json(obj), NULL);
2091         if (!event_string) {
2092                 return NULL;
2093         }
2094
2095         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
2096                 "%s"
2097                 "%s"
2098                 "%s",
2099                 caller_event_string ? ast_str_buffer(caller_event_string) : "",
2100                 agent_event_string ? ast_str_buffer(agent_event_string) : "",
2101                 ast_str_buffer(event_string));
2102 }
2103
2104 static struct ast_manager_event_blob *queue_agent_called_to_ami(struct stasis_message *message)
2105 {
2106         return queue_multi_channel_to_ami("AgentCalled", message);
2107 }
2108
2109 static struct ast_manager_event_blob *queue_agent_connect_to_ami(struct stasis_message *message)
2110 {
2111         return queue_multi_channel_to_ami("AgentConnect", message);
2112 }
2113
2114 static struct ast_manager_event_blob *queue_agent_complete_to_ami(struct stasis_message *message)
2115 {
2116         return queue_multi_channel_to_ami("AgentComplete", message);
2117 }
2118
2119 static struct ast_manager_event_blob *queue_agent_dump_to_ami(struct stasis_message *message)
2120 {
2121         return queue_multi_channel_to_ami("AgentDump", message);
2122 }
2123
2124 static struct ast_manager_event_blob *queue_agent_ringnoanswer_to_ami(struct stasis_message *message)
2125 {
2126         return queue_multi_channel_to_ami("AgentRingNoAnswer", message);
2127 }
2128
2129 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_called_type,
2130         .to_ami = queue_agent_called_to_ami,
2131         );
2132 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_connect_type,
2133         .to_ami = queue_agent_connect_to_ami,
2134         );
2135 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_complete_type,
2136         .to_ami = queue_agent_complete_to_ami,
2137         );
2138 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_dump_type,
2139         .to_ami = queue_agent_dump_to_ami,
2140         );
2141 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_ringnoanswer_type,
2142         .to_ami = queue_agent_ringnoanswer_to_ami,
2143         );
2144
2145 static void queue_publish_multi_channel_snapshot_blob(struct stasis_topic *topic,
2146                 struct ast_channel_snapshot *caller_snapshot,
2147                 struct ast_channel_snapshot *agent_snapshot,
2148                 struct stasis_message_type *type, struct ast_json *blob)
2149 {
2150         RAII_VAR(struct ast_multi_channel_blob *, payload, NULL, ao2_cleanup);
2151         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2152
2153         if (!type) {
2154                 return;
2155         }
2156
2157         payload = ast_multi_channel_blob_create(blob);
2158         if (!payload) {
2159                 return;
2160         }
2161
2162         ast_multi_channel_blob_add_channel(payload, "caller", caller_snapshot);
2163         if (agent_snapshot) {
2164                 ast_multi_channel_blob_add_channel(payload, "agent", agent_snapshot);
2165         }
2166
2167         msg = stasis_message_create(type, payload);
2168         if (!msg) {
2169                 return;
2170         }
2171
2172         stasis_publish(topic, msg);
2173 }
2174
2175 static void queue_publish_multi_channel_blob(struct ast_channel *caller, struct ast_channel *agent,
2176                 struct stasis_message_type *type, struct ast_json *blob)
2177 {
2178         RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
2179         RAII_VAR(struct ast_channel_snapshot *, agent_snapshot, NULL, ao2_cleanup);
2180
2181         ast_channel_lock(caller);
2182         caller_snapshot = ast_channel_snapshot_create(caller);
2183         ast_channel_unlock(caller);
2184         ast_channel_lock(agent);
2185         agent_snapshot = ast_channel_snapshot_create(agent);
2186         ast_channel_unlock(agent);
2187
2188         if (!caller_snapshot || !agent_snapshot) {
2189                 return;
2190         }
2191
2192         queue_publish_multi_channel_snapshot_blob(ast_channel_topic(caller), caller_snapshot,
2193                         agent_snapshot, type, blob);
2194 }
2195
2196 /*!
2197  * \internal
2198  * \brief Publish the member blob.
2199  * \since 12.0.0
2200  *
2201  * \param type Stasis message type to publish.
2202  * \param blob The information being published.
2203  *
2204  * \note The json blob reference is passed to this function.
2205  *
2206  * \return Nothing
2207  */
2208 static void queue_publish_member_blob(struct stasis_message_type *type, struct ast_json *blob)
2209 {
2210         RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
2211         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2212
2213         if (!blob || !type) {
2214                 return;
2215         }
2216
2217         payload = ast_json_payload_create(blob);
2218         ast_json_unref(blob);
2219         if (!payload) {
2220                 return;
2221         }
2222
2223         msg = stasis_message_create(type, payload);
2224         if (!msg) {
2225                 return;
2226         }
2227
2228         stasis_publish(ast_manager_get_topic(), msg);
2229 }
2230
2231 static struct ast_json *queue_member_blob_create(struct call_queue *q, struct member *mem)
2232 {
2233         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}",
2234                 "Queue", q->name,
2235                 "MemberName", mem->membername,
2236                 "Interface", mem->interface,
2237                 "StateInterface", mem->state_interface,
2238                 "Membership", (mem->dynamic ? "dynamic" : (mem->realtime ? "realtime" : "static")),
2239                 "Penalty", mem->penalty,
2240                 "CallsTaken", mem->calls,
2241                 "LastCall", (int)mem->lastcall,
2242                 "LastPause", (int)mem->lastpause,
2243                 "InCall", mem->starttime ? 1 : 0,
2244                 "Status", mem->status,
2245                 "Paused", mem->paused,
2246                 "PausedReason", mem->reason_paused,
2247                 "Ringinuse", mem->ringinuse);
2248 }
2249
2250 /*! \brief Check if members are available
2251  *
2252  * This function checks to see if members are available to be called. If any member
2253  * is available, the function immediately returns 0. If no members are available,
2254  * then -1 is returned.
2255  */
2256 static int get_member_status(struct call_queue *q, int max_penalty, int min_penalty, int raise_penalty, enum empty_conditions conditions, int devstate)
2257 {
2258         struct member *member;
2259         struct ao2_iterator mem_iter;
2260
2261         ao2_lock(q);
2262         mem_iter = ao2_iterator_init(q->members, 0);
2263         for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
2264                 int penalty = member->penalty;
2265                 if (raise_penalty != INT_MAX && penalty < raise_penalty) {
2266                         ast_debug(4, "%s is having his penalty raised up from %d to %d\n", member->membername, penalty, raise_penalty);
2267                         penalty = raise_penalty;
2268                 }
2269                 if ((max_penalty != INT_MAX && penalty > max_penalty) || (min_penalty != INT_MAX && penalty < min_penalty)) {
2270                         if (conditions & QUEUE_EMPTY_PENALTY) {
2271                                 ast_debug(4, "%s is unavailable because his penalty is not between %d and %d\n", member->membername, min_penalty, max_penalty);
2272                                 continue;
2273                         }
2274                 }
2275
2276                 switch (devstate ? ast_device_state(member->state_interface) : member->status) {
2277                 case AST_DEVICE_INVALID:
2278                         if (conditions & QUEUE_EMPTY_INVALID) {
2279                                 ast_debug(4, "%s is unavailable because his device state is 'invalid'\n", member->membername);
2280                                 break;
2281                         }
2282                         goto default_case;
2283                 case AST_DEVICE_UNAVAILABLE:
2284                         if (conditions & QUEUE_EMPTY_UNAVAILABLE) {
2285                                 ast_debug(4, "%s is unavailable because his device state is 'unavailable'\n", member->membername);
2286                                 break;
2287                         }
2288                         goto default_case;
2289                 case AST_DEVICE_INUSE:
2290                         if (conditions & QUEUE_EMPTY_INUSE) {
2291                                 ast_debug(4, "%s is unavailable because his device state is 'inuse'\n", member->membername);
2292                                 break;
2293                         }
2294                         goto default_case;
2295                 case AST_DEVICE_RINGING:
2296                         if (conditions & QUEUE_EMPTY_RINGING) {
2297                                 ast_debug(4, "%s is unavailable because his device state is 'ringing'\n", member->membername);
2298                                 break;
2299                         }
2300                         goto default_case;
2301                 case AST_DEVICE_UNKNOWN:
2302                         if (conditions & QUEUE_EMPTY_UNKNOWN) {
2303                                 ast_debug(4, "%s is unavailable because his device state is 'unknown'\n", member->membername);
2304                                 break;
2305                         }
2306                         /* Fall-through */
2307                 default:
2308                 default_case:
2309                         if (member->paused && (conditions & QUEUE_EMPTY_PAUSED)) {
2310                                 ast_debug(4, "%s is unavailable because he is paused'\n", member->membername);
2311                                 break;
2312                         } else if ((conditions & QUEUE_EMPTY_WRAPUP) && member->lastcall && q->wrapuptime && (time(NULL) - q->wrapuptime < member->lastcall)) {
2313                                 ast_debug(4, "%s is unavailable because it has only been %d seconds since his last call (wrapup time is %d)\n", member->membername, (int) (time(NULL) - member->lastcall), q->wrapuptime);
2314                                 break;
2315                         } else {
2316                                 ao2_ref(member, -1);
2317                                 ao2_iterator_destroy(&mem_iter);
2318                                 ao2_unlock(q);
2319                                 ast_debug(4, "%s is available.\n", member->membername);
2320                                 return 0;
2321                         }
2322                         break;
2323                 }
2324         }
2325         ao2_iterator_destroy(&mem_iter);
2326         ao2_unlock(q);
2327
2328         if (!devstate && (conditions & QUEUE_EMPTY_RINGING)) {
2329                 /* member state still may be RINGING due to lag in event message - check again with device state */
2330                 return get_member_status(q, max_penalty, min_penalty, raise_penalty, conditions, 1);
2331         }
2332         return -1;
2333 }
2334
2335 /*
2336  * A "pool" of member objects that calls are currently pending on. If an
2337  * agent is a member of multiple queues it's possible for that agent to be
2338  * called by each of the queues at the same time. This happens because device
2339  * state is slow to notify the queue app of one of it's member's being rung.
2340  * This "pool" allows us to track which members are currently being rung while
2341  * we wait on the device state change.
2342  */
2343 static struct ao2_container *pending_members;
2344 #define MAX_CALL_ATTEMPT_BUCKETS 353
2345
2346 static int pending_members_hash(const void *obj, const int flags)
2347 {
2348         const struct member *object;
2349         const char *key;
2350
2351         switch (flags & OBJ_SEARCH_MASK) {
2352         case OBJ_SEARCH_KEY:
2353                 key = obj;
2354                 break;
2355         case OBJ_SEARCH_OBJECT:
2356                 object = obj;
2357                 key = object->interface;
2358                 break;
2359         default:
2360                 ast_assert(0);
2361                 return 0;
2362         }
2363         return ast_str_case_hash(key);
2364 }
2365
2366 static int pending_members_cmp(void *obj, void *arg, int flags)
2367 {
2368         const struct member *object_left = obj;
2369         const struct member *object_right = arg;
2370         const char *right_key = arg;
2371         int cmp;
2372
2373         switch (flags & OBJ_SEARCH_MASK) {
2374         case OBJ_SEARCH_OBJECT:
2375                 right_key = object_right->interface;
2376                 /* Fall through */
2377         case OBJ_SEARCH_KEY:
2378                 cmp = strcasecmp(object_left->interface, right_key);
2379                 break;
2380         case OBJ_SEARCH_PARTIAL_KEY:
2381                 /* Not supported by container. */
2382                 ast_assert(0);
2383                 return 0;
2384         default:
2385                 cmp = 0;
2386                 break;
2387         }
2388         if (cmp) {
2389                 return 0;
2390         }
2391         return CMP_MATCH;
2392 }
2393
2394 static void pending_members_remove(struct member *mem)
2395 {
2396         ast_debug(3, "Removed %s from pending_members\n", mem->membername);
2397         ao2_find(pending_members, mem, OBJ_POINTER | OBJ_NODATA | OBJ_UNLINK);
2398 }
2399
2400 /*! \brief set a member's status based on device state of that member's state_interface.
2401  *
2402  * Lock interface list find sc, iterate through each queues queue_member list for member to
2403  * update state inside queues
2404 */
2405 static void update_status(struct call_queue *q, struct member *m, const int status)
2406 {
2407         if (m->status != status) {
2408                 /* If this member has transitioned to being available then update their queue
2409                  * information. If they are currently in a call then the leg to the agent will be
2410                  * considered done and the call finished.
2411                  */
2412                 if (status == AST_DEVICE_NOT_INUSE) {
2413                         update_queue(q, m, m->callcompletedinsl, m->starttime);
2414                 }
2415
2416                 m->status = status;
2417
2418                 /* Remove the member from the pending members pool only when the status changes.
2419                  * This is not done unconditionally because we can occasionally see multiple
2420                  * device state notifications of not in use after a previous call has ended,
2421                  * including after we have initiated a new call. This is more likely to
2422                  * happen when there is latency in the connection to the member.
2423                  */
2424                 pending_members_remove(m);
2425         }
2426
2427         queue_publish_member_blob(queue_member_status_type(), queue_member_blob_create(q, m));
2428 }
2429
2430 /*!
2431  * \internal
2432  * \brief Determine if a queue member is available
2433  * \retval 1 if the member is available
2434  * \retval 0 if the member is not available
2435  */
2436 static int is_member_available(struct call_queue *q, struct member *mem)
2437 {
2438         int available = 0;
2439
2440         switch (mem->status) {
2441                 case AST_DEVICE_INVALID:
2442                 case AST_DEVICE_UNAVAILABLE:
2443                         break;
2444                 case AST_DEVICE_INUSE:
2445                 case AST_DEVICE_BUSY:
2446                 case AST_DEVICE_RINGING:
2447                 case AST_DEVICE_RINGINUSE:
2448                 case AST_DEVICE_ONHOLD:
2449                         if (!mem->ringinuse) {
2450                                 break;
2451                         }
2452                         /* else fall through */
2453                 case AST_DEVICE_NOT_INUSE:
2454                 case AST_DEVICE_UNKNOWN:
2455                         if (!mem->paused) {
2456                                 available = 1;
2457                         }
2458                         break;
2459         }
2460
2461         /* Let wrapuptimes override device state availability */
2462         if (mem->lastcall && q->wrapuptime && (time(NULL) - q->wrapuptime < mem->lastcall)) {
2463                 available = 0;
2464         }
2465         return available;
2466 }
2467
2468 /*! \brief set a member's status based on device state of that member's interface*/
2469 static void device_state_cb(void *unused, struct stasis_subscription *sub, struct stasis_message *msg)
2470 {
2471         struct ao2_iterator miter, qiter;
2472         struct ast_device_state_message *dev_state;
2473         struct member *m;
2474         struct call_queue *q;
2475         char interface[80], *slash_pos;
2476         int found = 0;                  /* Found this member in any queue */
2477         int found_member;               /* Found this member in this queue */
2478         int avail = 0;                  /* Found an available member in this queue */
2479
2480         if (ast_device_state_message_type() != stasis_message_type(msg)) {
2481                 return;
2482         }
2483
2484         dev_state = stasis_message_data(msg);
2485         if (dev_state->eid) {
2486                 /* ignore non-aggregate states */
2487                 return;
2488         }
2489
2490         qiter = ao2_iterator_init(queues, 0);
2491         while ((q = ao2_t_iterator_next(&qiter, "Iterate over queues"))) {
2492                 ao2_lock(q);
2493
2494                 avail = 0;
2495                 found_member = 0;
2496                 miter = ao2_iterator_init(q->members, 0);
2497                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
2498                         if (!found_member) {
2499                                 ast_copy_string(interface, m->state_interface, sizeof(interface));
2500
2501                                 if ((slash_pos = strchr(interface, '/'))) {
2502                                         if (!strncasecmp(interface, "Local/", 6) && (slash_pos = strchr(slash_pos + 1, '/'))) {
2503                                                 *slash_pos = '\0';
2504                                         }
2505                                 }
2506
2507                                 if (!strcasecmp(interface, dev_state->device)) {
2508                                         found_member = 1;
2509                                         update_status(q, m, dev_state->state);
2510                                 }
2511                         }
2512
2513                         /* check every member until we find one NOT_INUSE */
2514                         if (!avail) {
2515                                 avail = is_member_available(q, m);
2516                         }
2517                         if (avail && found_member) {
2518                                 /* early exit as we've found an available member and the member of interest */
2519                                 ao2_ref(m, -1);
2520                                 break;
2521                         }
2522                 }
2523
2524                 if (found_member) {
2525                         found = 1;
2526                         if (avail) {
2527                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2528                         } else {
2529                                 ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2530                         }
2531                 }
2532
2533                 ao2_iterator_destroy(&miter);
2534
2535                 ao2_unlock(q);
2536                 queue_t_unref(q, "Done with iterator");
2537         }
2538         ao2_iterator_destroy(&qiter);
2539
2540         if (found) {
2541                 ast_debug(1, "Device '%s' changed to state '%u' (%s)\n",
2542                         dev_state->device,
2543                         dev_state->state,
2544                         ast_devstate2str(dev_state->state));
2545         } else {
2546                 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",
2547                         dev_state->device,
2548                         dev_state->state,
2549                         ast_devstate2str(dev_state->state));
2550         }
2551
2552         return;
2553 }
2554
2555 /*! \brief Helper function which converts from extension state to device state values */
2556 static int extensionstate2devicestate(int state)
2557 {
2558         switch (state) {
2559         case AST_EXTENSION_NOT_INUSE:
2560                 state = AST_DEVICE_NOT_INUSE;
2561                 break;
2562         case AST_EXTENSION_INUSE:
2563                 state = AST_DEVICE_INUSE;
2564                 break;
2565         case AST_EXTENSION_BUSY:
2566                 state = AST_DEVICE_BUSY;
2567                 break;
2568         case AST_EXTENSION_RINGING:
2569                 state = AST_DEVICE_RINGING;
2570                 break;
2571         case AST_EXTENSION_ONHOLD:
2572                 state = AST_DEVICE_ONHOLD;
2573                 break;
2574         case AST_EXTENSION_UNAVAILABLE:
2575                 state = AST_DEVICE_UNAVAILABLE;
2576                 break;
2577         case AST_EXTENSION_REMOVED:
2578         case AST_EXTENSION_DEACTIVATED:
2579         default:
2580                 state = AST_DEVICE_INVALID;
2581                 break;
2582         }
2583
2584         return state;
2585 }
2586
2587 static int extension_state_cb(const char *context, const char *exten, struct ast_state_cb_info *info, void *data)
2588 {
2589         struct ao2_iterator miter, qiter;
2590         struct member *m;
2591         struct call_queue *q;
2592         int state = info->exten_state;
2593         int found = 0, device_state = extensionstate2devicestate(state);
2594
2595         /* only interested in extension state updates involving device states */
2596         if (info->reason != AST_HINT_UPDATE_DEVICE) {
2597                 return 0;
2598         }
2599
2600         qiter = ao2_iterator_init(queues, 0);
2601         while ((q = ao2_t_iterator_next(&qiter, "Iterate through queues"))) {
2602                 ao2_lock(q);
2603
2604                 miter = ao2_iterator_init(q->members, 0);
2605                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
2606                         if (!strcmp(m->state_context, context) && !strcmp(m->state_exten, exten)) {
2607                                 update_status(q, m, device_state);
2608                                 ao2_ref(m, -1);
2609                                 found = 1;
2610                                 break;
2611                         }
2612                 }
2613                 ao2_iterator_destroy(&miter);
2614
2615                 ao2_unlock(q);
2616                 queue_t_unref(q, "Done with iterator");
2617         }
2618         ao2_iterator_destroy(&qiter);
2619
2620         if (found) {
2621                 ast_debug(1, "Extension '%s@%s' changed to state '%d' (%s)\n", exten, context, device_state, ast_devstate2str(device_state));
2622         } else {
2623                 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",
2624                           exten, context, device_state, ast_devstate2str(device_state));
2625         }
2626
2627         return 0;
2628 }
2629
2630 /*! \brief Return the current state of a member */
2631 static int get_queue_member_status(struct member *cur)
2632 {
2633         return ast_strlen_zero(cur->state_exten) ? ast_device_state(cur->state_interface) : extensionstate2devicestate(ast_extension_state(NULL, cur->state_context, cur->state_exten));
2634 }
2635
2636 static void destroy_queue_member_cb(void *obj)
2637 {
2638         struct member *mem = obj;
2639
2640         if (mem->state_id != -1) {
2641                 ast_extension_state_del(mem->state_id, extension_state_cb);
2642         }
2643 }
2644
2645 /*! \brief allocate space for new queue member and set fields based on parameters passed */
2646 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused, const char *state_interface, int ringinuse)
2647 {
2648         struct member *cur;
2649
2650         if ((cur = ao2_alloc(sizeof(*cur), destroy_queue_member_cb))) {
2651                 cur->ringinuse = ringinuse;
2652                 cur->penalty = penalty;
2653                 cur->paused = paused;
2654                 if (paused) {
2655                         time(&cur->lastpause); /* Update time of last pause */
2656                 }
2657                 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
2658                 if (!ast_strlen_zero(state_interface)) {
2659                         ast_copy_string(cur->state_interface, state_interface, sizeof(cur->state_interface));
2660                 } else {
2661                         ast_copy_string(cur->state_interface, interface, sizeof(cur->state_interface));
2662                 }
2663                 if (!ast_strlen_zero(membername)) {
2664                         ast_copy_string(cur->membername, membername, sizeof(cur->membername));
2665                 } else {
2666                         ast_copy_string(cur->membername, interface, sizeof(cur->membername));
2667                 }
2668                 if (!strchr(cur->interface, '/')) {
2669                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
2670                 }
2671                 if (!strncmp(cur->state_interface, "hint:", 5)) {
2672                         char *tmp = ast_strdupa(cur->state_interface), *context = tmp;
2673                         char *exten = strsep(&context, "@") + 5;
2674
2675                         ast_copy_string(cur->state_exten, exten, sizeof(cur->state_exten));
2676                         ast_copy_string(cur->state_context, S_OR(context, "default"), sizeof(cur->state_context));
2677
2678                         cur->state_id = ast_extension_state_add(cur->state_context, cur->state_exten, extension_state_cb, NULL);
2679                 } else {
2680                         cur->state_id = -1;
2681                 }
2682                 cur->status = get_queue_member_status(cur);
2683         }
2684
2685         return cur;
2686 }
2687
2688
2689 static int compress_char(const char c)
2690 {
2691         if (c < 32) {
2692                 return 0;
2693         } else if (c > 96) {
2694                 return c - 64;
2695         }
2696         return c - 32;
2697 }
2698
2699 static int member_hash_fn(const void *obj, const int flags)
2700 {
2701         const struct member *mem = obj;
2702         const char *interface = (flags & OBJ_KEY) ? obj : mem->interface;
2703         const char *chname = strchr(interface, '/');
2704         int ret = 0, i;
2705
2706         if (!chname) {
2707                 chname = interface;
2708         }
2709         for (i = 0; i < 5 && chname[i]; i++) {
2710                 ret += compress_char(chname[i]) << (i * 6);
2711         }
2712         return ret;
2713 }
2714
2715 static int member_cmp_fn(void *obj1, void *obj2, int flags)
2716 {
2717         struct member *mem1 = obj1;
2718         struct member *mem2 = obj2;
2719         const char *interface = (flags & OBJ_KEY) ? obj2 : mem2->interface;
2720
2721         return strcasecmp(mem1->interface, interface) ? 0 : CMP_MATCH | CMP_STOP;
2722 }
2723
2724 /*!
2725  * \brief Initialize Queue default values.
2726  * \note the queue's lock  must be held before executing this function
2727 */
2728 static void init_queue(struct call_queue *q)
2729 {
2730         int i;
2731         struct penalty_rule *pr_iter;
2732
2733         q->dead = 0;
2734         q->retry = DEFAULT_RETRY;
2735         q->timeout = DEFAULT_TIMEOUT;
2736         q->maxlen = 0;
2737
2738         ast_string_field_set(q, context, "");
2739
2740         q->announcefrequency = 0;
2741         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
2742         q->announceholdtime = 1;
2743         q->announceposition_only_up = 0;
2744         q->announcepositionlimit = 10; /* Default 10 positions */
2745         q->announceposition = ANNOUNCEPOSITION_YES; /* Default yes */
2746         q->roundingseconds = 0; /* Default - don't announce seconds */
2747         q->servicelevel = 0;
2748         q->ringinuse = 1;
2749         q->announce_to_first_user = 0;
2750         q->setinterfacevar = 0;
2751         q->setqueuevar = 0;
2752         q->setqueueentryvar = 0;
2753         q->autofill = autofill_default;
2754         q->montype = montype_default;
2755         q->monfmt[0] = '\0';
2756         q->reportholdtime = 0;
2757         q->wrapuptime = 0;
2758         q->penaltymemberslimit = 0;
2759         q->joinempty = 0;
2760         q->leavewhenempty = 0;
2761         q->memberdelay = 0;
2762         q->weight = 0;
2763         q->timeoutrestart = 0;
2764         q->periodicannouncefrequency = 0;
2765         q->randomperiodicannounce = 0;
2766         q->numperiodicannounce = 0;
2767         q->autopause = QUEUE_AUTOPAUSE_OFF;
2768         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
2769         q->autopausedelay = 0;
2770         if (!q->members) {
2771                 if (q->strategy == QUEUE_STRATEGY_LINEAR || q->strategy == QUEUE_STRATEGY_RRORDERED) {
2772                         /* linear strategy depends on order, so we have to place all members in a single bucket */
2773                         q->members = ao2_container_alloc(1, member_hash_fn, member_cmp_fn);
2774                 } else {
2775                         q->members = ao2_container_alloc(37, member_hash_fn, member_cmp_fn);
2776                 }
2777         }
2778         q->found = 1;
2779
2780         ast_string_field_set(q, moh, "");
2781         ast_string_field_set(q, sound_next, "queue-youarenext");
2782         ast_string_field_set(q, sound_thereare, "queue-thereare");
2783         ast_string_field_set(q, sound_calls, "queue-callswaiting");
2784         ast_string_field_set(q, queue_quantity1, "queue-quantity1");
2785         ast_string_field_set(q, queue_quantity2, "queue-quantity2");
2786         ast_string_field_set(q, sound_holdtime, "queue-holdtime");
2787         ast_string_field_set(q, sound_minutes, "queue-minutes");
2788         ast_string_field_set(q, sound_minute, "queue-minute");
2789         ast_string_field_set(q, sound_seconds, "queue-seconds");
2790         ast_string_field_set(q, sound_thanks, "queue-thankyou");
2791         ast_string_field_set(q, sound_reporthold, "queue-reporthold");
2792
2793         if (!q->sound_periodicannounce[0]) {
2794                 q->sound_periodicannounce[0] = ast_str_create(32);
2795         }
2796
2797         if (q->sound_periodicannounce[0]) {
2798                 ast_str_set(&q->sound_periodicannounce[0], 0, "queue-periodic-announce");
2799         }
2800
2801         for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
2802                 if (q->sound_periodicannounce[i]) {
2803                         ast_str_set(&q->sound_periodicannounce[i], 0, "%s", "");
2804                 }
2805         }
2806
2807         while ((pr_iter = AST_LIST_REMOVE_HEAD(&q->rules,list))) {
2808                 ast_free(pr_iter);
2809         }
2810
2811         /* On restart assume no members are available.
2812          * The queue_avail hint is a boolean state to indicate whether a member is available or not.
2813          *
2814          * This seems counter intuitive, but is required to light a BLF
2815          * AST_DEVICE_INUSE indicates no members are available.
2816          * AST_DEVICE_NOT_INUSE indicates a member is available.
2817          */
2818         ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2819 }
2820
2821 static void clear_queue(struct call_queue *q)
2822 {
2823         q->holdtime = 0;
2824         q->callscompleted = 0;
2825         q->callsabandoned = 0;
2826         q->callscompletedinsl = 0;