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