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