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