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