Merge "Fix misname 'res_external_mwi' to 'res_mwi_external' in comments."
[asterisk/asterisk.git] / apps / app_queue.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2018, 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="b" argsep="^">
137                                                 <para>Before initiating an outgoing call, <literal>Gosub</literal> to the specified
138                                                 location using the newly created channel.  The <literal>Gosub</literal> will be
139                                                 executed for each destination channel.</para>
140                                                 <argument name="context" required="false" />
141                                                 <argument name="exten" required="false" />
142                                                 <argument name="priority" required="true" hasparams="optional" argsep="^">
143                                                         <argument name="arg1" multiple="true" required="true" />
144                                                         <argument name="argN" />
145                                                 </argument>
146                                         </option>
147                                         <option name="B" argsep="^">
148                                                 <para>Before initiating the outgoing call(s), <literal>Gosub</literal> to the
149                                                 specified location using the current channel.</para>
150                                                 <argument name="context" required="false" />
151                                                 <argument name="exten" required="false" />
152                                                 <argument name="priority" required="true" hasparams="optional" argsep="^">
153                                                         <argument name="arg1" multiple="true" required="true" />
154                                                         <argument name="argN" />
155                                                 </argument>
156                                         </option>
157                                         <option name="C">
158                                                 <para>Mark all calls as "answered elsewhere" when cancelled.</para>
159                                         </option>
160                                         <option name="c">
161                                                 <para>Continue in the dialplan if the callee hangs up.</para>
162                                         </option>
163                                         <option name="d">
164                                                 <para>data-quality (modem) call (minimum delay).</para>
165                                         </option>
166                                         <option name="F" argsep="^">
167                                                 <argument name="context" required="false" />
168                                                 <argument name="exten" required="false" />
169                                                 <argument name="priority" required="true" />
170                                                 <para>When the caller hangs up, transfer the <emphasis>called member</emphasis>
171                                                 to the specified destination and <emphasis>start</emphasis> execution at that location.</para>
172                                                 <para>NOTE: Any channel variables you want the called channel to inherit from the caller channel must be
173                                                 prefixed with one or two underbars ('_').</para>
174                                         </option>
175                                         <option name="F">
176                                                 <para>When the caller hangs up, transfer the <emphasis>called member</emphasis> to the next priority of
177                                                 the current extension and <emphasis>start</emphasis> execution at that location.</para>
178                                                 <para>NOTE: Any channel variables you want the called channel to inherit from the caller channel must be
179                                                 prefixed with one or two underbars ('_').</para>
180                                                 <para>NOTE: Using this option from a Macro() or GoSub() might not make sense as there would be no return points.</para>
181                                         </option>
182                                         <option name="h">
183                                                 <para>Allow <emphasis>callee</emphasis> to hang up by pressing <literal>*</literal>.</para>
184                                         </option>
185                                         <option name="H">
186                                                 <para>Allow <emphasis>caller</emphasis> to hang up by pressing <literal>*</literal>.</para>
187                                         </option>
188                                         <option name="n">
189                                                 <para>No retries on the timeout; will exit this application and
190                                                 go to the next step.</para>
191                                         </option>
192                                         <option name="i">
193                                                 <para>Ignore call forward requests from queue members and do nothing
194                                                 when they are requested.</para>
195                                         </option>
196                                         <option name="I">
197                                                 <para>Asterisk will ignore any connected line update requests or any redirecting party
198                                                 update requests it may receive on this dial attempt.</para>
199                                         </option>
200                                         <option name="r">
201                                                 <para>Ring instead of playing MOH. Periodic Announcements are still made, if applicable.</para>
202                                         </option>
203                                         <option name="R">
204                                                 <para>Ring instead of playing MOH when a member channel is actually ringing.</para>
205                                         </option>
206                                         <option name="t">
207                                                 <para>Allow the <emphasis>called</emphasis> user to transfer the calling user.</para>
208                                         </option>
209                                         <option name="T">
210                                                 <para>Allow the <emphasis>calling</emphasis> user to transfer the call.</para>
211                                         </option>
212                                         <option name="w">
213                                                 <para>Allow the <emphasis>called</emphasis> user to write the conversation to
214                                                 disk via Monitor.</para>
215                                         </option>
216                                         <option name="W">
217                                                 <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
218                                                 disk via Monitor.</para>
219                                         </option>
220                                         <option name="k">
221                                                 <para>Allow the <emphasis>called</emphasis> party to enable parking of the call by sending
222                                                 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
223                                         </option>
224                                         <option name="K">
225                                                 <para>Allow the <emphasis>calling</emphasis> party to enable parking of the call by sending
226                                                 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
227                                         </option>
228                                         <option name="x">
229                                                 <para>Allow the <emphasis>called</emphasis> user to write the conversation
230                                                 to disk via MixMonitor.</para>
231                                         </option>
232                                         <option name="X">
233                                                 <para>Allow the <emphasis>calling</emphasis> user to write the conversation to
234                                                 disk via MixMonitor.</para>
235                                         </option>
236                                 </optionlist>
237                         </parameter>
238                         <parameter name="URL">
239                                 <para><replaceable>URL</replaceable> will be sent to the called party if the channel supports it.</para>
240                         </parameter>
241                         <parameter name="announceoverride" />
242                         <parameter name="timeout">
243                                 <para>Will cause the queue to fail out after a specified number of
244                                 seconds, checked between each <filename>queues.conf</filename> <replaceable>timeout</replaceable> and
245                                 <replaceable>retry</replaceable> cycle.</para>
246                         </parameter>
247                         <parameter name="AGI">
248                                 <para>Will setup an AGI script to be executed on the calling party's channel once they are
249                                 connected to a queue member.</para>
250                         </parameter>
251                         <parameter name="macro">
252                                 <para>Will run a macro on the called party's channel (the queue member) once the parties are connected.</para>
253                                 <para>NOTE: Macros are deprecated, GoSub should be used instead.</para>
254                         </parameter>
255                         <parameter name="gosub">
256                                 <para>Will run a gosub on the called party's channel (the queue member)
257                                 once the parties are connected.  The subroutine execution starts in the
258                                 named context at the s exten and priority 1.</para>
259                         </parameter>
260                         <parameter name="rule">
261                                 <para>Will cause the queue's defaultrule to be overridden by the rule specified.</para>
262                         </parameter>
263                         <parameter name="position">
264                                 <para>Attempt to enter the caller into the queue at the numerical position specified. <literal>1</literal>
265                                 would attempt to enter the caller at the head of the queue, and <literal>3</literal> would attempt to place
266                                 the caller third in the queue.</para>
267                         </parameter>
268                 </syntax>
269                 <description>
270                         <para>In addition to transferring the call, a call may be parked and then picked
271                         up by another user.</para>
272                         <para>This application will return to the dialplan if the queue does not exist, or
273                         any of the join options cause the caller to not enter the queue.</para>
274                         <para>This application does not automatically answer and should be preceeded
275                         by an application such as Answer(), Progress(), or Ringing().</para>
276                         <para>This application sets the following channel variables upon completion:</para>
277                         <variablelist>
278                                 <variable name="QUEUESTATUS">
279                                         <para>The status of the call as a text string.</para>
280                                         <value name="TIMEOUT" />
281                                         <value name="FULL" />
282                                         <value name="JOINEMPTY" />
283                                         <value name="LEAVEEMPTY" />
284                                         <value name="JOINUNAVAIL" />
285                                         <value name="LEAVEUNAVAIL" />
286                                         <value name="CONTINUE" />
287                                 </variable>
288                                 <variable name="ABANDONED">
289                                         <para>If the call was not answered by an agent this variable will be TRUE.</para>
290                                         <value name="TRUE" />
291                                 </variable>
292                         </variablelist>
293                 </description>
294                 <see-also>
295                         <ref type="application">Queue</ref>
296                         <ref type="application">QueueLog</ref>
297                         <ref type="application">AddQueueMember</ref>
298                         <ref type="application">RemoveQueueMember</ref>
299                         <ref type="application">PauseQueueMember</ref>
300                         <ref type="application">UnpauseQueueMember</ref>
301                         <ref type="function">QUEUE_VARIABLES</ref>
302                         <ref type="function">QUEUE_MEMBER</ref>
303                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
304                         <ref type="function">QUEUE_EXISTS</ref>
305                         <ref type="function">QUEUE_GET_CHANNEL</ref>
306                         <ref type="function">QUEUE_WAITING_COUNT</ref>
307                         <ref type="function">QUEUE_MEMBER_LIST</ref>
308                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
309                 </see-also>
310         </application>
311         <application name="AddQueueMember" language="en_US">
312                 <synopsis>
313                         Dynamically adds queue members.
314                 </synopsis>
315                 <syntax>
316                         <parameter name="queuename" required="true" />
317                         <parameter name="interface" />
318                         <parameter name="penalty" />
319                         <parameter name="options" />
320                         <parameter name="membername" />
321                         <parameter name="stateinterface" />
322                         <parameter name="wrapuptime" />
323                 </syntax>
324                 <description>
325                         <para>Dynamically adds interface to an existing queue. If the interface is
326                         already in the queue it will return an error.</para>
327                         <para>This application sets the following channel variable upon completion:</para>
328                         <variablelist>
329                                 <variable name="AQMSTATUS">
330                                         <para>The status of the attempt to add a queue member as a text string.</para>
331                                         <value name="ADDED" />
332                                         <value name="MEMBERALREADY" />
333                                         <value name="NOSUCHQUEUE" />
334                                 </variable>
335                         </variablelist>
336                 </description>
337                 <see-also>
338                         <ref type="application">Queue</ref>
339                         <ref type="application">QueueLog</ref>
340                         <ref type="application">AddQueueMember</ref>
341                         <ref type="application">RemoveQueueMember</ref>
342                         <ref type="application">PauseQueueMember</ref>
343                         <ref type="application">UnpauseQueueMember</ref>
344                         <ref type="function">QUEUE_VARIABLES</ref>
345                         <ref type="function">QUEUE_MEMBER</ref>
346                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
347                         <ref type="function">QUEUE_EXISTS</ref>
348                         <ref type="function">QUEUE_GET_CHANNEL</ref>
349                         <ref type="function">QUEUE_WAITING_COUNT</ref>
350                         <ref type="function">QUEUE_MEMBER_LIST</ref>
351                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
352                 </see-also>
353         </application>
354         <application name="RemoveQueueMember" language="en_US">
355                 <synopsis>
356                         Dynamically removes queue members.
357                 </synopsis>
358                 <syntax>
359                         <parameter name="queuename" required="true" />
360                         <parameter name="interface" />
361                 </syntax>
362                 <description>
363                         <para>If the interface is <emphasis>NOT</emphasis> in the queue it will return an error.</para>
364                         <para>This application sets the following channel variable upon completion:</para>
365                         <variablelist>
366                                 <variable name="RQMSTATUS">
367                                         <value name="REMOVED" />
368                                         <value name="NOTINQUEUE" />
369                                         <value name="NOSUCHQUEUE" />
370                                         <value name="NOTDYNAMIC" />
371                                 </variable>
372                         </variablelist>
373                         <para>Example: RemoveQueueMember(techsupport,SIP/3000)</para>
374                 </description>
375                 <see-also>
376                         <ref type="application">Queue</ref>
377                         <ref type="application">QueueLog</ref>
378                         <ref type="application">AddQueueMember</ref>
379                         <ref type="application">RemoveQueueMember</ref>
380                         <ref type="application">PauseQueueMember</ref>
381                         <ref type="application">UnpauseQueueMember</ref>
382                         <ref type="function">QUEUE_VARIABLES</ref>
383                         <ref type="function">QUEUE_MEMBER</ref>
384                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
385                         <ref type="function">QUEUE_EXISTS</ref>
386                         <ref type="function">QUEUE_GET_CHANNEL</ref>
387                         <ref type="function">QUEUE_WAITING_COUNT</ref>
388                         <ref type="function">QUEUE_MEMBER_LIST</ref>
389                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
390                 </see-also>
391         </application>
392         <application name="PauseQueueMember" language="en_US">
393                 <synopsis>
394                         Pauses a queue member.
395                 </synopsis>
396                 <syntax>
397                         <parameter name="queuename" />
398                         <parameter name="interface" required="true" />
399                         <parameter name="options" />
400                         <parameter name="reason">
401                                 <para>Is used to add extra information to the appropriate queue_log entries and manager events.</para>
402                         </parameter>
403                 </syntax>
404                 <description>
405                         <para>Pauses (blocks calls for) a queue member. The given interface will be paused in the given queue.
406                         This prevents any calls from being sent from the queue to the interface until it is
407                         unpaused with UnpauseQueueMember or the manager interface.  If no queuename is given,
408                         the interface is paused in every queue it is a member of. The application will fail if the
409                         interface is not found.</para>
410                         <para>This application sets the following channel variable upon completion:</para>
411                         <variablelist>
412                                 <variable name="PQMSTATUS">
413                                         <para>The status of the attempt to pause a queue member as a text string.</para>
414                                         <value name="PAUSED" />
415                                         <value name="NOTFOUND" />
416                                 </variable>
417                         </variablelist>
418                         <para>Example: PauseQueueMember(,SIP/3000)</para>
419                 </description>
420                 <see-also>
421                         <ref type="application">Queue</ref>
422                         <ref type="application">QueueLog</ref>
423                         <ref type="application">AddQueueMember</ref>
424                         <ref type="application">RemoveQueueMember</ref>
425                         <ref type="application">PauseQueueMember</ref>
426                         <ref type="application">UnpauseQueueMember</ref>
427                         <ref type="function">QUEUE_VARIABLES</ref>
428                         <ref type="function">QUEUE_MEMBER</ref>
429                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
430                         <ref type="function">QUEUE_EXISTS</ref>
431                         <ref type="function">QUEUE_GET_CHANNEL</ref>
432                         <ref type="function">QUEUE_WAITING_COUNT</ref>
433                         <ref type="function">QUEUE_MEMBER_LIST</ref>
434                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
435                 </see-also>
436         </application>
437         <application name="UnpauseQueueMember" language="en_US">
438                 <synopsis>
439                         Unpauses a queue member.
440                 </synopsis>
441                 <syntax>
442                         <parameter name="queuename" />
443                         <parameter name="interface" required="true" />
444                         <parameter name="options" />
445                         <parameter name="reason">
446                                 <para>Is used to add extra information to the appropriate queue_log entries and manager events.</para>
447                         </parameter>
448                 </syntax>
449                 <description>
450                         <para>Unpauses (resumes calls to) a queue member. This is the counterpart to <literal>PauseQueueMember()</literal>
451                         and operates exactly the same way, except it unpauses instead of pausing the given interface.</para>
452                         <para>This application sets the following channel variable upon completion:</para>
453                         <variablelist>
454                                 <variable name="UPQMSTATUS">
455                                         <para>The status of the attempt to unpause a queue member as a text string.</para>
456                                         <value name="UNPAUSED" />
457                                         <value name="NOTFOUND" />
458                                 </variable>
459                         </variablelist>
460                         <para>Example: UnpauseQueueMember(,SIP/3000)</para>
461                 </description>
462                 <see-also>
463                         <ref type="application">Queue</ref>
464                         <ref type="application">QueueLog</ref>
465                         <ref type="application">AddQueueMember</ref>
466                         <ref type="application">RemoveQueueMember</ref>
467                         <ref type="application">PauseQueueMember</ref>
468                         <ref type="application">UnpauseQueueMember</ref>
469                         <ref type="function">QUEUE_VARIABLES</ref>
470                         <ref type="function">QUEUE_MEMBER</ref>
471                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
472                         <ref type="function">QUEUE_EXISTS</ref>
473                         <ref type="function">QUEUE_GET_CHANNEL</ref>
474                         <ref type="function">QUEUE_WAITING_COUNT</ref>
475                         <ref type="function">QUEUE_MEMBER_LIST</ref>
476                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
477                 </see-also>
478         </application>
479         <application name="QueueLog" language="en_US">
480                 <synopsis>
481                         Writes to the queue_log file.
482                 </synopsis>
483                 <syntax>
484                         <parameter name="queuename" required="true" />
485                         <parameter name="uniqueid" required="true" />
486                         <parameter name="agent" required="true" />
487                         <parameter name="event" required="true" />
488                         <parameter name="additionalinfo" />
489                 </syntax>
490                 <description>
491                         <para>Allows you to write your own events into the queue log.</para>
492                         <para>Example: QueueLog(101,${UNIQUEID},${AGENT},WENTONBREAK,600)</para>
493                 </description>
494                 <see-also>
495                         <ref type="application">Queue</ref>
496                         <ref type="application">QueueLog</ref>
497                         <ref type="application">AddQueueMember</ref>
498                         <ref type="application">RemoveQueueMember</ref>
499                         <ref type="application">PauseQueueMember</ref>
500                         <ref type="application">UnpauseQueueMember</ref>
501                         <ref type="function">QUEUE_VARIABLES</ref>
502                         <ref type="function">QUEUE_MEMBER</ref>
503                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
504                         <ref type="function">QUEUE_EXISTS</ref>
505                         <ref type="function">QUEUE_GET_CHANNEL</ref>
506                         <ref type="function">QUEUE_WAITING_COUNT</ref>
507                         <ref type="function">QUEUE_MEMBER_LIST</ref>
508                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
509                 </see-also>
510         </application>
511         <application name="QueueUpdate" language="en_US">
512                 <synopsis>
513                         Writes to the queue_log file for OutBound calls and updates Realtime Data.
514                         Is used at h extension to be able to have all the parameters.
515                 </synopsis>
516                 <syntax>
517                         <parameter name="queuename" required="true" />
518                         <parameter name="uniqueid" required="true" />
519                         <parameter name="agent" required="true" />
520                         <parameter name="status" required="true" />
521                         <parameter name="talktime" required="true" />
522                         <parameter name="params" required="false" />
523                 </syntax>
524                 <description>
525                         <para>Allows you to write Outbound events into the queue log.</para>
526                         <para>Example: exten => h,1,QueueUpdate(${QUEUE}, ${UNIQUEID}, ${AGENT}, ${DIALSTATUS}, ${ANSWEREDTIME}, ${DIALEDTIME} | ${DIALEDNUMBER})</para>
527                 </description>
528         </application>
529         <function name="QUEUE_VARIABLES" language="en_US">
530                 <synopsis>
531                         Return Queue information in variables.
532                 </synopsis>
533                 <syntax>
534                         <parameter name="queuename" required="true">
535                                 <enumlist>
536                                         <enum name="QUEUEMAX">
537                                                 <para>Maxmimum number of calls allowed.</para>
538                                         </enum>
539                                         <enum name="QUEUESTRATEGY">
540                                                 <para>The strategy of the queue.</para>
541                                         </enum>
542                                         <enum name="QUEUECALLS">
543                                                 <para>Number of calls currently in the queue.</para>
544                                         </enum>
545                                         <enum name="QUEUEHOLDTIME">
546                                                 <para>Current average hold time.</para>
547                                         </enum>
548                                         <enum name="QUEUECOMPLETED">
549                                                 <para>Number of completed calls for the queue.</para>
550                                         </enum>
551                                         <enum name="QUEUEABANDONED">
552                                                 <para>Number of abandoned calls.</para>
553                                         </enum>
554                                         <enum name="QUEUESRVLEVEL">
555                                                 <para>Queue service level.</para>
556                                         </enum>
557                                         <enum name="QUEUESRVLEVELPERF">
558                                                 <para>Current service level performance.</para>
559                                         </enum>
560                                 </enumlist>
561                         </parameter>
562                 </syntax>
563                 <description>
564                         <para>Makes the following queue variables available.</para>
565                         <para>Returns <literal>0</literal> if queue is found and setqueuevar is defined, <literal>-1</literal> otherwise.</para>
566                 </description>
567                 <see-also>
568                         <ref type="application">Queue</ref>
569                         <ref type="application">QueueLog</ref>
570                         <ref type="application">AddQueueMember</ref>
571                         <ref type="application">RemoveQueueMember</ref>
572                         <ref type="application">PauseQueueMember</ref>
573                         <ref type="application">UnpauseQueueMember</ref>
574                         <ref type="function">QUEUE_VARIABLES</ref>
575                         <ref type="function">QUEUE_MEMBER</ref>
576                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
577                         <ref type="function">QUEUE_EXISTS</ref>
578                         <ref type="function">QUEUE_GET_CHANNEL</ref>
579                         <ref type="function">QUEUE_WAITING_COUNT</ref>
580                         <ref type="function">QUEUE_MEMBER_LIST</ref>
581                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
582                 </see-also>
583         </function>
584         <function name="QUEUE_MEMBER" language="en_US">
585                 <synopsis>
586                         Provides a count of queue members based on the provided criteria, or updates a
587                         queue member's settings.
588                 </synopsis>
589                 <syntax>
590                         <parameter name="queuename" required="false" />
591                         <parameter name="option" required="true">
592                                 <enumlist>
593                                         <enum name="logged">
594                                                 <para>Returns the number of logged-in members for the specified queue.</para>
595                                         </enum>
596                                         <enum name="free">
597                                                 <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>
598                                         </enum>
599                                         <enum name="ready">
600                                                 <para>Returns the number of logged-in members for the specified queue that are immediately available to answer a call.</para>
601                                         </enum>
602                                         <enum name="count">
603                                                 <para>Returns the total number of members for the specified queue.</para>
604                                         </enum>
605                                         <enum name="penalty">
606                                                 <para>Gets or sets queue member penalty.  If
607                                                 <replaceable>queuename</replaceable> is not specified
608                                                 when setting the penalty then the penalty is set in all queues
609                                                 the interface is a member.</para>
610                                         </enum>
611                                         <enum name="paused">
612                                                 <para>Gets or sets queue member paused status.  If
613                                                 <replaceable>queuename</replaceable> is not specified
614                                                 when setting the paused status then the paused status is set
615                                                 in all queues the interface is a member.</para>
616                                         </enum>
617                                         <enum name="ringinuse">
618                                                 <para>Gets or sets queue member ringinuse.  If
619                                                 <replaceable>queuename</replaceable> is not specified
620                                                 when setting ringinuse then ringinuse is set
621                                                 in all queues the interface is a member.</para>
622                                         </enum>
623                                 </enumlist>
624                         </parameter>
625                         <parameter name="interface" required="false" />
626                 </syntax>
627                 <description>
628                         <para>Allows access to queue counts [R] and member information [R/W].</para>
629                         <para><replaceable>queuename</replaceable> is required for all read operations.</para>
630                         <para><replaceable>interface</replaceable> is required for all member operations.</para>
631                 </description>
632                 <see-also>
633                         <ref type="application">Queue</ref>
634                         <ref type="application">QueueLog</ref>
635                         <ref type="application">AddQueueMember</ref>
636                         <ref type="application">RemoveQueueMember</ref>
637                         <ref type="application">PauseQueueMember</ref>
638                         <ref type="application">UnpauseQueueMember</ref>
639                         <ref type="function">QUEUE_VARIABLES</ref>
640                         <ref type="function">QUEUE_MEMBER</ref>
641                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
642                         <ref type="function">QUEUE_EXISTS</ref>
643                         <ref type="function">QUEUE_GET_CHANNEL</ref>
644                         <ref type="function">QUEUE_WAITING_COUNT</ref>
645                         <ref type="function">QUEUE_MEMBER_LIST</ref>
646                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
647                 </see-also>
648         </function>
649         <function name="QUEUE_MEMBER_COUNT" language="en_US">
650                 <synopsis>
651                         Count number of members answering a queue.
652                 </synopsis>
653                 <syntax>
654                         <parameter name="queuename" required="true" />
655                 </syntax>
656                 <description>
657                         <para>Returns the number of members currently associated with the specified <replaceable>queuename</replaceable>.</para>
658                         <warning><para>This function has been deprecated in favor of the <literal>QUEUE_MEMBER()</literal> function</para></warning>
659                 </description>
660                 <see-also>
661                         <ref type="application">Queue</ref>
662                         <ref type="application">QueueLog</ref>
663                         <ref type="application">AddQueueMember</ref>
664                         <ref type="application">RemoveQueueMember</ref>
665                         <ref type="application">PauseQueueMember</ref>
666                         <ref type="application">UnpauseQueueMember</ref>
667                         <ref type="function">QUEUE_VARIABLES</ref>
668                         <ref type="function">QUEUE_MEMBER</ref>
669                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
670                         <ref type="function">QUEUE_EXISTS</ref>
671                         <ref type="function">QUEUE_GET_CHANNEL</ref>
672                         <ref type="function">QUEUE_WAITING_COUNT</ref>
673                         <ref type="function">QUEUE_MEMBER_LIST</ref>
674                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
675                 </see-also>
676         </function>
677         <function name="QUEUE_EXISTS" language="en_US">
678                 <synopsis>
679                         Check if a named queue exists on this server
680                 </synopsis>
681                 <syntax>
682                         <parameter name="queuename" />
683                 </syntax>
684                 <description>
685                         <para>Returns 1 if the specified queue exists, 0 if it does not</para>
686                 </description>
687                 <see-also>
688                         <ref type="application">Queue</ref>
689                         <ref type="application">QueueLog</ref>
690                         <ref type="application">AddQueueMember</ref>
691                         <ref type="application">RemoveQueueMember</ref>
692                         <ref type="application">PauseQueueMember</ref>
693                         <ref type="application">UnpauseQueueMember</ref>
694                         <ref type="function">QUEUE_VARIABLES</ref>
695                         <ref type="function">QUEUE_MEMBER</ref>
696                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
697                         <ref type="function">QUEUE_EXISTS</ref>
698                         <ref type="function">QUEUE_GET_CHANNEL</ref>
699                         <ref type="function">QUEUE_WAITING_COUNT</ref>
700                         <ref type="function">QUEUE_MEMBER_LIST</ref>
701                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
702                 </see-also>
703         </function>
704         <function name="QUEUE_GET_CHANNEL" language="en_US">
705                 <synopsis>
706                         Return caller at the specified position in a queue.
707                 </synopsis>
708                 <syntax>
709                         <parameter name="queuename" required="true" />
710                         <parameter name="position" />
711                 </syntax>
712                 <description>
713                         <para>Returns the caller channel at <replaceable>position</replaceable> in the specified <replaceable>queuename</replaceable>.</para>
714                         <para>If <replaceable>position</replaceable> is unspecified the first channel is returned.</para>
715                 </description>
716                 <see-also>
717                         <ref type="application">Queue</ref>
718                         <ref type="application">QueueLog</ref>
719                         <ref type="application">AddQueueMember</ref>
720                         <ref type="application">RemoveQueueMember</ref>
721                         <ref type="application">PauseQueueMember</ref>
722                         <ref type="application">UnpauseQueueMember</ref>
723                         <ref type="function">QUEUE_VARIABLES</ref>
724                         <ref type="function">QUEUE_MEMBER</ref>
725                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
726                         <ref type="function">QUEUE_EXISTS</ref>
727                         <ref type="function">QUEUE_WAITING_COUNT</ref>
728                         <ref type="function">QUEUE_MEMBER_LIST</ref>
729                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
730                 </see-also>
731         </function>
732         <function name="QUEUE_WAITING_COUNT" language="en_US">
733                 <synopsis>
734                         Count number of calls currently waiting in a queue.
735                 </synopsis>
736                 <syntax>
737                         <parameter name="queuename" />
738                 </syntax>
739                 <description>
740                         <para>Returns the number of callers currently waiting in the specified <replaceable>queuename</replaceable>.</para>
741                 </description>
742                 <see-also>
743                         <ref type="application">Queue</ref>
744                         <ref type="application">QueueLog</ref>
745                         <ref type="application">AddQueueMember</ref>
746                         <ref type="application">RemoveQueueMember</ref>
747                         <ref type="application">PauseQueueMember</ref>
748                         <ref type="application">UnpauseQueueMember</ref>
749                         <ref type="function">QUEUE_VARIABLES</ref>
750                         <ref type="function">QUEUE_MEMBER</ref>
751                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
752                         <ref type="function">QUEUE_EXISTS</ref>
753                         <ref type="function">QUEUE_GET_CHANNEL</ref>
754                         <ref type="function">QUEUE_WAITING_COUNT</ref>
755                         <ref type="function">QUEUE_MEMBER_LIST</ref>
756                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
757                 </see-also>
758         </function>
759         <function name="QUEUE_MEMBER_LIST" language="en_US">
760                 <synopsis>
761                         Returns a list of interfaces on a queue.
762                 </synopsis>
763                 <syntax>
764                         <parameter name="queuename" required="true" />
765                 </syntax>
766                 <description>
767                         <para>Returns a comma-separated list of members associated with the specified <replaceable>queuename</replaceable>.</para>
768                 </description>
769                 <see-also>
770                         <ref type="application">Queue</ref>
771                         <ref type="application">QueueLog</ref>
772                         <ref type="application">AddQueueMember</ref>
773                         <ref type="application">RemoveQueueMember</ref>
774                         <ref type="application">PauseQueueMember</ref>
775                         <ref type="application">UnpauseQueueMember</ref>
776                         <ref type="function">QUEUE_VARIABLES</ref>
777                         <ref type="function">QUEUE_MEMBER</ref>
778                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
779                         <ref type="function">QUEUE_EXISTS</ref>
780                         <ref type="function">QUEUE_GET_CHANNEL</ref>
781                         <ref type="function">QUEUE_WAITING_COUNT</ref>
782                         <ref type="function">QUEUE_MEMBER_LIST</ref>
783                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
784                 </see-also>
785         </function>
786         <function name="QUEUE_MEMBER_PENALTY" language="en_US">
787                 <synopsis>
788                         Gets or sets queue members penalty.
789                 </synopsis>
790                 <syntax>
791                         <parameter name="queuename" required="true" />
792                         <parameter name="interface" required="true" />
793                 </syntax>
794                 <description>
795                         <para>Gets or sets queue members penalty.</para>
796                         <warning><para>This function has been deprecated in favor of the <literal>QUEUE_MEMBER()</literal> function</para></warning>
797                 </description>
798                 <see-also>
799                         <ref type="application">Queue</ref>
800                         <ref type="application">QueueLog</ref>
801                         <ref type="application">AddQueueMember</ref>
802                         <ref type="application">RemoveQueueMember</ref>
803                         <ref type="application">PauseQueueMember</ref>
804                         <ref type="application">UnpauseQueueMember</ref>
805                         <ref type="function">QUEUE_VARIABLES</ref>
806                         <ref type="function">QUEUE_MEMBER</ref>
807                         <ref type="function">QUEUE_MEMBER_COUNT</ref>
808                         <ref type="function">QUEUE_EXISTS</ref>
809                         <ref type="function">QUEUE_GET_CHANNEL</ref>
810                         <ref type="function">QUEUE_WAITING_COUNT</ref>
811                         <ref type="function">QUEUE_MEMBER_LIST</ref>
812                         <ref type="function">QUEUE_MEMBER_PENALTY</ref>
813                 </see-also>
814         </function>
815         <manager name="QueueStatus" language="en_US">
816                 <synopsis>
817                         Show queue status.
818                 </synopsis>
819                 <syntax>
820                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
821                         <parameter name="Queue">
822                                 <para>Limit the response to the status of the specified queue.</para>
823                         </parameter>
824                         <parameter name="Member">
825                                 <para>Limit the response to the status of the specified member.</para>
826                         </parameter>
827                 </syntax>
828                 <description>
829                         <para>Check the status of one or more queues.</para>
830                 </description>
831         </manager>
832         <manager name="QueueSummary" language="en_US">
833                 <synopsis>
834                         Show queue summary.
835                 </synopsis>
836                 <syntax>
837                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
838                         <parameter name="Queue">
839                                 <para>Queue for which the summary is requested.</para>
840                         </parameter>
841                 </syntax>
842                 <description>
843                         <para>Request the manager to send a QueueSummary event.</para>
844                 </description>
845         </manager>
846         <manager name="QueueAdd" language="en_US">
847                 <synopsis>
848                         Add interface to queue.
849                 </synopsis>
850                 <syntax>
851                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
852                         <parameter name="Queue" required="true">
853                                 <para>Queue's name.</para>
854                         </parameter>
855                         <parameter name="Interface" required="true">
856                                 <para>The name of the interface (tech/name) to add to the queue.</para>
857                         </parameter>
858                         <parameter name="Penalty">
859                                 <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>
860                         </parameter>
861                         <parameter name="Paused">
862                                 <para>To pause or not the member initially (true/false or 1/0).</para>
863                         </parameter>
864                         <parameter name="MemberName">
865                                 <para>Text alias for the interface.</para>
866                         </parameter>
867                         <parameter name="StateInterface" />
868                 </syntax>
869                 <description>
870                 </description>
871         </manager>
872         <manager name="QueueRemove" language="en_US">
873                 <synopsis>
874                         Remove interface from queue.
875                 </synopsis>
876                 <syntax>
877                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
878                         <parameter name="Queue" required="true">
879                                 <para>The name of the queue to take action on.</para>
880                         </parameter>
881                         <parameter name="Interface" required="true">
882                                 <para>The interface (tech/name) to remove from queue.</para>
883                         </parameter>
884                 </syntax>
885                 <description>
886                 </description>
887         </manager>
888         <manager name="QueuePause" language="en_US">
889                 <synopsis>
890                         Makes a queue member temporarily unavailable.
891                 </synopsis>
892                 <syntax>
893                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
894                         <parameter name="Interface" required="true">
895                                 <para>The name of the interface (tech/name) to pause or unpause.</para>
896                         </parameter>
897                         <parameter name="Paused" required="true">
898                                 <para>Pause or unpause the interface. Set to 'true' to pause the member or 'false' to unpause.</para>
899                         </parameter>
900                         <parameter name="Queue">
901                                 <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>
902                         </parameter>
903                         <parameter name="Reason">
904                                 <para>Text description, returned in the event QueueMemberPaused.</para>
905                         </parameter>
906                 </syntax>
907                 <description>
908                         <para>Pause or unpause a member in a queue.</para>
909                 </description>
910         </manager>
911         <manager name="QueueLog" language="en_US">
912                 <synopsis>
913                         Adds custom entry in queue_log.
914                 </synopsis>
915                 <syntax>
916                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
917                         <parameter name="Queue" required="true" />
918                         <parameter name="Event" required="true" />
919                         <parameter name="Uniqueid" />
920                         <parameter name="Interface" />
921                         <parameter name="Message" />
922                 </syntax>
923                 <description>
924                 </description>
925         </manager>
926         <manager name="QueuePenalty" language="en_US">
927                 <synopsis>
928                         Set the penalty for a queue member.
929                 </synopsis>
930                 <syntax>
931                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
932                         <parameter name="Interface" required="true">
933                                 <para>The interface (tech/name) of the member whose penalty to change.</para>
934                         </parameter>
935                         <parameter name="Penalty" required="true">
936                                 <para>The new penalty (number) for the member. Must be nonnegative.</para>
937                         </parameter>
938                         <parameter name="Queue">
939                                 <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>
940                         </parameter>
941                 </syntax>
942                 <description>
943                         <para>Change the penalty of a queue member</para>
944                 </description>
945         </manager>
946         <manager name="QueueMemberRingInUse" language="en_US">
947                 <synopsis>
948                         Set the ringinuse value for a queue member.
949                 </synopsis>
950                 <syntax>
951                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
952                         <parameter name="Interface" required="true" />
953                         <parameter name="RingInUse" required="true" />
954                         <parameter name="Queue" />
955                 </syntax>
956                 <description>
957                 </description>
958         </manager>
959         <manager name="QueueRule" language="en_US">
960                 <synopsis>
961                         Queue Rules.
962                 </synopsis>
963                 <syntax>
964                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
965                         <parameter name="Rule">
966                                 <para>The name of the rule in queuerules.conf whose contents to list.</para>
967                         </parameter>
968                 </syntax>
969                 <description>
970                         <para>List queue rules defined in queuerules.conf</para>
971                 </description>
972         </manager>
973         <manager name="QueueReload" language="en_US">
974                 <synopsis>
975                         Reload a queue, queues, or any sub-section of a queue or queues.
976                 </synopsis>
977                 <syntax>
978                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
979                         <parameter name="Queue">
980                                 <para>The name of the queue to take action on. If no queue name is specified, then all queues are affected.</para>
981                         </parameter>
982                         <parameter name="Members">
983                                 <para>Whether to reload the queue's members.</para>
984                                 <enumlist>
985                                         <enum name="yes" />
986                                         <enum name="no" />
987                                 </enumlist>
988                         </parameter>
989                         <parameter name="Rules">
990                                 <para>Whether to reload queuerules.conf</para>
991                                 <enumlist>
992                                         <enum name="yes" />
993                                         <enum name="no" />
994                                 </enumlist>
995                         </parameter>
996                         <parameter name="Parameters">
997                                 <para>Whether to reload the other queue options.</para>
998                                 <enumlist>
999                                         <enum name="yes" />
1000                                         <enum name="no" />
1001                                 </enumlist>
1002                         </parameter>
1003                 </syntax>
1004                 <description>
1005                 </description>
1006         </manager>
1007         <manager name="QueueReset" language="en_US">
1008                 <synopsis>
1009                         Reset queue statistics.
1010                 </synopsis>
1011                 <syntax>
1012                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1013                         <parameter name="Queue">
1014                                 <para>The name of the queue on which to reset statistics.</para>
1015                         </parameter>
1016                 </syntax>
1017                 <description>
1018                         <para>Reset the statistics for a queue.</para>
1019                 </description>
1020         </manager>
1021         <manager name="QueueChangePriorityCaller" language="en_US">
1022                 <synopsis>
1023                         Change priority of a caller on queue.
1024                 </synopsis>
1025                 <syntax>
1026                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1027                         <parameter name="Queue" required="true">
1028                                 <para>The name of the queue to take action on.</para>
1029                         </parameter>
1030                         <parameter name="Caller" required="true">
1031                                 <para>The caller (channel) to change priority on queue.</para>
1032                         </parameter>
1033
1034                         <parameter name="Priority" required="true">
1035                                 <para>Priority value for change for caller on queue.</para>
1036                         </parameter>
1037                 </syntax>
1038                 <description>
1039                 </description>
1040         </manager>
1041
1042         <managerEvent language="en_US" name="QueueMemberStatus">
1043                 <managerEventInstance class="EVENT_FLAG_AGENT">
1044                         <synopsis>Raised when a Queue member's status has changed.</synopsis>
1045                         <syntax>
1046                                 <parameter name="Queue">
1047                                         <para>The name of the queue.</para>
1048                                 </parameter>
1049                                 <parameter name="MemberName">
1050                                         <para>The name of the queue member.</para>
1051                                 </parameter>
1052                                 <parameter name="Interface">
1053                                         <para>The queue member's channel technology or location.</para>
1054                                 </parameter>
1055                                 <parameter name="StateInterface">
1056                                         <para>Channel technology or location from which to read device state changes.</para>
1057                                 </parameter>
1058                                 <parameter name="Membership">
1059                                         <enumlist>
1060                                                 <enum name="dynamic"/>
1061                                                 <enum name="realtime"/>
1062                                                 <enum name="static"/>
1063                                         </enumlist>
1064                                 </parameter>
1065                                 <parameter name="Penalty">
1066                                         <para>The penalty associated with the queue member.</para>
1067                                 </parameter>
1068                                 <parameter name="CallsTaken">
1069                                         <para>The number of calls this queue member has serviced.</para>
1070                                 </parameter>
1071                                 <parameter name="LastCall">
1072                                         <para>The time this member last took a call, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1073                                 </parameter>
1074                                 <parameter name="LastPause">
1075                                         <para>The time when started last paused the queue member.</para>
1076                                 </parameter>
1077                                 <parameter name="InCall">
1078                                         <para>Set to 1 if member is in call. Set to 0 after LastCall time is updated.</para>
1079                                         <enumlist>
1080                                                 <enum name="0"/>
1081                                                 <enum name="1"/>
1082                                         </enumlist>
1083                                 </parameter>
1084                                 <parameter name="Status">
1085                                         <para>The numeric device state status of the queue member.</para>
1086                                         <enumlist>
1087                                                 <enum name="0"><para>AST_DEVICE_UNKNOWN</para></enum>
1088                                                 <enum name="1"><para>AST_DEVICE_NOT_INUSE</para></enum>
1089                                                 <enum name="2"><para>AST_DEVICE_INUSE</para></enum>
1090                                                 <enum name="3"><para>AST_DEVICE_BUSY</para></enum>
1091                                                 <enum name="4"><para>AST_DEVICE_INVALID</para></enum>
1092                                                 <enum name="5"><para>AST_DEVICE_UNAVAILABLE</para></enum>
1093                                                 <enum name="6"><para>AST_DEVICE_RINGING</para></enum>
1094                                                 <enum name="7"><para>AST_DEVICE_RINGINUSE</para></enum>
1095                                                 <enum name="8"><para>AST_DEVICE_ONHOLD</para></enum>
1096                                         </enumlist>
1097                                 </parameter>
1098                                 <parameter name="Paused">
1099                                         <enumlist>
1100                                                 <enum name="0"/>
1101                                                 <enum name="1"/>
1102                                         </enumlist>
1103                                 </parameter>
1104                                 <parameter name="PausedReason">
1105                                         <para>If set when paused, the reason the queue member was paused.</para>
1106                                 </parameter>
1107                                 <parameter name="Ringinuse">
1108                                         <enumlist>
1109                                                 <enum name="0"/>
1110                                                 <enum name="1"/>
1111                                         </enumlist>
1112                                 </parameter>
1113                                 <parameter name="Wrapuptime">
1114                                         <para>The Wrapup Time of the queue member. If this value is set will override the wrapup time of queue.</para>
1115                                 </parameter>
1116                         </syntax>
1117                 </managerEventInstance>
1118         </managerEvent>
1119         <managerEvent language="en_US" name="QueueMemberAdded">
1120                 <managerEventInstance class="EVENT_FLAG_AGENT">
1121                         <synopsis>Raised when a member is added to the queue.</synopsis>
1122                         <syntax>
1123                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1124                         </syntax>
1125                         <see-also>
1126                                 <ref type="managerEvent">QueueMemberRemoved</ref>
1127                                 <ref type="application">AddQueueMember</ref>
1128                         </see-also>
1129                 </managerEventInstance>
1130         </managerEvent>
1131         <managerEvent language="en_US" name="QueueMemberRemoved">
1132                 <managerEventInstance class="EVENT_FLAG_AGENT">
1133                         <synopsis>Raised when a member is removed from the queue.</synopsis>
1134                         <syntax>
1135                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1136                         </syntax>
1137                         <see-also>
1138                                 <ref type="managerEvent">QueueMemberAdded</ref>
1139                                 <ref type="application">RemoveQueueMember</ref>
1140                         </see-also>
1141                 </managerEventInstance>
1142         </managerEvent>
1143         <managerEvent language="en_US" name="QueueMemberPause">
1144                 <managerEventInstance class="EVENT_FLAG_AGENT">
1145                         <synopsis>Raised when a member is paused/unpaused in the queue.</synopsis>
1146                         <syntax>
1147                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1148                                 <parameter name="Reason">
1149                                         <para>The reason a member was paused.</para>
1150                                 </parameter>
1151                         </syntax>
1152                         <see-also>
1153                                 <ref type="application">PauseQueueMember</ref>
1154                                 <ref type="application">UnPauseQueueMember</ref>
1155                         </see-also>
1156                 </managerEventInstance>
1157         </managerEvent>
1158         <managerEvent language="en_US" name="QueueMemberPenalty">
1159                 <managerEventInstance class="EVENT_FLAG_AGENT">
1160                         <synopsis>Raised when a member's penalty is changed.</synopsis>
1161                         <syntax>
1162                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1163                         </syntax>
1164                         <see-also>
1165                                 <ref type="function">QUEUE_MEMBER</ref>
1166                         </see-also>
1167                 </managerEventInstance>
1168         </managerEvent>
1169         <managerEvent language="en_US" name="QueueMemberRinginuse">
1170                 <managerEventInstance class="EVENT_FLAG_AGENT">
1171                         <synopsis>Raised when a member's ringinuse setting is changed.</synopsis>
1172                         <syntax>
1173                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter)" />
1174                         </syntax>
1175                         <see-also>
1176                                 <ref type="function">QUEUE_MEMBER</ref>
1177                         </see-also>
1178                 </managerEventInstance>
1179         </managerEvent>
1180         <managerEvent language="en_US" name="QueueCallerJoin">
1181                 <managerEventInstance class="EVENT_FLAG_AGENT">
1182                         <synopsis>Raised when a caller joins a Queue.</synopsis>
1183                         <syntax>
1184                                 <channel_snapshot/>
1185                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1186                                 <parameter name="Position">
1187                                         <para>This channel's current position in the queue.</para>
1188                                 </parameter>
1189                                 <parameter name="Count">
1190                                         <para>The total number of channels in the queue.</para>
1191                                 </parameter>
1192                         </syntax>
1193                         <see-also>
1194                                 <ref type="managerEvent">QueueCallerLeave</ref>
1195                                 <ref type="application">Queue</ref>
1196                         </see-also>
1197                 </managerEventInstance>
1198         </managerEvent>
1199         <managerEvent language="en_US" name="QueueCallerLeave">
1200                 <managerEventInstance class="EVENT_FLAG_AGENT">
1201                         <synopsis>Raised when a caller leaves a Queue.</synopsis>
1202                         <syntax>
1203                                 <channel_snapshot/>
1204                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1205                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Count'])" />
1206                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Position'])" />
1207                         </syntax>
1208                         <see-also>
1209                                 <ref type="managerEvent">QueueCallerJoin</ref>
1210                         </see-also>
1211                 </managerEventInstance>
1212         </managerEvent>
1213         <managerEvent language="en_US" name="QueueCallerAbandon">
1214                 <managerEventInstance class="EVENT_FLAG_AGENT">
1215                         <synopsis>Raised when a caller abandons the queue.</synopsis>
1216                         <syntax>
1217                                 <channel_snapshot/>
1218                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1219                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerJoin']/managerEventInstance/syntax/parameter[@name='Position'])" />
1220                                 <parameter name="OriginalPosition">
1221                                         <para>The channel's original position in the queue.</para>
1222                                 </parameter>
1223                                 <parameter name="HoldTime">
1224                                         <para>The time the channel was in the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1225                                 </parameter>
1226                         </syntax>
1227                 </managerEventInstance>
1228         </managerEvent>
1229         <managerEvent language="en_US" name="AgentCalled">
1230                 <managerEventInstance class="EVENT_FLAG_AGENT">
1231                         <synopsis>Raised when an queue member is notified of a caller in the queue.</synopsis>
1232                         <syntax>
1233                                 <channel_snapshot/>
1234                                 <channel_snapshot prefix="Dest"/>
1235                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1236                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1237                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1238                         </syntax>
1239                         <see-also>
1240                                 <ref type="managerEvent">AgentRingNoAnswer</ref>
1241                                 <ref type="managerEvent">AgentComplete</ref>
1242                                 <ref type="managerEvent">AgentConnect</ref>
1243                         </see-also>
1244                 </managerEventInstance>
1245         </managerEvent>
1246         <managerEvent language="en_US" name="AgentRingNoAnswer">
1247                 <managerEventInstance class="EVENT_FLAG_AGENT">
1248                         <synopsis>Raised when a queue member is notified of a caller in the queue and fails to answer.</synopsis>
1249                         <syntax>
1250                                 <channel_snapshot/>
1251                                 <channel_snapshot prefix="Dest"/>
1252                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1253                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1254                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1255                                 <parameter name="RingTime">
1256                                         <para>The time the queue member was rung, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1257                                 </parameter>
1258                         </syntax>
1259                         <see-also>
1260                                 <ref type="managerEvent">AgentCalled</ref>
1261                         </see-also>
1262                 </managerEventInstance>
1263         </managerEvent>
1264         <managerEvent language="en_US" name="AgentComplete">
1265                 <managerEventInstance class="EVENT_FLAG_AGENT">
1266                         <synopsis>Raised when a queue member has finished servicing a caller in the queue.</synopsis>
1267                         <syntax>
1268                                 <channel_snapshot/>
1269                                 <channel_snapshot prefix="Dest"/>
1270                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1271                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1272                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1273                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerAbandon']/managerEventInstance/syntax/parameter[@name='HoldTime'])" />
1274                                 <parameter name="TalkTime">
1275                                         <para>The time the queue member talked with the caller in the queue, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1276                                 </parameter>
1277                                 <parameter name="Reason">
1278                                         <enumlist>
1279                                                 <enum name="caller"/>
1280                                                 <enum name="agent"/>
1281                                                 <enum name="transfer"/>
1282                                         </enumlist>
1283                                 </parameter>
1284                         </syntax>
1285                         <see-also>
1286                                 <ref type="managerEvent">AgentCalled</ref>
1287                                 <ref type="managerEvent">AgentConnect</ref>
1288                         </see-also>
1289                 </managerEventInstance>
1290         </managerEvent>
1291         <managerEvent language="en_US" name="AgentDump">
1292                 <managerEventInstance class="EVENT_FLAG_AGENT">
1293                         <synopsis>Raised when a queue member hangs up on a caller in the queue.</synopsis>
1294                         <syntax>
1295                                 <channel_snapshot/>
1296                                 <channel_snapshot prefix="Dest"/>
1297                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1298                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1299                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1300                         </syntax>
1301                         <see-also>
1302                                 <ref type="managerEvent">AgentCalled</ref>
1303                                 <ref type="managerEvent">AgentConnect</ref>
1304                         </see-also>
1305                 </managerEventInstance>
1306         </managerEvent>
1307         <managerEvent language="en_US" name="AgentConnect">
1308                 <managerEventInstance class="EVENT_FLAG_AGENT">
1309                         <synopsis>Raised when a queue member answers and is bridged to a caller in the queue.</synopsis>
1310                         <syntax>
1311                                 <channel_snapshot/>
1312                                 <channel_snapshot prefix="Dest"/>
1313                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Queue'])" />
1314                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='MemberName'])" />
1315                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueMemberStatus']/managerEventInstance/syntax/parameter[@name='Interface'])" />
1316                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='AgentRingNoAnswer']/managerEventInstance/syntax/parameter[@name='RingTime'])" />
1317                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='QueueCallerAbandon']/managerEventInstance/syntax/parameter[@name='HoldTime'])" />
1318                         </syntax>
1319                         <see-also>
1320                                 <ref type="managerEvent">AgentCalled</ref>
1321                                 <ref type="managerEvent">AgentComplete</ref>
1322                                 <ref type="managerEvent">AgentDump</ref>
1323                         </see-also>
1324                 </managerEventInstance>
1325         </managerEvent>
1326  ***/
1327
1328 enum {
1329         OPT_MARK_AS_ANSWERED =       (1 << 0),
1330         OPT_GO_ON =                  (1 << 1),
1331         OPT_DATA_QUALITY =           (1 << 2),
1332         OPT_CALLEE_GO_ON =           (1 << 3),
1333         OPT_CALLEE_HANGUP =          (1 << 4),
1334         OPT_CALLER_HANGUP =          (1 << 5),
1335         OPT_IGNORE_CALL_FW =         (1 << 6),
1336         OPT_IGNORE_CONNECTEDLINE =   (1 << 7),
1337         OPT_CALLEE_PARK =            (1 << 8),
1338         OPT_CALLER_PARK =            (1 << 9),
1339         OPT_NO_RETRY =               (1 << 10),
1340         OPT_RINGING =                (1 << 11),
1341         OPT_RING_WHEN_RINGING =      (1 << 12),
1342         OPT_CALLEE_TRANSFER =        (1 << 13),
1343         OPT_CALLER_TRANSFER =        (1 << 14),
1344         OPT_CALLEE_AUTOMIXMON =      (1 << 15),
1345         OPT_CALLER_AUTOMIXMON =      (1 << 16),
1346         OPT_CALLEE_AUTOMON =         (1 << 17),
1347         OPT_CALLER_AUTOMON =         (1 << 18),
1348         OPT_PREDIAL_CALLEE =         (1 << 19),
1349         OPT_PREDIAL_CALLER =         (1 << 20),
1350 };
1351
1352 enum {
1353         OPT_ARG_CALLEE_GO_ON = 0,
1354         OPT_ARG_PREDIAL_CALLEE,
1355         OPT_ARG_PREDIAL_CALLER,
1356         /* note: this entry _MUST_ be the last one in the enum */
1357         OPT_ARG_ARRAY_SIZE
1358 };
1359
1360 AST_APP_OPTIONS(queue_exec_options, BEGIN_OPTIONS
1361         AST_APP_OPTION_ARG('b', OPT_PREDIAL_CALLEE, OPT_ARG_PREDIAL_CALLEE),
1362         AST_APP_OPTION_ARG('B', OPT_PREDIAL_CALLER, OPT_ARG_PREDIAL_CALLER),
1363         AST_APP_OPTION('C', OPT_MARK_AS_ANSWERED),
1364         AST_APP_OPTION('c', OPT_GO_ON),
1365         AST_APP_OPTION('d', OPT_DATA_QUALITY),
1366         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
1367         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
1368         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
1369         AST_APP_OPTION('i', OPT_IGNORE_CALL_FW),
1370         AST_APP_OPTION('I', OPT_IGNORE_CONNECTEDLINE),
1371         AST_APP_OPTION('k', OPT_CALLEE_PARK),
1372         AST_APP_OPTION('K', OPT_CALLER_PARK),
1373         AST_APP_OPTION('n', OPT_NO_RETRY),
1374         AST_APP_OPTION('r', OPT_RINGING),
1375         AST_APP_OPTION('R', OPT_RING_WHEN_RINGING),
1376         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
1377         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
1378         AST_APP_OPTION('x', OPT_CALLEE_AUTOMIXMON),
1379         AST_APP_OPTION('X', OPT_CALLER_AUTOMIXMON),
1380         AST_APP_OPTION('w', OPT_CALLEE_AUTOMON),
1381         AST_APP_OPTION('W', OPT_CALLER_AUTOMON),
1382 END_OPTIONS);
1383
1384 enum {
1385         QUEUE_STRATEGY_RINGALL = 0,
1386         QUEUE_STRATEGY_LEASTRECENT,
1387         QUEUE_STRATEGY_FEWESTCALLS,
1388         QUEUE_STRATEGY_RANDOM,
1389         QUEUE_STRATEGY_RRMEMORY,
1390         QUEUE_STRATEGY_LINEAR,
1391         QUEUE_STRATEGY_WRANDOM,
1392         QUEUE_STRATEGY_RRORDERED,
1393 };
1394
1395 enum {
1396         QUEUE_AUTOPAUSE_OFF = 0,
1397         QUEUE_AUTOPAUSE_ON,
1398         QUEUE_AUTOPAUSE_ALL
1399 };
1400
1401 enum queue_reload_mask {
1402         QUEUE_RELOAD_PARAMETERS = (1 << 0),
1403         QUEUE_RELOAD_MEMBER = (1 << 1),
1404         QUEUE_RELOAD_RULES = (1 << 2),
1405         QUEUE_RESET_STATS = (1 << 3),
1406 };
1407
1408 static const struct strategy {
1409         int strategy;
1410         const char *name;
1411 } strategies[] = {
1412         { QUEUE_STRATEGY_RINGALL, "ringall" },
1413         { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
1414         { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
1415         { QUEUE_STRATEGY_RANDOM, "random" },
1416         { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
1417         { QUEUE_STRATEGY_RRMEMORY, "roundrobin" },
1418         { QUEUE_STRATEGY_LINEAR, "linear" },
1419         { QUEUE_STRATEGY_WRANDOM, "wrandom"},
1420         { QUEUE_STRATEGY_RRORDERED, "rrordered"},
1421 };
1422
1423 static const struct autopause {
1424         int autopause;
1425         const char *name;
1426 } autopausesmodes [] = {
1427         { QUEUE_AUTOPAUSE_OFF,"no" },
1428         { QUEUE_AUTOPAUSE_ON, "yes" },
1429         { QUEUE_AUTOPAUSE_ALL,"all" },
1430 };
1431
1432 #define DEFAULT_RETRY           5
1433 #define DEFAULT_TIMEOUT         15
1434 #define RECHECK                 1               /*!< Recheck every second to see we we're at the top yet */
1435 #define MAX_PERIODIC_ANNOUNCEMENTS 10           /*!< The maximum periodic announcements we can have */
1436 /*!
1437  * \brief The minimum number of seconds between position announcements.
1438  * \note The default value of 15 provides backwards compatibility.
1439  */
1440 #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15
1441
1442 #define MAX_QUEUE_BUCKETS 53
1443
1444 #define RES_OKAY        0               /*!< Action completed */
1445 #define RES_EXISTS      (-1)            /*!< Entry already exists */
1446 #define RES_OUTOFMEMORY (-2)            /*!< Out of memory */
1447 #define RES_NOSUCHQUEUE (-3)            /*!< No such queue */
1448 #define RES_NOT_DYNAMIC (-4)            /*!< Member is not dynamic */
1449 #define RES_NOT_CALLER  (-5)            /*!< Caller not found */
1450
1451 static char *app = "Queue";
1452
1453 static char *app_aqm = "AddQueueMember" ;
1454
1455 static char *app_rqm = "RemoveQueueMember" ;
1456
1457 static char *app_pqm = "PauseQueueMember" ;
1458
1459 static char *app_upqm = "UnpauseQueueMember" ;
1460
1461 static char *app_ql = "QueueLog" ;
1462
1463 static char *app_qupd = "QueueUpdate";
1464
1465 /*! \brief Persistent Members astdb family */
1466 static const char * const pm_family = "Queue/PersistentMembers";
1467
1468 /*! \brief queues.conf [general] option */
1469 static int queue_persistent_members = 0;
1470
1471 /*! \brief queues.conf per-queue weight option */
1472 static int use_weight = 0;
1473
1474 /*! \brief queues.conf [general] option */
1475 static int autofill_default = 1;
1476
1477 /*! \brief queues.conf [general] option */
1478 static int montype_default = 0;
1479
1480 /*! \brief queues.conf [general] option */
1481 static int shared_lastcall = 0;
1482
1483 /*! \brief queuesrules.conf [general] option */
1484 static int realtime_rules = 0;
1485
1486 /*! \brief Subscription to device state change messages */
1487 static struct stasis_subscription *device_state_sub;
1488
1489 /*! \brief queues.conf [general] option */
1490 static int update_cdr = 0;
1491
1492 /*! \brief queues.conf [general] option */
1493 static int negative_penalty_invalid = 0;
1494
1495 /*! \brief queues.conf [general] option */
1496 static int log_membername_as_agent = 0;
1497
1498 /*! \brief name of the ringinuse field in the realtime database */
1499 static char *realtime_ringinuse_field;
1500
1501 enum queue_result {
1502         QUEUE_UNKNOWN = 0,
1503         QUEUE_TIMEOUT = 1,
1504         QUEUE_JOINEMPTY = 2,
1505         QUEUE_LEAVEEMPTY = 3,
1506         QUEUE_JOINUNAVAIL = 4,
1507         QUEUE_LEAVEUNAVAIL = 5,
1508         QUEUE_FULL = 6,
1509         QUEUE_CONTINUE = 7,
1510 };
1511
1512 static const struct {
1513         enum queue_result id;
1514         char *text;
1515 } queue_results[] = {
1516         { QUEUE_UNKNOWN, "UNKNOWN" },
1517         { QUEUE_TIMEOUT, "TIMEOUT" },
1518         { QUEUE_JOINEMPTY,"JOINEMPTY" },
1519         { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
1520         { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
1521         { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
1522         { QUEUE_FULL, "FULL" },
1523         { QUEUE_CONTINUE, "CONTINUE" },
1524 };
1525
1526 enum queue_timeout_priority {
1527         TIMEOUT_PRIORITY_APP,
1528         TIMEOUT_PRIORITY_CONF,
1529 };
1530
1531 /*! \brief We define a custom "local user" structure because we
1532  *  use it not only for keeping track of what is in use but
1533  *  also for keeping track of who we're dialing.
1534  *
1535  *  There are two "links" defined in this structure, q_next and call_next.
1536  *  q_next links ALL defined callattempt structures into a linked list. call_next is
1537  *  a link which allows for a subset of the callattempts to be traversed. This subset
1538  *  is used in wait_for_answer so that irrelevant callattempts are not traversed. This
1539  *  also is helpful so that queue logs are always accurate in the case where a call to
1540  *  a member times out, especially if using the ringall strategy.
1541 */
1542
1543 struct callattempt {
1544         struct callattempt *q_next;
1545         struct callattempt *call_next;
1546         struct ast_channel *chan;
1547         char interface[256];                    /*!< An Asterisk dial string (not a channel name) */
1548         int metric;
1549         time_t lastcall;
1550         struct call_queue *lastqueue;
1551         struct member *member;
1552         /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
1553         struct ast_party_connected_line connected;
1554         /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
1555         unsigned int pending_connected_update:1;
1556         /*! TRUE if the connected line update is blocked. */
1557         unsigned int block_connected_update:1;
1558         /*! TRUE if caller id is not available for connected line */
1559         unsigned int dial_callerid_absent:1;
1560         /*! TRUE if the call is still active */
1561         unsigned int stillgoing:1;
1562         struct ast_aoc_decoded *aoc_s_rate_list;
1563         /*! Original channel name.  Must be freed.  Could be NULL if allocation failed. */
1564         char *orig_chan_name;
1565 };
1566
1567
1568 struct queue_ent {
1569         struct call_queue *parent;             /*!< What queue is our parent */
1570         char moh[MAX_MUSICCLASS];              /*!< Name of musiconhold to be used */
1571         char announce[PATH_MAX];               /*!< Announcement to play for member when call is answered */
1572         char context[AST_MAX_CONTEXT];         /*!< Context when user exits queue */
1573         char digits[AST_MAX_EXTENSION];        /*!< Digits entered while in queue */
1574         const char *predial_callee;            /*!< Gosub app arguments for outgoing calls.  NULL if not supplied. */
1575         int valid_digits;                      /*!< Digits entered correspond to valid extension. Exited */
1576         int pos;                               /*!< Where we are in the queue */
1577         int prio;                              /*!< Our priority */
1578         int last_pos_said;                     /*!< Last position we told the user */
1579         int ring_when_ringing;                 /*!< Should we only use ring indication when a channel is ringing? */
1580         time_t last_periodic_announce_time;    /*!< The last time we played a periodic announcement */
1581         int last_periodic_announce_sound;      /*!< The last periodic announcement we made */
1582         time_t last_pos;                       /*!< Last time we told the user their position */
1583         int opos;                              /*!< Where we started in the queue */
1584         int handled;                           /*!< Whether our call was handled */
1585         int pending;                           /*!< Non-zero if we are attempting to call a member */
1586         int max_penalty;                       /*!< Limit the members that can take this call to this penalty or lower */
1587         int min_penalty;                       /*!< Limit the members that can take this call to this penalty or higher */
1588         int raise_penalty;                     /*!< Float lower penalty mambers to a minimum penalty */
1589         int linpos;                            /*!< If using linear strategy, what position are we at? */
1590         int linwrapped;                        /*!< Is the linpos wrapped? */
1591         time_t start;                          /*!< When we started holding */
1592         time_t expire;                         /*!< When this entry should expire (time out of queue) */
1593         int cancel_answered_elsewhere;         /*!< Whether we should force the CAE flag on this call (C) option*/
1594         struct ast_channel *chan;              /*!< Our channel */
1595         AST_LIST_HEAD_NOLOCK(,penalty_rule) qe_rules; /*!< Local copy of the queue's penalty rules */
1596         struct penalty_rule *pr;               /*!< Pointer to the next penalty rule to implement */
1597         struct queue_ent *next;                /*!< The next queue entry */
1598 };
1599
1600 struct member {
1601         char interface[AST_CHANNEL_NAME];    /*!< Technology/Location to dial to reach this member*/
1602         char state_exten[AST_MAX_EXTENSION]; /*!< Extension to get state from (if using hint) */
1603         char state_context[AST_MAX_CONTEXT]; /*!< Context to use when getting state (if using hint) */
1604         char state_interface[AST_CHANNEL_NAME]; /*!< Technology/Location from which to read devicestate changes */
1605         int state_id;                        /*!< Extension state callback id (if using hint) */
1606         char membername[80];                 /*!< Member name to use in queue logs */
1607         int penalty;                         /*!< Are we a last resort? */
1608         int calls;                           /*!< Number of calls serviced by this member */
1609         int dynamic;                         /*!< Are we dynamically added? */
1610         int realtime;                        /*!< Is this member realtime? */
1611         int status;                          /*!< Status of queue member */
1612         int paused;                          /*!< Are we paused (not accepting calls)? */
1613         char reason_paused[80];              /*!< Reason of paused if member is paused */
1614         int queuepos;                        /*!< In what order (pertains to certain strategies) should this member be called? */
1615         int callcompletedinsl;               /*!< Whether the current call was completed within service level */
1616         int wrapuptime;                      /*!< Wrapup Time */
1617         time_t starttime;                    /*!< The time at which the member answered the current caller. */
1618         time_t lastcall;                     /*!< When last successful call was hungup */
1619         time_t lastpause;                    /*!< When started the last pause */
1620         struct call_queue *lastqueue;        /*!< Last queue we received a call */
1621         unsigned int dead:1;                 /*!< Used to detect members deleted in realtime */
1622         unsigned int delme:1;                /*!< Flag to delete entry on reload */
1623         char rt_uniqueid[80];                /*!< Unique id of realtime member entry */
1624         unsigned int ringinuse:1;            /*!< Flag to ring queue members even if their status is 'inuse' */
1625 };
1626
1627 enum empty_conditions {
1628         QUEUE_EMPTY_PENALTY = (1 << 0),
1629         QUEUE_EMPTY_PAUSED = (1 << 1),
1630         QUEUE_EMPTY_INUSE = (1 << 2),
1631         QUEUE_EMPTY_RINGING = (1 << 3),
1632         QUEUE_EMPTY_UNAVAILABLE = (1 << 4),
1633         QUEUE_EMPTY_INVALID = (1 << 5),
1634         QUEUE_EMPTY_UNKNOWN = (1 << 6),
1635         QUEUE_EMPTY_WRAPUP = (1 << 7),
1636 };
1637
1638 enum member_properties {
1639         MEMBER_PENALTY = 0,
1640         MEMBER_RINGINUSE = 1,
1641 };
1642
1643 /* values used in multi-bit flags in call_queue */
1644 #define ANNOUNCEHOLDTIME_ALWAYS 1
1645 #define ANNOUNCEHOLDTIME_ONCE 2
1646 #define QUEUE_EVENT_VARIABLES 3
1647
1648 struct penalty_rule {
1649         int time;                           /*!< Number of seconds that need to pass before applying this rule */
1650         int max_value;                      /*!< The amount specified in the penalty rule for max penalty */
1651         int min_value;                      /*!< The amount specified in the penalty rule for min penalty */
1652         int raise_value;                      /*!< The amount specified in the penalty rule for min penalty */
1653         int max_relative;                   /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
1654         int min_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1655         int raise_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1656         AST_LIST_ENTRY(penalty_rule) list;  /*!< Next penalty_rule */
1657 };
1658
1659 #define ANNOUNCEPOSITION_YES 1 /*!< We announce position */
1660 #define ANNOUNCEPOSITION_NO 2 /*!< We don't announce position */
1661 #define ANNOUNCEPOSITION_MORE_THAN 3 /*!< We say "Currently there are more than <limit>" */
1662 #define ANNOUNCEPOSITION_LIMIT 4 /*!< We not announce position more than <limit> */
1663
1664 struct call_queue {
1665         AST_DECLARE_STRING_FIELDS(
1666                 /*! Queue name */
1667                 AST_STRING_FIELD(name);
1668                 /*! Music on Hold class */
1669                 AST_STRING_FIELD(moh);
1670                 /*! Announcement to play when call is answered */
1671                 AST_STRING_FIELD(announce);
1672                 /*! Exit context */
1673                 AST_STRING_FIELD(context);
1674                 /*! Macro to run upon member connection */
1675                 AST_STRING_FIELD(membermacro);
1676                 /*! Gosub to run upon member connection */
1677                 AST_STRING_FIELD(membergosub);
1678                 /*! Default rule to use if none specified in call to Queue() */
1679                 AST_STRING_FIELD(defaultrule);
1680                 /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
1681                 AST_STRING_FIELD(sound_next);
1682                 /*! Sound file: "There are currently" (def. queue-thereare) */
1683                 AST_STRING_FIELD(sound_thereare);
1684                 /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
1685                 AST_STRING_FIELD(sound_calls);
1686                 /*! Sound file: "Currently there are more than" (def. queue-quantity1) */
1687                 AST_STRING_FIELD(queue_quantity1);
1688                 /*! Sound file: "callers waiting to speak with a representative" (def. queue-quantity2) */
1689                 AST_STRING_FIELD(queue_quantity2);
1690                 /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
1691                 AST_STRING_FIELD(sound_holdtime);
1692                 /*! Sound file: "minutes." (def. queue-minutes) */
1693                 AST_STRING_FIELD(sound_minutes);
1694                 /*! Sound file: "minute." (def. queue-minute) */
1695                 AST_STRING_FIELD(sound_minute);
1696                 /*! Sound file: "seconds." (def. queue-seconds) */
1697                 AST_STRING_FIELD(sound_seconds);
1698                 /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
1699                 AST_STRING_FIELD(sound_thanks);
1700                 /*! Sound file: Custom announce for caller, no default */
1701                 AST_STRING_FIELD(sound_callerannounce);
1702                 /*! Sound file: "Hold time" (def. queue-reporthold) */
1703                 AST_STRING_FIELD(sound_reporthold);
1704         );
1705         /*! Sound files: Custom announce, no default */
1706         struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
1707         unsigned int dead:1;
1708         unsigned int ringinuse:1;
1709         unsigned int announce_to_first_user:1; /*!< Whether or not we announce to the first user in a queue */
1710         unsigned int setinterfacevar:1;
1711         unsigned int setqueuevar:1;
1712         unsigned int setqueueentryvar:1;
1713         unsigned int reportholdtime:1;
1714         unsigned int wrapped:1;
1715         unsigned int timeoutrestart:1;
1716         unsigned int announceholdtime:2;
1717         unsigned int announceposition:3;
1718         unsigned int announceposition_only_up:1; /*!< Only announce position if it has improved */
1719         int strategy:4;
1720         unsigned int realtime:1;
1721         unsigned int found:1;
1722         unsigned int relativeperiodicannounce:1;
1723         unsigned int autopausebusy:1;
1724         unsigned int autopauseunavail:1;
1725         enum empty_conditions joinempty;
1726         enum empty_conditions leavewhenempty;
1727         int announcepositionlimit;          /*!< How many positions we announce? */
1728         int announcefrequency;              /*!< How often to announce their position */
1729         int minannouncefrequency;           /*!< The minimum number of seconds between position announcements (def. 15) */
1730         int periodicannouncefrequency;      /*!< How often to play periodic announcement */
1731         int numperiodicannounce;            /*!< The number of periodic announcements configured */
1732         int randomperiodicannounce;         /*!< Are periodic announcments randomly chosen */
1733         int roundingseconds;                /*!< How many seconds do we round to? */
1734         int holdtime;                       /*!< Current avg holdtime, based on an exponential average */
1735         int talktime;                       /*!< Current avg talktime, based on the same exponential average */
1736         int callscompleted;                 /*!< Number of queue calls completed */
1737         int callsabandoned;                 /*!< Number of queue calls abandoned */
1738         int callsabandonedinsl;             /*!< Number of queue calls abandoned in servicelevel */
1739         int servicelevel;                   /*!< seconds setting for servicelevel*/
1740         int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
1741         char monfmt[8];                     /*!< Format to use when recording calls */
1742         int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
1743         int count;                          /*!< How many entries */
1744         int maxlen;                         /*!< Max number of entries */
1745         int wrapuptime;                     /*!< Wrapup Time */
1746         int penaltymemberslimit;            /*!< Disregard penalty when queue has fewer than this many members */
1747
1748         int retry;                          /*!< Retry calling everyone after this amount of time */
1749         int timeout;                        /*!< How long to wait for an answer */
1750         int weight;                         /*!< Respective weight */
1751         int autopause;                      /*!< Auto pause queue members if they fail to answer */
1752         int autopausedelay;                 /*!< Delay auto pause for autopausedelay seconds since last call */
1753         int timeoutpriority;                /*!< Do we allow a fraction of the timeout to occur for a ring? */
1754
1755         /* Queue strategy things */
1756         int rrpos;                          /*!< Round Robin - position */
1757         int memberdelay;                    /*!< Seconds to delay connecting member to caller */
1758         int autofill;                       /*!< Ignore the head call status and ring an available agent */
1759
1760         struct ao2_container *members;      /*!< Head of the list of members */
1761         struct queue_ent *head;             /*!< Head of the list of callers */
1762         AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
1763         AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
1764 };
1765
1766 struct rule_list {
1767         char name[80];
1768         AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
1769         AST_LIST_ENTRY(rule_list) list;
1770 };
1771
1772 static AST_LIST_HEAD_STATIC(rule_lists, rule_list);
1773
1774 static struct ao2_container *queues;
1775
1776 static void update_realtime_members(struct call_queue *q);
1777 static struct member *interface_exists(struct call_queue *q, const char *interface);
1778 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
1779 static int update_queue(struct call_queue *q, struct member *member, int callcompletedinsl, time_t starttime);
1780
1781 static struct member *find_member_by_queuename_and_interface(const char *queuename, const char *interface);
1782 /*! \brief sets the QUEUESTATUS channel variable */
1783 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
1784 {
1785         int i;
1786
1787         for (i = 0; i < ARRAY_LEN(queue_results); i++) {
1788                 if (queue_results[i].id == res) {
1789                         pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
1790                         return;
1791                 }
1792         }
1793 }
1794
1795 static const char *int2strat(int strategy)
1796 {
1797         int x;
1798
1799         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1800                 if (strategy == strategies[x].strategy) {
1801                         return strategies[x].name;
1802                 }
1803         }
1804
1805         return "<unknown>";
1806 }
1807
1808 static int strat2int(const char *strategy)
1809 {
1810         int x;
1811
1812         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1813                 if (!strcasecmp(strategy, strategies[x].name)) {
1814                         return strategies[x].strategy;
1815                 }
1816         }
1817
1818         return -1;
1819 }
1820
1821 static int autopause2int(const char *autopause)
1822 {
1823         int x;
1824         /*This 'double check' that default value is OFF */
1825         if (ast_strlen_zero(autopause)) {
1826                 return QUEUE_AUTOPAUSE_OFF;
1827         }
1828
1829         /*This 'double check' is to ensure old values works */
1830         if(ast_true(autopause)) {
1831                 return QUEUE_AUTOPAUSE_ON;
1832         }
1833
1834         for (x = 0; x < ARRAY_LEN(autopausesmodes); x++) {
1835                 if (!strcasecmp(autopause, autopausesmodes[x].name)) {
1836                         return autopausesmodes[x].autopause;
1837                 }
1838         }
1839
1840         /*This 'double check' that default value is OFF */
1841         return QUEUE_AUTOPAUSE_OFF;
1842 }
1843
1844 static int queue_hash_cb(const void *obj, const int flags)
1845 {
1846         const struct call_queue *q = obj;
1847
1848         return ast_str_case_hash(q->name);
1849 }
1850
1851 static int queue_cmp_cb(void *obj, void *arg, int flags)
1852 {
1853         struct call_queue *q = obj, *q2 = arg;
1854         return !strcasecmp(q->name, q2->name) ? CMP_MATCH | CMP_STOP : 0;
1855 }
1856
1857 /*!
1858  * \brief Return wrapuptime
1859  *
1860  * This function checks if wrapuptime in member is set and return this value.
1861  * Otherwise return value the wrapuptime in the queue configuration
1862  * \return integer value
1863  */
1864 static int get_wrapuptime(struct call_queue *q, struct member *member)
1865 {
1866         if (member->wrapuptime) {
1867                 return member->wrapuptime;
1868         }
1869         return q->wrapuptime;
1870 }
1871
1872 /*! \internal
1873  * \brief ao2_callback, Decreases queuepos of all followers with a queuepos greater than arg.
1874  * \param obj the member being acted on
1875  * \param arg pointer to an integer containing the position value that was removed and requires reduction for anything above
1876  */
1877 static int queue_member_decrement_followers(void *obj, void *arg, int flag)
1878 {
1879         struct member *mem = obj;
1880         int *decrement_followers_after = arg;
1881
1882         if (mem->queuepos > *decrement_followers_after) {
1883                 mem->queuepos--;
1884         }
1885
1886         return 0;
1887 }
1888
1889 /*! \internal
1890  * \brief ao2_callback, finds members in a queue marked for deletion and in a cascading fashion runs queue_member_decrement_followers
1891  *        on them. This callback should always be ran before performing mass unlinking of delmarked members from queues.
1892  * \param obj member being acted on
1893  * \param arg pointer to the queue members are being removed from
1894  */
1895 static int queue_delme_members_decrement_followers(void *obj, void *arg, int flag)
1896 {
1897         struct member *mem = obj;
1898         struct call_queue *queue = arg;
1899         int rrpos = mem->queuepos;
1900
1901         if (mem->delme) {
1902                 ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &rrpos);
1903         }
1904
1905         return 0;
1906 }
1907
1908 /*! \internal
1909  * \brief Use this to decrement followers during removal of a member
1910  * \param queue which queue the member is being removed from
1911  * \param mem which member is being removed from the queue
1912  */
1913 static void queue_member_follower_removal(struct call_queue *queue, struct member *mem)
1914 {
1915         int pos = mem->queuepos;
1916
1917         /* 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
1918          * who would have been next otherwise. */
1919         if (pos < queue->rrpos) {
1920                 queue->rrpos--;
1921         }
1922
1923         ao2_callback(queue->members, OBJ_NODATA | OBJ_MULTIPLE, queue_member_decrement_followers, &pos);
1924 }
1925
1926 #define queue_ref(q)                            ao2_bump(q)
1927 #define queue_unref(q)                          ({ ao2_cleanup(q); NULL; })
1928 #define queue_t_ref(q, tag)                     ao2_t_bump(q, tag)
1929 #define queue_t_unref(q, tag)           ({ ao2_t_cleanup(q, tag); NULL; })
1930 #define queues_t_link(c, q, tag)        ao2_t_link(c, q, tag)
1931 #define queues_t_unlink(c, q, tag)      ao2_t_unlink(c, q, tag)
1932
1933 /*! \brief Set variables of queue */
1934 static void set_queue_variables(struct call_queue *q, struct ast_channel *chan)
1935 {
1936         char interfacevar[256]="";
1937         float sl = 0;
1938
1939         ao2_lock(q);
1940
1941         if (q->setqueuevar) {
1942                 sl = 0;
1943                 if (q->callscompleted > 0) {
1944                         sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
1945                 }
1946
1947                 snprintf(interfacevar, sizeof(interfacevar),
1948                         "QUEUENAME=%s,QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
1949                         q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned,  q->servicelevel, sl);
1950
1951                 ao2_unlock(q);
1952
1953                 pbx_builtin_setvar_multiple(chan, interfacevar);
1954         } else {
1955                 ao2_unlock(q);
1956         }
1957 }
1958
1959 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
1960 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
1961 {
1962         struct queue_ent *cur;
1963
1964         if (!q || !new)
1965                 return;
1966         if (prev) {
1967                 cur = prev->next;
1968                 prev->next = new;
1969         } else {
1970                 cur = q->head;
1971                 q->head = new;
1972         }
1973         new->next = cur;
1974
1975         /* every queue_ent must have a reference to it's parent call_queue, this
1976          * reference does not go away until the end of the queue_ent's life, meaning
1977          * that even when the queue_ent leaves the call_queue this ref must remain. */
1978         queue_ref(q);
1979         new->parent = q;
1980         new->pos = ++(*pos);
1981         new->opos = *pos;
1982 }
1983
1984 static struct ast_manager_event_blob *queue_channel_to_ami(const char *type, struct stasis_message *message)
1985 {
1986         struct ast_channel_blob *obj = stasis_message_data(message);
1987         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
1988         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
1989
1990         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
1991         event_string = ast_manager_str_from_json_object(obj->blob, NULL);
1992         if (!channel_string || !event_string) {
1993                 return NULL;
1994         }
1995
1996         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
1997                 "%s"
1998                 "%s",
1999                 ast_str_buffer(channel_string),
2000                 ast_str_buffer(event_string));
2001 }
2002
2003 static struct ast_manager_event_blob *queue_caller_join_to_ami(struct stasis_message *message)
2004 {
2005         return queue_channel_to_ami("QueueCallerJoin", message);
2006 }
2007
2008 static struct ast_manager_event_blob *queue_caller_leave_to_ami(struct stasis_message *message)
2009 {
2010         return queue_channel_to_ami("QueueCallerLeave", message);
2011 }
2012
2013 static struct ast_manager_event_blob *queue_caller_abandon_to_ami(struct stasis_message *message)
2014 {
2015         return queue_channel_to_ami("QueueCallerAbandon", message);
2016 }
2017
2018 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_join_type,
2019         .to_ami = queue_caller_join_to_ami,
2020         );
2021 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_leave_type,
2022         .to_ami = queue_caller_leave_to_ami,
2023         );
2024 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_caller_abandon_type,
2025         .to_ami = queue_caller_abandon_to_ami,
2026         );
2027
2028 static struct ast_manager_event_blob *queue_member_to_ami(const char *type, struct stasis_message *message)
2029 {
2030         struct ast_json_payload *payload = stasis_message_data(message);
2031         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
2032
2033         event_string = ast_manager_str_from_json_object(payload->json, NULL);
2034         if (!event_string) {
2035                 return NULL;
2036         }
2037
2038         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
2039                 "%s",
2040                 ast_str_buffer(event_string));
2041 }
2042
2043 static struct ast_manager_event_blob *queue_member_status_to_ami(struct stasis_message *message)
2044 {
2045         return queue_member_to_ami("QueueMemberStatus", message);
2046 }
2047
2048 static struct ast_manager_event_blob *queue_member_added_to_ami(struct stasis_message *message)
2049 {
2050         return queue_member_to_ami("QueueMemberAdded", message);
2051 }
2052
2053 static struct ast_manager_event_blob *queue_member_removed_to_ami(struct stasis_message *message)
2054 {
2055         return queue_member_to_ami("QueueMemberRemoved", message);
2056 }
2057
2058 static struct ast_manager_event_blob *queue_member_pause_to_ami(struct stasis_message *message)
2059 {
2060         return queue_member_to_ami("QueueMemberPause", message);
2061 }
2062
2063 static struct ast_manager_event_blob *queue_member_penalty_to_ami(struct stasis_message *message)
2064 {
2065         return queue_member_to_ami("QueueMemberPenalty", message);
2066 }
2067
2068 static struct ast_manager_event_blob *queue_member_ringinuse_to_ami(struct stasis_message *message)
2069 {
2070         return queue_member_to_ami("QueueMemberRinginuse", message);
2071 }
2072
2073 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_status_type,
2074         .to_ami = queue_member_status_to_ami,
2075         );
2076 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_added_type,
2077         .to_ami = queue_member_added_to_ami,
2078         );
2079 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_removed_type,
2080         .to_ami = queue_member_removed_to_ami,
2081         );
2082 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_pause_type,
2083         .to_ami = queue_member_pause_to_ami,
2084         );
2085 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_penalty_type,
2086         .to_ami = queue_member_penalty_to_ami,
2087         );
2088 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_member_ringinuse_type,
2089         .to_ami = queue_member_ringinuse_to_ami,
2090         );
2091
2092 static struct ast_manager_event_blob *queue_multi_channel_to_ami(const char *type, struct stasis_message *message)
2093 {
2094         struct ast_multi_channel_blob *obj = stasis_message_data(message);
2095         struct ast_channel_snapshot *caller;
2096         struct ast_channel_snapshot *agent;
2097         RAII_VAR(struct ast_str *, caller_event_string, NULL, ast_free);
2098         RAII_VAR(struct ast_str *, agent_event_string, NULL, ast_free);
2099         RAII_VAR(struct ast_str *, event_string, NULL, ast_free);
2100
2101         caller = ast_multi_channel_blob_get_channel(obj, "caller");
2102         if (caller) {
2103                 caller_event_string = ast_manager_build_channel_state_string(caller);
2104                 if (!caller_event_string) {
2105                         ast_log(LOG_NOTICE, "No caller event string, bailing\n");
2106                         return NULL;
2107                 }
2108         }
2109
2110         agent = ast_multi_channel_blob_get_channel(obj, "agent");
2111         if (agent) {
2112                 agent_event_string = ast_manager_build_channel_state_string_prefix(agent, "Dest");
2113                 if (!agent_event_string) {
2114                         ast_log(LOG_NOTICE, "No agent event string, bailing\n");
2115                         return NULL;
2116                 }
2117         }
2118
2119         event_string = ast_manager_str_from_json_object(ast_multi_channel_blob_get_json(obj), NULL);
2120         if (!event_string) {
2121                 return NULL;
2122         }
2123
2124         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, type,
2125                 "%s"
2126                 "%s"
2127                 "%s",
2128                 caller_event_string ? ast_str_buffer(caller_event_string) : "",
2129                 agent_event_string ? ast_str_buffer(agent_event_string) : "",
2130                 ast_str_buffer(event_string));
2131 }
2132
2133 static struct ast_manager_event_blob *queue_agent_called_to_ami(struct stasis_message *message)
2134 {
2135         return queue_multi_channel_to_ami("AgentCalled", message);
2136 }
2137
2138 static struct ast_manager_event_blob *queue_agent_connect_to_ami(struct stasis_message *message)
2139 {
2140         return queue_multi_channel_to_ami("AgentConnect", message);
2141 }
2142
2143 static struct ast_manager_event_blob *queue_agent_complete_to_ami(struct stasis_message *message)
2144 {
2145         return queue_multi_channel_to_ami("AgentComplete", message);
2146 }
2147
2148 static struct ast_manager_event_blob *queue_agent_dump_to_ami(struct stasis_message *message)
2149 {
2150         return queue_multi_channel_to_ami("AgentDump", message);
2151 }
2152
2153 static struct ast_manager_event_blob *queue_agent_ringnoanswer_to_ami(struct stasis_message *message)
2154 {
2155         return queue_multi_channel_to_ami("AgentRingNoAnswer", message);
2156 }
2157
2158 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_called_type,
2159         .to_ami = queue_agent_called_to_ami,
2160         );
2161 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_connect_type,
2162         .to_ami = queue_agent_connect_to_ami,
2163         );
2164 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_complete_type,
2165         .to_ami = queue_agent_complete_to_ami,
2166         );
2167 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_dump_type,
2168         .to_ami = queue_agent_dump_to_ami,
2169         );
2170 STASIS_MESSAGE_TYPE_DEFN_LOCAL(queue_agent_ringnoanswer_type,
2171         .to_ami = queue_agent_ringnoanswer_to_ami,
2172         );
2173
2174 static void queue_publish_multi_channel_snapshot_blob(struct stasis_topic *topic,
2175                 struct ast_channel_snapshot *caller_snapshot,
2176                 struct ast_channel_snapshot *agent_snapshot,
2177                 struct stasis_message_type *type, struct ast_json *blob)
2178 {
2179         RAII_VAR(struct ast_multi_channel_blob *, payload, NULL, ao2_cleanup);
2180         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2181
2182         if (!type) {
2183                 return;
2184         }
2185
2186         payload = ast_multi_channel_blob_create(blob);
2187         if (!payload) {
2188                 return;
2189         }
2190
2191         if (caller_snapshot) {
2192                 ast_multi_channel_blob_add_channel(payload, "caller", caller_snapshot);
2193         } else {
2194                 ast_debug(1, "Empty caller_snapshot; sending incomplete event\n");
2195         }
2196
2197         if (agent_snapshot) {
2198                 ast_multi_channel_blob_add_channel(payload, "agent", agent_snapshot);
2199         }
2200
2201         msg = stasis_message_create(type, payload);
2202         if (!msg) {
2203                 return;
2204         }
2205
2206         stasis_publish(topic, msg);
2207 }
2208
2209 static void queue_publish_multi_channel_blob(struct ast_channel *caller, struct ast_channel *agent,
2210                 struct stasis_message_type *type, struct ast_json *blob)
2211 {
2212         RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
2213         RAII_VAR(struct ast_channel_snapshot *, agent_snapshot, NULL, ao2_cleanup);
2214
2215         ast_channel_lock(caller);
2216         caller_snapshot = ast_channel_snapshot_create(caller);
2217         ast_channel_unlock(caller);
2218         ast_channel_lock(agent);
2219         agent_snapshot = ast_channel_snapshot_create(agent);
2220         ast_channel_unlock(agent);
2221
2222         if (!caller_snapshot || !agent_snapshot) {
2223                 return;
2224         }
2225
2226         queue_publish_multi_channel_snapshot_blob(ast_channel_topic(caller), caller_snapshot,
2227                         agent_snapshot, type, blob);
2228 }
2229
2230 /*!
2231  * \internal
2232  * \brief Publish the member blob.
2233  * \since 12.0.0
2234  *
2235  * \param type Stasis message type to publish.
2236  * \param blob The information being published.
2237  *
2238  * \note The json blob reference is passed to this function.
2239  *
2240  * \return Nothing
2241  */
2242 static void queue_publish_member_blob(struct stasis_message_type *type, struct ast_json *blob)
2243 {
2244         RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
2245         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
2246
2247         if (!blob || !type) {
2248                 ast_json_unref(blob);
2249                 return;
2250         }
2251
2252         payload = ast_json_payload_create(blob);
2253         ast_json_unref(blob);
2254         if (!payload) {
2255                 return;
2256         }
2257
2258         msg = stasis_message_create(type, payload);
2259         if (!msg) {
2260                 return;
2261         }
2262
2263         stasis_publish(ast_manager_get_topic(), msg);
2264 }
2265
2266 static struct ast_json *queue_member_blob_create(struct call_queue *q, struct member *mem)
2267 {
2268         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, s: i}",
2269                 "Queue", q->name,
2270                 "MemberName", mem->membername,
2271                 "Interface", mem->interface,
2272                 "StateInterface", mem->state_interface,
2273                 "Membership", (mem->dynamic ? "dynamic" : (mem->realtime ? "realtime" : "static")),
2274                 "Penalty", mem->penalty,
2275                 "CallsTaken", mem->calls,
2276                 "LastCall", (int)mem->lastcall,
2277                 "LastPause", (int)mem->lastpause,
2278                 "InCall", mem->starttime ? 1 : 0,
2279                 "Status", mem->status,
2280                 "Paused", mem->paused,
2281                 "PausedReason", mem->reason_paused,
2282                 "Ringinuse", mem->ringinuse,
2283                 "Wrapuptime", mem->wrapuptime);
2284 }
2285
2286 /*! \brief Check if members are available
2287  *
2288  * This function checks to see if members are available to be called. If any member
2289  * is available, the function immediately returns 0. If no members are available,
2290  * then -1 is returned.
2291  */
2292 static int get_member_status(struct call_queue *q, int max_penalty, int min_penalty, int raise_penalty, enum empty_conditions conditions, int devstate)
2293 {
2294         struct member *member;
2295         struct ao2_iterator mem_iter;
2296
2297         ao2_lock(q);
2298         mem_iter = ao2_iterator_init(q->members, 0);
2299         for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
2300                 int penalty = member->penalty;
2301                 if (raise_penalty != INT_MAX && penalty < raise_penalty) {
2302                         ast_debug(4, "%s is having his penalty raised up from %d to %d\n", member->membername, penalty, raise_penalty);
2303                         penalty = raise_penalty;
2304                 }
2305                 if ((max_penalty != INT_MAX && penalty > max_penalty) || (min_penalty != INT_MAX && penalty < min_penalty)) {
2306                         if (conditions & QUEUE_EMPTY_PENALTY) {
2307                                 ast_debug(4, "%s is unavailable because his penalty is not between %d and %d\n", member->membername, min_penalty, max_penalty);
2308                                 continue;
2309                         }
2310                 }
2311
2312                 switch (devstate ? ast_device_state(member->state_interface) : member->status) {
2313                 case AST_DEVICE_INVALID:
2314                         if (conditions & QUEUE_EMPTY_INVALID) {
2315                                 ast_debug(4, "%s is unavailable because his device state is 'invalid'\n", member->membername);
2316                                 break;
2317                         }
2318                         goto default_case;
2319                 case AST_DEVICE_UNAVAILABLE:
2320                         if (conditions & QUEUE_EMPTY_UNAVAILABLE) {
2321                                 ast_debug(4, "%s is unavailable because his device state is 'unavailable'\n", member->membername);
2322                                 break;
2323                         }
2324                         goto default_case;
2325                 case AST_DEVICE_INUSE:
2326                         if (conditions & QUEUE_EMPTY_INUSE) {
2327                                 ast_debug(4, "%s is unavailable because his device state is 'inuse'\n", member->membername);
2328                                 break;
2329                         }
2330                         goto default_case;
2331                 case AST_DEVICE_RINGING:
2332                         if (conditions & QUEUE_EMPTY_RINGING) {
2333                                 ast_debug(4, "%s is unavailable because his device state is 'ringing'\n", member->membername);
2334                                 break;
2335                         }
2336                         goto default_case;
2337                 case AST_DEVICE_UNKNOWN:
2338                         if (conditions & QUEUE_EMPTY_UNKNOWN) {
2339                                 ast_debug(4, "%s is unavailable because his device state is 'unknown'\n", member->membername);
2340                                 break;
2341                         }
2342                         /* Fall-through */
2343                 default:
2344                 default_case:
2345                         if (member->paused && (conditions & QUEUE_EMPTY_PAUSED)) {
2346                                 ast_debug(4, "%s is unavailable because he is paused'\n", member->membername);
2347                                 break;
2348                         } else if ((conditions & QUEUE_EMPTY_WRAPUP)
2349                                 && member->lastcall
2350                                 && get_wrapuptime(q, member)
2351                                 && (time(NULL) - get_wrapuptime(q, member) < member->lastcall)) {
2352                                 ast_debug(4, "%s is unavailable because it has only been %d seconds since his last call (wrapup time is %d)\n",
2353                                         member->membername, (int) (time(NULL) - member->lastcall), get_wrapuptime(q, member));
2354                                 break;
2355                         } else {
2356                                 ao2_ref(member, -1);
2357                                 ao2_iterator_destroy(&mem_iter);
2358                                 ao2_unlock(q);
2359                                 ast_debug(4, "%s is available.\n", member->membername);
2360                                 return 0;
2361                         }
2362                         break;
2363                 }
2364         }
2365         ao2_iterator_destroy(&mem_iter);
2366         ao2_unlock(q);
2367
2368         if (!devstate && (conditions & QUEUE_EMPTY_RINGING)) {
2369                 /* member state still may be RINGING due to lag in event message - check again with device state */
2370                 return get_member_status(q, max_penalty, min_penalty, raise_penalty, conditions, 1);
2371         }
2372         return -1;
2373 }
2374
2375 /*
2376  * A "pool" of member objects that calls are currently pending on. If an
2377  * agent is a member of multiple queues it's possible for that agent to be
2378  * called by each of the queues at the same time. This happens because device
2379  * state is slow to notify the queue app of one of it's member's being rung.
2380  * This "pool" allows us to track which members are currently being rung while
2381  * we wait on the device state change.
2382  */
2383 static struct ao2_container *pending_members;
2384 #define MAX_CALL_ATTEMPT_BUCKETS 353
2385
2386 static int pending_members_hash(const void *obj, const int flags)
2387 {
2388         const struct member *object;
2389         const char *key;
2390
2391         switch (flags & OBJ_SEARCH_MASK) {
2392         case OBJ_SEARCH_KEY:
2393                 key = obj;
2394                 break;
2395         case OBJ_SEARCH_OBJECT:
2396                 object = obj;
2397                 key = object->interface;
2398                 break;
2399         default:
2400                 ast_assert(0);
2401                 return 0;
2402         }
2403         return ast_str_case_hash(key);
2404 }
2405
2406 static int pending_members_cmp(void *obj, void *arg, int flags)
2407 {
2408         const struct member *object_left = obj;
2409         const struct member *object_right = arg;
2410         const char *right_key = arg;
2411         int cmp;
2412
2413         switch (flags & OBJ_SEARCH_MASK) {
2414         case OBJ_SEARCH_OBJECT:
2415                 right_key = object_right->interface;
2416                 /* Fall through */
2417         case OBJ_SEARCH_KEY:
2418                 cmp = strcasecmp(object_left->interface, right_key);
2419                 break;
2420         case OBJ_SEARCH_PARTIAL_KEY:
2421                 /* Not supported by container. */
2422                 ast_assert(0);
2423                 return 0;
2424         default:
2425                 cmp = 0;
2426                 break;
2427         }
2428         if (cmp) {
2429                 return 0;
2430         }
2431         return CMP_MATCH;
2432 }
2433
2434 static void pending_members_remove(struct member *mem)
2435 {
2436         ast_debug(3, "Removed %s from pending_members\n", mem->membername);
2437         ao2_find(pending_members, mem, OBJ_POINTER | OBJ_NODATA | OBJ_UNLINK);
2438 }
2439
2440 /*! \brief set a member's status based on device state of that member's state_interface.
2441  *
2442  * Lock interface list find sc, iterate through each queues queue_member list for member to
2443  * update state inside queues
2444 */
2445 static void update_status(struct call_queue *q, struct member *m, const int status)
2446 {
2447         if (m->status != status) {
2448                 /* If this member has transitioned to being available then update their queue
2449                  * information. If they are currently in a call then the leg to the agent will be
2450                  * considered done and the call finished.
2451                  */
2452                 if (status == AST_DEVICE_NOT_INUSE) {
2453                         update_queue(q, m, m->callcompletedinsl, m->starttime);
2454                 }
2455
2456                 m->status = status;
2457
2458                 /* Remove the member from the pending members pool only when the status changes.
2459                  * This is not done unconditionally because we can occasionally see multiple
2460                  * device state notifications of not in use after a previous call has ended,
2461                  * including after we have initiated a new call. This is more likely to
2462                  * happen when there is latency in the connection to the member.
2463                  */
2464                 pending_members_remove(m);
2465         }
2466
2467         queue_publish_member_blob(queue_member_status_type(), queue_member_blob_create(q, m));
2468 }
2469
2470 /*!
2471  * \internal
2472  * \brief Determine if a queue member is available
2473  * \retval 1 if the member is available
2474  * \retval 0 if the member is not available
2475  */
2476 static int is_member_available(struct call_queue *q, struct member *mem)
2477 {
2478         int available = 0;
2479         int wrapuptime;
2480
2481         switch (mem->status) {
2482                 case AST_DEVICE_INVALID:
2483                 case AST_DEVICE_UNAVAILABLE:
2484                         break;
2485                 case AST_DEVICE_INUSE:
2486                 case AST_DEVICE_BUSY:
2487                 case AST_DEVICE_RINGING:
2488                 case AST_DEVICE_RINGINUSE:
2489                 case AST_DEVICE_ONHOLD:
2490                         if (!mem->ringinuse) {
2491                                 break;
2492                         }
2493                         /* else fall through */
2494                 case AST_DEVICE_NOT_INUSE:
2495                 case AST_DEVICE_UNKNOWN:
2496                         if (!mem->paused) {
2497                                 available = 1;
2498                         }
2499                         break;
2500         }
2501
2502         /* Let wrapuptimes override device state availability */
2503         wrapuptime = get_wrapuptime(q, mem);
2504         if (mem->lastcall && wrapuptime && (time(NULL) - wrapuptime < mem->lastcall)) {
2505                 available = 0;
2506         }
2507         return available;
2508 }
2509
2510 /*! \brief set a member's status based on device state of that member's interface*/
2511 static void device_state_cb(void *unused, struct stasis_subscription *sub, struct stasis_message *msg)
2512 {
2513         struct ao2_iterator miter, qiter;
2514         struct ast_device_state_message *dev_state;
2515         struct member *m;
2516         struct call_queue *q;
2517         char interface[80], *slash_pos;
2518         int found = 0;                  /* Found this member in any queue */
2519         int found_member;               /* Found this member in this queue */
2520         int avail = 0;                  /* Found an available member in this queue */
2521
2522         if (ast_device_state_message_type() != stasis_message_type(msg)) {
2523                 return;
2524         }
2525
2526         dev_state = stasis_message_data(msg);
2527         if (dev_state->eid) {
2528                 /* ignore non-aggregate states */
2529                 return;
2530         }
2531
2532         qiter = ao2_iterator_init(queues, 0);
2533         while ((q = ao2_t_iterator_next(&qiter, "Iterate over queues"))) {
2534                 ao2_lock(q);
2535
2536                 avail = 0;
2537                 found_member = 0;
2538                 miter = ao2_iterator_init(q->members, 0);
2539                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
2540                         if (!found_member) {
2541                                 ast_copy_string(interface, m->state_interface, sizeof(interface));
2542
2543                                 if ((slash_pos = strchr(interface, '/'))) {
2544                                         if (!strncasecmp(interface, "Local/", 6) && (slash_pos = strchr(slash_pos + 1, '/'))) {
2545                                                 *slash_pos = '\0';
2546                                         }
2547                                 }
2548
2549                                 if (!strcasecmp(interface, dev_state->device)) {
2550                                         found_member = 1;
2551                                         update_status(q, m, dev_state->state);
2552                                 }
2553                         }
2554
2555                         /* check every member until we find one NOT_INUSE */
2556                         if (!avail) {
2557                                 avail = is_member_available(q, m);
2558                         }
2559                         if (avail && found_member) {
2560                                 /* early exit as we've found an available member and the member of interest */
2561                                 ao2_ref(m, -1);
2562                                 break;
2563                         }
2564                 }
2565
2566                 if (found_member) {
2567                         found = 1;
2568                         if (avail) {
2569                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2570                         } else {
2571                                 ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2572                         }
2573                 }
2574
2575                 ao2_iterator_destroy(&miter);
2576
2577                 ao2_unlock(q);
2578                 queue_t_unref(q, "Done with iterator");
2579         }
2580         ao2_iterator_destroy(&qiter);
2581
2582         if (found) {
2583                 ast_debug(1, "Device '%s' changed to state '%u' (%s)\n",
2584                         dev_state->device,
2585                         dev_state->state,
2586                         ast_devstate2str(dev_state->state));
2587         } else {
2588                 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",
2589                         dev_state->device,
2590                         dev_state->state,
2591                         ast_devstate2str(dev_state->state));
2592         }
2593
2594         return;
2595 }
2596
2597 /*! \brief Helper function which converts from extension state to device state values */
2598 static int extensionstate2devicestate(int state)
2599 {
2600         switch (state) {
2601         case AST_EXTENSION_NOT_INUSE:
2602                 state = AST_DEVICE_NOT_INUSE;
2603                 break;
2604         case AST_EXTENSION_INUSE:
2605                 state = AST_DEVICE_INUSE;
2606                 break;
2607         case AST_EXTENSION_BUSY:
2608                 state = AST_DEVICE_BUSY;
2609                 break;
2610         case AST_EXTENSION_RINGING:
2611                 state = AST_DEVICE_RINGING;
2612                 break;
2613         case AST_EXTENSION_ONHOLD:
2614                 state = AST_DEVICE_ONHOLD;
2615                 break;
2616         case AST_EXTENSION_UNAVAILABLE:
2617                 state = AST_DEVICE_UNAVAILABLE;
2618                 break;
2619         case AST_EXTENSION_REMOVED:
2620         case AST_EXTENSION_DEACTIVATED:
2621         default:
2622                 state = AST_DEVICE_INVALID;
2623                 break;
2624         }
2625
2626         return state;
2627 }
2628
2629 static int extension_state_cb(const char *context, const char *exten, struct ast_state_cb_info *info, void *data)
2630 {
2631         struct ao2_iterator miter, qiter;
2632         struct member *m;
2633         struct call_queue *q;
2634         int state = info->exten_state;
2635         int found = 0, device_state = extensionstate2devicestate(state);
2636
2637         /* only interested in extension state updates involving device states */
2638         if (info->reason != AST_HINT_UPDATE_DEVICE) {
2639                 return 0;
2640         }
2641
2642         qiter = ao2_iterator_init(queues, 0);
2643         while ((q = ao2_t_iterator_next(&qiter, "Iterate through queues"))) {
2644                 ao2_lock(q);
2645
2646                 miter = ao2_iterator_init(q->members, 0);
2647                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
2648                         if (!strcmp(m->state_context, context) && !strcmp(m->state_exten, exten)) {
2649                                 update_status(q, m, device_state);
2650                                 ao2_ref(m, -1);
2651                                 found = 1;
2652                                 break;
2653                         }
2654                 }
2655                 ao2_iterator_destroy(&miter);
2656
2657                 ao2_unlock(q);
2658                 queue_t_unref(q, "Done with iterator");
2659         }
2660         ao2_iterator_destroy(&qiter);
2661
2662         if (found) {
2663                 ast_debug(1, "Extension '%s@%s' changed to state '%d' (%s)\n", exten, context, device_state, ast_devstate2str(device_state));
2664         } else {
2665                 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",
2666                           exten, context, device_state, ast_devstate2str(device_state));
2667         }
2668
2669         return 0;
2670 }
2671
2672 /*! \brief Return the current state of a member */
2673 static int get_queue_member_status(struct member *cur)
2674 {
2675         return ast_strlen_zero(cur->state_exten) ? ast_device_state(cur->state_interface) : extensionstate2devicestate(ast_extension_state(NULL, cur->state_context, cur->state_exten));
2676 }
2677
2678 static void destroy_queue_member_cb(void *obj)
2679 {
2680         struct member *mem = obj;
2681
2682         if (mem->state_id != -1) {
2683                 ast_extension_state_del(mem->state_id, extension_state_cb);
2684         }
2685 }
2686
2687 /*! \brief allocate space for new queue member and set fields based on parameters passed */
2688 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused, const char *state_interface, int ringinuse, int wrapuptime)
2689 {
2690         struct member *cur;
2691
2692         if ((cur = ao2_alloc(sizeof(*cur), destroy_queue_member_cb))) {
2693                 cur->ringinuse = ringinuse;
2694                 cur->penalty = penalty;
2695                 cur->paused = paused;
2696                 cur->wrapuptime = wrapuptime;
2697                 if (paused) {
2698                         time(&cur->lastpause); /* Update time of last pause */
2699                 }
2700                 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
2701                 if (!ast_strlen_zero(state_interface)) {
2702                         ast_copy_string(cur->state_interface, state_interface, sizeof(cur->state_interface));
2703                 } else {
2704                         ast_copy_string(cur->state_interface, interface, sizeof(cur->state_interface));
2705                 }
2706                 if (!ast_strlen_zero(membername)) {
2707                         ast_copy_string(cur->membername, membername, sizeof(cur->membername));
2708                 } else {
2709                         ast_copy_string(cur->membername, interface, sizeof(cur->membername));
2710                 }
2711                 if (!strchr(cur->interface, '/')) {
2712                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
2713                 }
2714                 if (!strncmp(cur->state_interface, "hint:", 5)) {
2715                         char *tmp = ast_strdupa(cur->state_interface), *context = tmp;
2716                         char *exten = strsep(&context, "@") + 5;
2717
2718                         ast_copy_string(cur->state_exten, exten, sizeof(cur->state_exten));
2719                         ast_copy_string(cur->state_context, S_OR(context, "default"), sizeof(cur->state_context));
2720
2721                         cur->state_id = ast_extension_state_add(cur->state_context, cur->state_exten, extension_state_cb, NULL);
2722                 } else {
2723                         cur->state_id = -1;
2724                 }
2725                 cur->status = get_queue_member_status(cur);
2726         }
2727
2728         return cur;
2729 }
2730
2731
2732 static int compress_char(const char c)
2733 {
2734         if (c < 32) {
2735                 return 0;
2736         } else if (c > 96) {
2737                 return c - 64;
2738         }
2739         return c - 32;
2740 }
2741
2742 static int member_hash_fn(const void *obj, const int flags)
2743 {
2744         const struct member *mem = obj;
2745         const char *interface = (flags & OBJ_KEY) ? obj : mem->interface;
2746         const char *chname = strchr(interface, '/');
2747         int ret = 0, i;
2748
2749         if (!chname) {
2750                 chname = interface;
2751         }
2752         for (i = 0; i < 5 && chname[i]; i++) {
2753                 ret += compress_char(chname[i]) << (i * 6);
2754         }
2755         return ret;
2756 }
2757
2758 static int member_cmp_fn(void *obj1, void *obj2, int flags)
2759 {
2760         struct member *mem1 = obj1;
2761         struct member *mem2 = obj2;
2762         const char *interface = (flags & OBJ_KEY) ? obj2 : mem2->interface;
2763
2764         return strcasecmp(mem1->interface, interface) ? 0 : CMP_MATCH | CMP_STOP;
2765 }
2766
2767 /*!
2768  * \brief Initialize Queue default values.
2769  * \note the queue's lock  must be held before executing this function
2770 */
2771 static void init_queue(struct call_queue *q)
2772 {
2773         int i;
2774         struct penalty_rule *pr_iter;
2775
2776         q->dead = 0;
2777         q->retry = DEFAULT_RETRY;
2778         q->timeout = DEFAULT_TIMEOUT;
2779         q->maxlen = 0;
2780
2781         ast_string_field_set(q, context, "");
2782
2783         q->announcefrequency = 0;
2784         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
2785         q->announceholdtime = 1;
2786         q->announceposition_only_up = 0;
2787         q->announcepositionlimit = 10; /* Default 10 positions */
2788         q->announceposition = ANNOUNCEPOSITION_YES; /* Default yes */
2789         q->roundingseconds = 0; /* Default - don't announce seconds */
2790         q->servicelevel = 0;
2791         q->ringinuse = 1;
2792         q->announce_to_first_user = 0;
2793         q->setinterfacevar = 0;
2794         q->setqueuevar = 0;
2795         q->setqueueentryvar = 0;
2796         q->autofill = autofill_default;
2797         q->montype = montype_default;
2798         q->monfmt[0] = '\0';
2799         q->reportholdtime = 0;
2800         q->wrapuptime = 0;
2801         q->penaltymemberslimit = 0;
2802         q->joinempty = 0;
2803         q->leavewhenempty = 0;
2804         q->memberdelay = 0;
2805         q->weight = 0;
2806         q->timeoutrestart = 0;
2807         q->periodicannouncefrequency = 0;
2808         q->randomperiodicannounce = 0;
2809         q->numperiodicannounce = 0;
2810         q->autopause = QUEUE_AUTOPAUSE_OFF;
2811         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
2812         q->autopausedelay = 0;
2813         if (!q->members) {
2814                 if (q->strategy == QUEUE_STRATEGY_LINEAR || q->strategy == QUEUE_STRATEGY_RRORDERED) {
2815                         /* linear strategy depends on order, so we have to place all members in a list */
2816                         q->members = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, member_cmp_fn);
2817                 } else {
2818                         q->members = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 37,
2819                                 member_hash_fn, NULL, member_cmp_fn);
2820                 }
2821         }
2822         q->found = 1;
2823
2824         ast_string_field_set(q, moh, "");
2825         ast_string_field_set(q, sound_next, "queue-youarenext");
2826         ast_string_field_set(q, sound_thereare, "queue-thereare");
2827         ast_string_field_set(q, sound_calls, "queue-callswaiting");
2828         ast_string_field_set(q, queue_quantity1, "queue-quantity1");
2829         ast_string_field_set(q, queue_quantity2, "queue-quantity2");
2830         ast_string_field_set(q, sound_holdtime, "queue-holdtime");
2831         ast_string_field_set(q, sound_minutes, "queue-minutes");
2832         ast_string_field_set(q, sound_minute, "queue-minute");
2833         ast_string_field_set(q, sound_seconds, "queue-seconds");
2834         ast_string_field_set(q, sound_thanks, "queue-thankyou");
2835         ast_string_field_set(q, sound_reporthold, "queue-reporthold");
2836
2837         if (!q->sound_periodicannounce[0]) {
2838                 q->sound_periodicannounce[0] = ast_str_create(32);
2839         }
2840
2841         if (q->sound_periodicannounce[0]) {
2842                 ast_str_set(&q->sound_periodicannounce[0], 0, "queue-periodic-announce");
2843         }
2844
2845         for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
2846                 if (q->sound_periodicannounce[i]) {
2847                         ast_str_set(&q->sound_periodicannounce[i], 0, "%s", "");
2848                 }
2849         }
2850
2851         while ((pr_iter = AST_LIST_REMOVE_HEAD(&q->rules,list))) {
2852                 ast_free(pr_iter);
2853         }
2854
2855         /* On restart assume no members are available.
2856          * The queue_avail hint is a boolean state to indicate whether a member is available or not.
2857          *
2858          * This seems counter intuitive, but is required to light a BLF
2859          * AST_DEVICE_INUSE indicates no members are available.
2860          * AST_DEVICE_NOT_INUSE indicates a member is available.
2861          */
2862         ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Queue:%s_avail", q->name);
2863 }
2864
2865 static void clear_queue(struct call_queue *q)
2866 {
2867         q->holdtime = 0;
2868         q->callscompleted = 0;
2869         q->callsabandoned = 0;
2870         q->callscompletedinsl = 0;
2871         q->callsabandonedinsl = 0;
2872         q->talktime = 0;
2873
2874         if (q->members) {
2875                 struct member *mem;
2876                 struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
2877                 while ((mem = ao2_iterator_next(&mem_iter))) {
2878                         mem->calls = 0;
2879                         mem->callcompletedinsl = 0;
2880                         mem->lastcall = 0;
2881                         mem->starttime = 0;
2882                         ao2_ref(mem, -1);
2883                 }
2884                 ao2_iterator_destroy(&mem_iter);
2885         }
2886 }
2887
2888 /*!
2889  * \brief Change queue penalty by adding rule.
2890  *
2891  * Check rule for errors with time or fomatting, see if rule is relative to rest
2892  * of queue, iterate list of rules to find correct insertion point, insert and return.
2893  * \retval -1 on failure
2894  * \retval 0 on success
2895  * \note Call this with the rule_lists locked
2896 */
2897 static int insert_penaltychange(const char *list_name, const char *content, const int linenum)
2898 {
2899         char *timestr, *maxstr, *minstr, *raisestr, *contentdup;
2900         struct penalty_rule *rule = NULL, *rule_iter;
2901         struct rule_list *rl_iter;
2902         int penaltychangetime, inserted = 0;
2903
2904         if (!(rule = ast_calloc(1, sizeof(*rule)))) {
2905                 return -1;
2906         }
2907
2908         contentdup = ast_strdupa(content);
2909
2910         if (!(maxstr = strchr(contentdup, ','))) {
2911                 ast_log(LOG_WARNING, "Improperly formatted penaltychange rule at line %d. Ignoring.\n", linenum);
2912                 ast_free(rule);
2913                 return -1;
2914         }
2915
2916         *maxstr++ = '\0';
2917         if ((minstr = strchr(maxstr,','))) {
2918                 *minstr++ = '\0';
2919                 if ((raisestr = strchr(minstr,','))) {
2920                         *raisestr++ = '\0';
2921                 }
2922         } else {
2923                 raisestr = NULL;
2924         }
2925
2926         timestr = contentdup;
2927         if ((penaltychangetime = atoi(timestr)) < 0) {
2928                 ast_log(LOG_WARNING, "Improper time parameter specified for penaltychange rule at line %d. Ignoring.\n", linenum);
2929                 ast_free(rule);
2930                 return -1;
2931         }
2932
2933         rule->time = penaltychangetime;
2934
2935         /* The last check will evaluate true if either no penalty change is indicated for a given rule
2936          * OR if a min penalty change is indicated but no max penalty change is */
2937         if (*maxstr == '+' || *maxstr == '-' || *maxstr == '\0') {
2938                 rule->max_relative = 1;
2939         }
2940
2941         rule->max_value = atoi(maxstr);
2942
2943         if (!ast_strlen_zero(minstr)) {
2944                 if (*minstr == '+' || *minstr == '-') {
2945                         rule->min_relative = 1;
2946                 }
2947                 rule->min_value = atoi(minstr);
2948         } else { /*there was no minimum specified, so assume this means no change*/
2949                 rule->min_relative = 1;
2950         }
2951
2952         if (!ast_strlen_zero(raisestr)) {
2953                 if (*raisestr == '+' || *raisestr == '-') {
2954                         rule->raise_relative = 1;
2955                 }
2956                 rule->raise_value = atoi(raisestr);
2957         } else { /*there was no raise specified, so assume this means no change*/
2958                 rule->raise_relative = 1;
2959         }
2960
2961         /*We have the rule made, now we need to insert it where it belongs*/
2962         AST_LIST_TRAVERSE(&rule_lists, rl_iter, list){
2963                 if (strcasecmp(rl_iter->name, list_name)) {
2964                         continue;
2965                 }
2966
2967                 AST_LIST_TRAVERSE_SAFE_BEGIN(&rl_iter->rules, rule_iter, list) {
2968                         if (rule->time < rule_iter->time) {
2969                                 AST_LIST_INSERT_BEFORE_CURRENT(rule, list);
2970                                 inserted = 1;
2971                                 break;
2972                         }
2973                 }
2974                 AST_LIST_TRAVERSE_SAFE_END;
2975
2976                 if (!inserted) {
2977                         AST_LIST_INSERT_TAIL(&rl_iter->rules, rule, list);
2978                         inserted = 1;
2979                 }
2980
2981                 break;
2982         }
2983
2984         if (!inserted) {
2985                 ast_log(LOG_WARNING, "Unknown rule list name %s; ignoring.\n", list_name);
2986                 ast_free(rule);
2987                 return -1;
2988         }
2989         return 0;
2990 }
2991
2992 /*!
2993  * \brief Load queue rules from realtime.
2994  *
2995  * Check rule for errors with time or fomatting, see if rule is relative to rest
2996  * of queue, iterate list of rules to find correct insertion point, insert and return.
2997  * \retval -1 on failure
2998  * \retval 0 on success
2999  * \note Call this with the rule_lists locked
3000 */
3001 static int load_realtime_rules(void)
3002 {
3003         struct ast_config *cfg;
3004         struct rule_list *rl_iter, *new_rl;
3005         struct penalty_rule *pr_iter;
3006         char *rulecat = NULL;
3007
3008         if (!ast_check_realtime("queue_rules")) {
3009                 ast_log(LOG_WARNING, "Missing \"queue_rules\" in extconfig.conf\n");
3010                 return 0;
3011         }
3012         if (!(cfg = ast_load_realtime_multientry("queue_rules", "rule_name LIKE", "%", SENTINEL))) {
3013                 ast_log(LOG_WARNING, "Failed to load queue rules from realtime\n");
3014                 return 0;
3015         }
3016         while ((rulecat = ast_category_browse(cfg, rulecat))) {
3017                 const char *timestr, *maxstr, *minstr, *raisestr, *rule_name;
3018                 int penaltychangetime, rule_exists = 0, inserted = 0;
3019                 int max_penalty = 0, min_penalty = 0, raise_penalty = 0;
3020                 int min_relative = 0, max_relative = 0, raise_relative = 0;
3021                 struct penalty_rule *new_penalty_rule = NULL;
3022
3023                 rule_name = ast_variable_retrieve(cfg, rulecat, "rule_name");
3024                 if (ast_strlen_zero(rule_name)) {
3025                         continue;
3026                 }
3027
3028                 AST_LIST_TRAVERSE(&rule_lists, rl_iter, list) {
3029                         if (!(strcasecmp(rl_iter->name, rule_name))) {
3030                                 rule_exists = 1;
3031                                 new_rl = rl_iter;
3032                                 break;
3033                         }
3034                 }
3035                 if (!rule_exists) {
3036                         if (!(new_rl = ast_calloc(1, sizeof(*new_rl)))) {
3037                                 ast_config_destroy(cfg);
3038                                 return -1;
3039                         }
3040                         ast_copy_string(new_rl->name, rule_name, sizeof(new_rl->name));
3041                         AST_LIST_INSERT_TAIL(&rule_lists, new_rl, list);
3042                 }
3043                 timestr = ast_variable_retrieve(cfg, rulecat, "time");
3044                 if (!(timestr) || sscanf(timestr, "%30d", &penaltychangetime) != 1) {
3045                         ast_log(LOG_NOTICE, "Failed to parse time (%s) for one of the %s rules, skipping it\n",
3046                                 (ast_strlen_zero(timestr) ? "invalid value" : timestr), rule_name);
3047                         continue;
3048                 }
3049                 if (!(new_penalty_rule = ast_calloc(1, sizeof(*new_penalty_rule)))) {
3050                         ast_config_destroy(cfg);
3051                         return -1;
3052                 }
3053                 if (!(maxstr = ast_variable_retrieve(cfg, rulecat, "max_penalty")) ||
3054                         ast_strlen_zero(maxstr) || sscanf(maxstr, "%30d", &max_penalty) != 1) {
3055                         max_penalty = 0;
3056                         max_relative = 1;
3057                 } else {
3058                         if (*maxstr == '+' || *maxstr == '-') {
3059                                 max_relative = 1;
3060                         }
3061                 }
3062                 if (!(minstr = ast_variable_retrieve(cfg, rulecat, "min_penalty")) ||
3063                         ast_strlen_zero(minstr) || sscanf(minstr, "%30d", &min_penalty) != 1) {
3064                         min_penalty = 0;
3065                         min_relative = 1;
3066                 } else {
3067                         if (*minstr == '+' || *minstr == '-') {
3068                                 min_relative = 1;
3069                         }
3070                 }
3071                 if (!(raisestr = ast_variable_retrieve(cfg, rulecat, "raise_penalty")) ||
3072                         ast_strlen_zero(raisestr) || sscanf(raisestr, "%30d", &raise_penalty) != 1) {
3073                         raise_penalty = 0;
3074                         raise_relative = 1;
3075                 } else {
3076                         if (*raisestr == '+' || *raisestr == '-') {
3077                                 raise_relative = 1;
3078                         }
3079                 }
3080                 new_penalty_rule->time = penaltychangetime;
3081                 new_penalty_rule->max_relative = max_relative;
3082                 new_penalty_rule->max_value = max_penalty;
3083                 new_penalty_rule->min_relative = min_relative;
3084                 new_penalty_rule->min_value = min_penalty;
3085                 new_penalty_rule->raise_relative = raise_relative;
3086                 new_penalty_rule->raise_value = raise_penalty;
3087                 AST_LIST_TRAVERSE_SAFE_BEGIN(&new_rl->rules, pr_iter, list) {
3088                         if (new_penalty_rule->time < pr_iter->time) {
3089                                 AST_LIST_INSERT_BEFORE_CURRENT(new_penalty_rule, list);
3090                                 inserted = 1;
3091                         }
3092                 }
3093                 AST_LIST_TRAVERSE_SAFE_END;
3094                 if (!inserted) {
3095                         AST_LIST_INSERT_TAIL(&new_rl->rules, new_penalty_rule, list);
3096                 }
3097         }
3098
3099         ast_config_destroy(cfg);
3100         return 0;
3101 }
3102
3103 static void parse_empty_options(const char *value, enum empty_conditions *empty, int joinempty)
3104 {
3105         char *value_copy = ast_strdupa(value);
3106         char *option = NULL;
3107         while ((option = strsep(&value_copy, ","))) {
3108                 if (!strcasecmp(option, "paused")) {
3109                         *empty |= QUEUE_EMPTY_PAUSED;
3110                 } else if (!strcasecmp(option, "penalty")) {
3111                         *empty |= QUEUE_EMPTY_PENALTY;
3112                 } else if (!strcasecmp(option, "inuse")) {
3113                         *empty |= QUEUE_EMPTY_INUSE;
3114                 } else if (!strcasecmp(option, "ringing")) {
3115                         *empty |= QUEUE_EMPTY_RINGING;
3116                 } else if (!strcasecmp(option, "invalid")) {
3117                         *empty |= QUEUE_EMPTY_INVALID;
3118                 } else if (!strcasecmp(option, "wrapup")) {
3119                         *empty |= QUEUE_EMPTY_WRAPUP;
3120                 } else if (!strcasecmp(option, "unavailable")) {
3121                         *empty |= QUEUE_EMPTY_UNAVAILABLE;
3122                 } else if (!strcasecmp(option, "unknown")) {
3123                         *empty |= QUEUE_EMPTY_UNKNOWN;
3124                 } else if (!strcasecmp(option, "loose")) {
3125                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID);
3126                 } else if (!strcasecmp(option, "strict")) {
3127                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED | QUEUE_EMPTY_UNAVAILABLE);
3128                 } else if ((ast_false(option) && joinempty) || (ast_true(option) && !joinempty)) {
3129                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED);
3130                 } else if ((ast_false(option) && !joinempty) || (ast_true(option) && joinempty)) {
3131                         *empty = 0;
3132                 } else {
3133                         ast_log(LOG_WARNING, "Unknown option %s for '%s'\n", option, joinempty ? "joinempty" : "leavewhenempty");
3134                 }
3135         }
3136 }
3137
3138 /*! \brief Configure a queue parameter.
3139  *
3140  * The failunknown flag is set for config files (and static realtime) to show
3141  * errors for unknown parameters. It is cleared for dynamic realtime to allow
3142  *  extra fields in the tables.
3143  * \note For error reporting, line number is passed for .conf static configuration,
3144  * for Realtime queues, linenum is -1.
3145 */
3146 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
3147 {
3148         if (!strcasecmp(param, "musicclass") ||
3149                 !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
3150                 ast_string_field_set(q, moh, val);
3151         } else if (!strcasecmp(param, "announce")) {
3152                 ast_string_field_set(q, announce, val);
3153         } else if (!strcasecmp(param, "context")) {
3154                 ast_string_field_set(q, context, val);
3155         } else if (!strcasecmp(param, "timeout")) {
3156                 q->timeout = atoi(val);
3157                 if (q->timeout < 0) {
3158                         q->timeout = DEFAULT_TIMEOUT;
3159                 }
3160         } else if (!strcasecmp(param, "ringinuse")) {
3161                 q->ringinuse = ast_true(val);
3162         } else if (!strcasecmp(param, "setinterfacevar")) {
3163                 q->setinterfacevar = ast_true(val);
3164         } else if (!strcasecmp(param, "setqueuevar")) {
3165                 q->setqueuevar = ast_true(val);
3166         } else if (!strcasecmp(param, "setqueueentryvar")) {
3167                 q->setqueueentryvar = ast_true(val);
3168         } else if (!strcasecmp(param, "monitor-format")) {
3169                 ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
3170         } else if (!strcasecmp(param, "membermacro")) {
3171                 ast_string_field_set(q, membermacro, val);
3172         } else if (!strcasecmp(param, "membergosub")) {
3173                 ast_string_field_set(q, membergosub, val);
3174         } else if (!strcasecmp(param, "queue-youarenext")) {
3175                 ast_string_field_set(q, sound_next, val);
3176         } else if (!strcasecmp(param, "queue-thereare")) {
3177                 ast_string_field_set(q, sound_thereare, val);
3178         } else if (!strcasecmp(param, "queue-callswaiting")) {
3179                 ast_string_field_set(q, sound_calls, val);
3180         } else if (!strcasecmp(param, "queue-quantity1")) {
3181                 ast_string_field_set(q, queue_quantity1, val);
3182         } else if (!strcasecmp(param, "queue-quantity2")) {
3183                 ast_string_field_set(q, queue_quantity2, val);
3184         } else if (!strcasecmp(param, "queue-holdtime")) {
3185                 ast_string_field_set(q, sound_holdtime, val);
3186         } else if (!strcasecmp(param, "queue-minutes")) {
3187                 ast_string_field_set(q, sound_minutes, val);
3188         } else if (!strcasecmp(param, "queue-minute")) {
3189                 ast_string_field_set(q, sound_minute, val);
3190         } else if (!strcasecmp(param, "queue-seconds")) {
3191                 ast_string_field_set(q, sound_seconds, val);
3192         } else if (!strcasecmp(param, "queue-thankyou")) {
3193                 ast_string_field_set(q, sound_thanks, val);
3194         } else if (!strcasecmp(param, "queue-callerannounce")) {
3195                 ast_string_field_set(q, sound_callerannounce, val);
3196         } else if (!strcasecmp(param, "queue-reporthold")) {
3197                 ast_string_field_set(q, sound_reporthold, val);
3198         } else if (!strcasecmp(param, "announce-frequency")) {
3199                 q->announcefrequency = atoi(val);
3200         } else if (!strcasecmp(param, "announce-to-first-user")) {
3201                 q->announce_to_first_user = ast_true(val);
3202         } else if (!strcasecmp(param, "min-announce-frequency")) {
3203                 q->minannouncefrequency = atoi(val);
3204                 ast_debug(1, "%s=%s for queue '%s'\n", param, val, q->name);
3205         } else if (!strcasecmp(param, "announce-round-seconds")) {
3206                 q->roundingseconds = atoi(val);
3207                 /* Rounding to any other values just doesn't make sense... */
3208                 if (!(q->roundingseconds == 0 || q->roundingseconds == 5 || q->roundingseconds == 10
3209                         || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
3210                         if (linenum >= 0) {
3211                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
3212                                         "using 0 instead for queue '%s' at line %d of queues.conf\n",
3213                                         val, param, q->name, linenum);
3214                         } else {
3215                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
3216                                         "using 0 instead for queue '%s'\n", val, param, q->name);
3217                         }
3218                         q->roundingseconds=0;
3219                 }
3220         } else if (!strcasecmp(param, "announce-holdtime")) {
3221                 if (!strcasecmp(val, "once")) {
3222                         q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
3223                 } else if (ast_true(val)) {
3224                         q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
3225                 } else {
3226                         q->announceholdtime = 0;
3227                 }
3228         } else if (!strcasecmp(param, "announce-position")) {
3229                 if (!strcasecmp(val, "limit")) {
3230                         q->announceposition = ANNOUNCEPOSITION_LIMIT;
3231                 } else if (!strcasecmp(val, "more")) {
3232                         q->announceposition = ANNOUNCEPOSITION_MORE_THAN;
3233                 } else if (ast_true(val)) {
3234                         q->announceposition = ANNOUNCEPOSITION_YES;
3235                 } else {
3236                         q->announceposition = ANNOUNCEPOSITION_NO;
3237                 }
3238         } else if (!strcasecmp(param, "announce-position-only-up")) {
3239                 q->announceposition_only_up = ast_true(val);
3240         } else if (!strcasecmp(param, "announce-position-limit")) {
3241                 q->announcepositionlimit = atoi(val);
3242         } else if (!strcasecmp(param, "periodic-announce")) {
3243                 if (strchr(val, ',')) {
3244                         char *s, *buf = ast_strdupa(val);
3245                         unsigned int i = 0;
3246
3247                         while ((s = strsep(&buf, ",|"))) {
3248                                 if (!q->sound_periodicannounce[i]) {
3249                                         q->sound_periodicannounce[i] = ast_str_create(16);
3250                                 }
3251                                 ast_str_set(&q->sound_periodicannounce[i], 0, "%s", s);
3252                                 i++;
3253                                 if (i == MAX_PERIODIC_ANNOUNCEMENTS) {
3254                                         break;
3255                                 }
3256                         }
3257                         q->numperiodicannounce = i;
3258                 } else {
3259                         ast_str_set(&q->sound_periodicannounce[0], 0, "%s", val);
3260                         q->numperiodicannounce = 1;
3261                 }
3262         } else if (!strcasecmp(param, "periodic-announce-frequency")) {
3263                 q->periodicannouncefrequency = atoi(val);
3264         } else if (!strcasecmp(param, "relative-periodic-announce")) {
3265                 q->relativeperiodicannounce = ast_true(val);
3266         } else if (!strcasecmp(param, "random-periodic-announce")) {
3267                 q->randomperiodicannounce = ast_true(val);
3268         } else if (!strcasecmp(param, "retry")) {
3269                 q->retry = atoi(val);
3270                 if (q->retry <= 0) {
3271                         q->retry = DEFAULT_RETRY;
3272                 }
3273         } else if (!strcasecmp(param, "wrapuptime")) {
3274                 q->wrapuptime = atoi(val);
3275         } else if (!strcasecmp(param, "penaltymemberslimit")) {
3276                 if ((sscanf(val, "%10d", &q->penaltymemberslimit) != 1)) {
3277                         q->penaltymemberslimit = 0;
3278                 }
3279         } else if (!strcasecmp(param, "autofill")) {
3280                 q->autofill = ast_true(val);
3281         } else if (!strcasecmp(param, "monitor-type")) {
3282                 if (!strcasecmp(val, "mixmonitor")) {
3283                         q->montype = 1;
3284                 }
3285         } else if (!strcasecmp(param, "autopause")) {
3286                 q->autopause = autopause2int(val);
3287         } else if (!strcasecmp(param, "autopausedelay")) {
3288                 q->autopausedelay = atoi(val);
3289         } else if (!strcasecmp(param, "autopausebusy")) {
3290                 q->autopausebusy = ast_true(val);
3291         } else if (!strcasecmp(param, "autopauseunavail")) {
3292                 q->autopauseunavail = ast_true(val);
3293         } else if (!strcasecmp(param, "maxlen")) {
3294                 q->maxlen = atoi(val);
3295                 if (q->maxlen < 0) {
3296                         q->maxlen = 0;
3297                 }
3298         } else if (!strcasecmp(param, "servicelevel")) {
3299                 q->servicelevel= atoi(val);
3300         } else if (!strcasecmp(param, "strategy")) {
3301                 int strategy;
3302
3303                 /* We are a static queue and already have set this, no need to do it again */
3304                 if (failunknown) {
3305                         return;
3306                 }
3307                 strategy = strat2int(val);
3308                 if (strategy < 0) {
3309                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
3310                                 val, q->name);
3311                         q->strategy = QUEUE_STRATEGY_RINGALL;
3312                 }
3313                 if (strategy == q->strategy) {
3314                         return;
3315                 }
3316                 if (strategy == QUEUE_STRATEGY_LINEAR) {
3317                         ast_log(LOG_WARNING, "Changing to the linear strategy currently requires asterisk to be restarted.\n");
3318                         return;
3319                 }
3320                 q->strategy = strategy;
3321         } else if (!strcasecmp(param, "joinempty")) {
3322                 parse_empty_options(val, &q->joinempty, 1);
3323         } else if (!strcasecmp(param, "leavewhenempty")) {
3324                 parse_empty_options(val, &q->leavewhenempty, 0);
3325         } else if (!strcasecmp(param, "reportholdtime")) {
3326                 q->reportholdtime = ast_true(val);
3327         } else if (!strcasecmp(param, "memberdelay")) {
3328                 q->memberdelay = atoi(val);
3329         } else if (!strcasecmp(param, "weight")) {
3330                 q->weight = atoi(val);
3331         } else if (!strcasecmp(param, "timeoutrestart")) {
3332                 q->timeoutrestart = ast_true(val);
3333         } else if (!strcasecmp(param, "defaultrule")) {
3334                 ast_string_field_set(q, defaultrule, val);
3335         } else if (!strcasecmp(param, "timeoutpriority")) {
3336                 if (!strcasecmp(val, "conf")) {
3337                         q->timeoutpriority = TIMEOUT_PRIORITY_CONF;
3338                 } else {
3339                         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
3340                 }
3341         } else if (failunknown) {
3342                 if (linenum >= 0) {
3343                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
3344                                 q->name, param, linenum);
3345                 } else {
3346                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
3347                 }
3348         }
3349 }
3350
3351
3352 #define QUEUE_PAUSED_DEVSTATE AST_DEVICE_INUSE
3353 #define QUEUE_UNPAUSED_DEVSTATE AST_DEVICE_NOT_INUSE
3354 #define QUEUE_UNKNOWN_PAUSED_DEVSTATE AST_DEVICE_NOT_INUSE
3355
3356 /*! \internal
3357  * \brief If adding a single new member to a queue, use this function instead of ao2_linking.
3358  *        This adds round robin queue position data for a fresh member as well as links it.
3359  * \param queue Which queue the member is being added to
3360  * \param mem Which member is being added to the queue
3361  */
3362 static void member_add_to_queue(struct call_queue *queue, struct member *mem)
3363 {
3364         ao2_lock(queue->members);
3365         mem->queuepos = ao2_container_count(queue->members);
3366         ao2_link(queue->members, mem);
3367         ast_devstate_changed(mem->paused ? QUEUE_PAUSED_DEVSTATE : QUEUE_UNPAUSED_DEVSTATE,
3368                 AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", queue->name, mem->interface);
3369         ao2_unlock(queue->members);
3370 }
3371
3372 /*! \internal
3373  * \brief If removing a single member from a queue, use this function instead of ao2_unlinking.
3374  *        This will perform round robin queue position reordering for the remaining members.
3375  * \param queue Which queue the member is being removed from
3376  * \param member Which member is being removed from the queue
3377  */
3378 static void member_remove_from_queue(struct call_queue *queue, struct member *mem)
3379 {
3380         pending_members_remove(mem);
3381         ao2_lock(queue->members);
3382         ast_devstate_changed(QUEUE_UNKNOWN_PAUSED_DEVSTATE, AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", queue->name, mem->interface);
3383         queue_member_follower_removal(queue, mem);
3384         ao2_unlink(queue->members, mem);
3385         ao2_unlock(queue->members);
3386 }
3387
3388 /*!
3389  * \brief Find rt member record to update otherwise create one.
3390  *
3391  * Search for member in queue, if found update penalty/paused state,
3392  * if no member exists create one flag it as a RT member and add to queue member list.
3393 */
3394 static void rt_handle_member_record(struct call_queue *q, char *category, struct ast_config *member_config)
3395 {
3396         struct member *m;
3397         struct ao2_iterator mem_iter;
3398         int penalty = 0;
3399         int paused  = 0;
3400         int found = 0;
3401         int wrapuptime = 0;
3402         int ringinuse = q->ringinuse;
3403
3404         const char *config_val;
3405         const char *interface = ast_variable_retrieve(member_config, category, "interface");
3406         const char *rt_uniqueid = ast_variable_retrieve(member_config, category, "uniqueid");
3407         const char *membername = S_OR(ast_variable_retrieve(member_config, category, "membername"), interface);
3408         const char *state_interface = S_OR(ast_variable_retrieve(member_config, category, "state_interface"), interface);
3409         const char *penalty_str = ast_variable_retrieve(member_config, category, "penalty");
3410         const char *paused_str = ast_variable_retrieve(member_config, category, "paused");
3411         const char *wrapuptime_str = ast_variable_retrieve(member_config, category, "wrapuptime");
3412
3413         if (ast_strlen_zero(rt_uniqueid)) {
3414                 ast_log(LOG_WARNING, "Realtime field 'uniqueid' is empty for member %s\n",
3415                         S_OR(membername, "NULL"));
3416                 return;
3417         }
3418
3419         if (ast_strlen_zero(interface)) {
3420                 ast_log(LOG_WARNING, "Realtime field 'interface' is empty for member %s\n",
3421                         S_OR(membername, "NULL"));
3422                 return;
3423         }
3424
3425         if (penalty_str) {
3426                 penalty = atoi(penalty_str);
3427                 if ((penalty < 0) && negative_penalty_invalid) {
3428                         return;
3429                 } else if (penalty < 0) {
3430                         penalty = 0;
3431                 }
3432         }
3433
3434         if (paused_str) {
3435                 paused = atoi(paused_str);
3436                 if (paused < 0) {
3437                         paused = 0;
3438                 }
3439         }
3440
3441         if (wrapuptime_str) {
3442                 wrapuptime = atoi(wrapuptime_str);
3443                 if (wrapuptime < 0) {
3444                         wrapuptime = 0;
3445                 }
3446         }
3447
3448         if ((config_val = ast_variable_retrieve(member_config, category, realtime_ringinuse_field))) {
3449                 if (ast_true(config_val)) {
3450                         ringinuse = 1;
3451                 } else if (ast_false(config_val)) {
3452                         ringinuse = 0;
3453                 } else {
3454                         ast_log(LOG_WARNING, "Invalid value of '%s' field for %s in queue '%s'\n", realtime_ringinuse_field, interface, q->name);
3455                 }
3456         }
3457
3458         /* Find member by realtime uniqueid and update */
3459         mem_iter = ao2_iterator_init(q->members, 0);
3460         while ((m = ao2_iterator_next(&mem_iter))) {
3461                 if (!strcasecmp(m->rt_uniqueid, rt_uniqueid)) {
3462                         m->dead = 0;    /* Do not delete this one. */
3463                         ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
3464                         if (paused_str) {
3465                                 m->paused = paused;
3466                                 if (paused) {
3467                                         time(&m->lastpause); /* XXX: Should this come from realtime? */
3468                                 }
3469                                 ast_devstate_changed(m->paused ? QUEUE_PAUSED_DEVSTATE : QUEUE_UNPAUSED_DEVSTATE,
3470                                         AST_DEVSTATE_CACHABLE, "Queue:%s_pause_%s", q->name, m->interface);
3471                         }
3472                         if (strcasecmp(state_interface, m->state_interface)) {
3473                                 ast_copy_string(m->state_interface, state_interface, sizeof(m->state_interface));
3474                         }
3475                         m->penalty = penalty;
3476                         m->ringinuse = ringinuse;
3477                         m->wrapuptime = wrapuptime;
3478                         found = 1;
3479                         ao2_ref(m, -1);
3480                         break;
3481                 }
3482                 ao2_ref(m, -1);
3483         }
3484         ao2_iterator_destroy(&mem_iter);
3485
3486         /* Create a new member */
3487         if (!found) {
3488                 if ((m = create_queue_member(interface, membername, penalty, paused, state_interface, ringinuse, wrapuptime))) {
3489                         m->dead = 0;
3490                         m->realtime = 1;
3491                         ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
3492                         if (!log_membername_as_agent) {
3493                                 ast_queue_log(q->name, "REALTIME", m->interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
3494                         } else {
3495                                 ast_queue_log(q->name, "REALTIME", m->membername, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
3496                         }
3497                         member_add_to_queue(q, m);
3498                         ao2_ref(m, -1);
3499                         m = NULL;
3500                 }
3501         }
3502 }
3503
3504 /*! \brief Iterate through queue's member list and delete them */
3505 static void free_members(struct call_queue *q, int all)
3506 {
3507         /* Free non-dynamic members */
3508         struct member *cur;
3509         struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
3510
3511         while ((cur = ao2_iterator_next(&mem_iter))) {
3512                 if (all || !cur->dynamic) {
3513                         member_remove_from_queue(q, cur);
3514                 }
3515                 ao2_ref(cur, -1);
3516         }
3517         ao2_iterator_destroy(&mem_iter);
3518 }
3519
3520 /*! \brief Free queue's member list then its string fields */
3521 static void destroy_queue(void *obj)
3522 {
3523         struct call_queue *q = obj;
3524         int i;
3525
3526         free_members(q, 1);
3527         ast_string_field_free_memory(q);
3528         for (i = 0; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
3529                 if (q->sound_periodicannounce[i]) {
3530                         ast_free(q->sound_periodicannounce[i]);
3531                 }
3532         }
3533         ao2_ref(q->members, -1);
3534 }
3535
3536 static struct call_queue *alloc_queue(const char *queuename)
3537 {
3538         struct call_queue *q;
3539
3540         if ((q = ao2_t_alloc(sizeof(*q), destroy_queue, "Allocate queue"))) {
3541                 if (ast_string_field_init(q, 64)) {
3542                         queue_t_unref(q, "String field allocation failed");
3543                         return NULL;
3544                 }
3545                 ast_string_field_set(q, name, queuename);
3546         }
3547         return q;
3548 }
3549
3550 /*!
3551  * \brief Reload a single queue via realtime.
3552  *
3553  * Check for statically defined queue first, check if deleted RT queue,
3554  * check for new RT queue, if queue vars are not defined init them with defaults.
3555  * reload RT queue vars, set RT queue members dead and reload them, return finished queue.
3556  * \retval the queue,
3557  * \retval NULL if it doesn't exist.
3558  * \note Should be called with the "queues" container locked.
3559 */
3560 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
3561 {
3562         struct ast_variable *v;
3563         struct call_queue *q, tmpq = {
3564                 .name = queuename,
3565         };
3566         struct member *m;
3567         struct ao2_iterator mem_iter;
3568         char *category = NULL;
3569         const char *tmp_name;
3570         char *tmp;
3571         char tmpbuf[64];        /* Must be longer than the longest queue param name. */
3572
3573         /* Static queues override realtime. */
3574         if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Check if static queue exists"))) {
3575                 ao2_lock(q);
3576                 if (!q->realtime) {
3577                         if (q->dead) {
3578                                 ao2_unlock(q);
3579                                 queue_t_unref(q, "Queue is dead; can't return it");
3580                                 return NULL;
3581                         }
3582                         ast_log(LOG_WARNING, "Static queue '%s' already exists. Not loading from realtime\n", q->name);
3583                         ao2_unlock(q);
3584                         return q;
3585                 }
3586         } else if (!member_config) {
3587                 /* Not found in the list, and it's not realtime ... */
3588                 return NULL;
3589         }
3590         /* Check if queue is defined in realtime. */
3591         if (!queue_vars) {
3592                 /* Delete queue from in-core list if it has been deleted in realtime. */
3593                 if (q) {
3594                         /*! \note Hmm, can't seem to distinguish a DB failure from a not
3595                            found condition... So we might delete an in-core queue
3596                            in case of DB failure. */
3597                         ast_debug(1, "Queue %s not found in realtime.\n", queuename);
3598
3599                         q->dead = 1;
3600                         /* Delete if unused (else will be deleted when last caller leaves). */
3601                         queues_t_unlink(queues, q, "Unused; removing from container");
3602                         ao2_unlock(q);
3603                         queue_t_unref(q, "Queue is dead; can't return it");
3604                 }
3605                 return NULL;
3606         }
3607
3608         /* Create a new queue if an in-core entry does not exist yet. */
3609         if (!q) {
3610                 struct ast_variable *tmpvar = NULL;
3611                 if (!(q = alloc_queue(queuename))) {
3612                         return NULL;
3613                 }
3614                 ao2_lock(q);
3615                 clear_queue(q);
3616                 q->realtime = 1;
3617                 /*Before we initialize the queue, we need to set the strategy, so that linear strategy
3618                  * will allocate the members properly
3619                  */
3620                 for (tmpvar = queue_vars; tmpvar; tmpvar = tmpvar->next) {
3621                         if (!strcasecmp(tmpvar->name, "strategy")) {
3622                                 q->strategy = strat2int(tmpvar->value);
3623                                 if (q->strategy < 0) {
3624                                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
3625                                         tmpvar->value, q->name);
3626                                         q->strategy = QUEUE_STRATEGY_RINGALL;
3627                                 }
3628                     &n