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