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