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