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