app_queue: Made pass connected line updates from the caller to ringing queue members.
[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 /*! 
58  * \li The application app_queues uses configuration file \ref queues.conf
59  * \addtogroup configuration_file
60  */
61
62 /*! \page queues.conf queues.conf
63  * \verbinclude queues.conf.sample
64  */
65
66 /*** MODULEINFO
67         <use type="module">res_monitor</use>
68         <support_level>core</support_level>
69  ***/
70
71 #include "asterisk.h"
72
73 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
74
75 #include <sys/time.h>
76 #include <sys/signal.h>
77 #include <netinet/in.h>
78 #include <ctype.h>
79
80 #include "asterisk/lock.h"
81 #include "asterisk/file.h"
82 #include "asterisk/channel.h"
83 #include "asterisk/pbx.h"
84 #include "asterisk/app.h"
85 #include "asterisk/linkedlists.h"
86 #include "asterisk/module.h"
87 #include "asterisk/translate.h"
88 #include "asterisk/say.h"
89 #include "asterisk/features.h"
90 #include "asterisk/musiconhold.h"
91 #include "asterisk/cli.h"
92 #include "asterisk/manager.h"
93 #include "asterisk/config.h"
94 #include "asterisk/monitor.h"
95 #include "asterisk/utils.h"
96 #include "asterisk/causes.h"
97 #include "asterisk/astdb.h"
98 #include "asterisk/devicestate.h"
99 #include "asterisk/stringfields.h"
100 #include "asterisk/event.h"
101 #include "asterisk/astobj2.h"
102 #include "asterisk/strings.h"
103 #include "asterisk/global_datastores.h"
104 #include "asterisk/taskprocessor.h"
105 #include "asterisk/aoc.h"
106 #include "asterisk/callerid.h"
107 #include "asterisk/cel.h"
108 #include "asterisk/data.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
994 static struct ast_taskprocessor *devicestate_tps;
995
996 #define DEFAULT_RETRY           5
997 #define DEFAULT_TIMEOUT         15
998 #define RECHECK                 1               /*!< Recheck every second to see we we're at the top yet */
999 #define MAX_PERIODIC_ANNOUNCEMENTS 10           /*!< The maximum periodic announcements we can have */
1000 #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15       /*!< The minimum number of seconds between position announcements \
1001                                                      The default value of 15 provides backwards compatibility */
1002 #define MAX_QUEUE_BUCKETS 53
1003
1004 #define RES_OKAY        0               /*!< Action completed */
1005 #define RES_EXISTS      (-1)            /*!< Entry already exists */
1006 #define RES_OUTOFMEMORY (-2)            /*!< Out of memory */
1007 #define RES_NOSUCHQUEUE (-3)            /*!< No such queue */
1008 #define RES_NOT_DYNAMIC (-4)            /*!< Member is not dynamic */
1009
1010 static char *app = "Queue";
1011
1012 static char *app_aqm = "AddQueueMember" ;
1013
1014 static char *app_rqm = "RemoveQueueMember" ;
1015
1016 static char *app_pqm = "PauseQueueMember" ;
1017
1018 static char *app_upqm = "UnpauseQueueMember" ;
1019
1020 static char *app_ql = "QueueLog" ;
1021
1022 /*! \brief Persistent Members astdb family */
1023 static const char * const pm_family = "Queue/PersistentMembers";
1024
1025 /*! \brief queues.conf [general] option */
1026 static int queue_persistent_members = 0;
1027
1028 /*! \brief queues.conf per-queue weight option */
1029 static int use_weight = 0;
1030
1031 /*! \brief queues.conf [general] option */
1032 static int autofill_default = 1;
1033
1034 /*! \brief queues.conf [general] option */
1035 static int montype_default = 0;
1036
1037 /*! \brief queues.conf [general] option */
1038 static int shared_lastcall = 1;
1039
1040 /*! \brief Subscription to device state change events */
1041 static struct ast_event_sub *device_state_sub;
1042
1043 /*! \brief queues.conf [general] option */
1044 static int update_cdr = 0;
1045
1046 /*! \brief queues.conf [general] option */
1047 static int negative_penalty_invalid = 0;
1048
1049 /*! \brief queues.conf [general] option */
1050 static int log_membername_as_agent = 0;
1051
1052 /*! \brief queues.conf [general] option */
1053 static int check_state_unknown = 0;
1054
1055 /*! \brief name of the ringinuse field in the realtime database */
1056 static char *realtime_ringinuse_field;
1057
1058 enum queue_result {
1059         QUEUE_UNKNOWN = 0,
1060         QUEUE_TIMEOUT = 1,
1061         QUEUE_JOINEMPTY = 2,
1062         QUEUE_LEAVEEMPTY = 3,
1063         QUEUE_JOINUNAVAIL = 4,
1064         QUEUE_LEAVEUNAVAIL = 5,
1065         QUEUE_FULL = 6,
1066         QUEUE_CONTINUE = 7,
1067 };
1068
1069 static const struct {
1070         enum queue_result id;
1071         char *text;
1072 } queue_results[] = {
1073         { QUEUE_UNKNOWN, "UNKNOWN" },
1074         { QUEUE_TIMEOUT, "TIMEOUT" },
1075         { QUEUE_JOINEMPTY,"JOINEMPTY" },
1076         { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
1077         { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
1078         { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
1079         { QUEUE_FULL, "FULL" },
1080         { QUEUE_CONTINUE, "CONTINUE" },
1081 };
1082
1083 enum queue_timeout_priority {
1084         TIMEOUT_PRIORITY_APP,
1085         TIMEOUT_PRIORITY_CONF,
1086 };
1087
1088 /*! \brief We define a custom "local user" structure because we
1089  *  use it not only for keeping track of what is in use but
1090  *  also for keeping track of who we're dialing.
1091  *
1092  *  There are two "links" defined in this structure, q_next and call_next.
1093  *  q_next links ALL defined callattempt structures into a linked list. call_next is
1094  *  a link which allows for a subset of the callattempts to be traversed. This subset
1095  *  is used in wait_for_answer so that irrelevant callattempts are not traversed. This
1096  *  also is helpful so that queue logs are always accurate in the case where a call to 
1097  *  a member times out, especially if using the ringall strategy. 
1098 */
1099
1100 struct callattempt {
1101         struct callattempt *q_next;
1102         struct callattempt *call_next;
1103         struct ast_channel *chan;
1104         char interface[256];                    /*!< An Asterisk dial string (not a channel name) */
1105         int metric;
1106         time_t lastcall;
1107         struct call_queue *lastqueue;
1108         struct member *member;
1109         /*! Saved connected party info from an AST_CONTROL_CONNECTED_LINE. */
1110         struct ast_party_connected_line connected;
1111         /*! TRUE if an AST_CONTROL_CONNECTED_LINE update was saved to the connected element. */
1112         unsigned int pending_connected_update:1;
1113         /*! TRUE if the connected line update is blocked. */
1114         unsigned int block_connected_update:1;
1115         /*! TRUE if caller id is not available for connected line */
1116         unsigned int dial_callerid_absent:1;
1117         /*! TRUE if the call is still active */
1118         unsigned int stillgoing:1;
1119         struct ast_aoc_decoded *aoc_s_rate_list;
1120 };
1121
1122
1123 struct queue_ent {
1124         struct call_queue *parent;             /*!< What queue is our parent */
1125         char moh[MAX_MUSICCLASS];              /*!< Name of musiconhold to be used */
1126         char announce[PATH_MAX];               /*!< Announcement to play for member when call is answered */
1127         char context[AST_MAX_CONTEXT];         /*!< Context when user exits queue */
1128         char digits[AST_MAX_EXTENSION];        /*!< Digits entered while in queue */
1129         int valid_digits;                      /*!< Digits entered correspond to valid extension. Exited */
1130         int pos;                               /*!< Where we are in the queue */
1131         int prio;                              /*!< Our priority */
1132         int last_pos_said;                     /*!< Last position we told the user */
1133         int ring_when_ringing;                 /*!< Should we only use ring indication when a channel is ringing? */
1134         time_t last_periodic_announce_time;    /*!< The last time we played a periodic announcement */
1135         int last_periodic_announce_sound;      /*!< The last periodic announcement we made */
1136         time_t last_pos;                       /*!< Last time we told the user their position */
1137         int opos;                              /*!< Where we started in the queue */
1138         int handled;                           /*!< Whether our call was handled */
1139         int pending;                           /*!< Non-zero if we are attempting to call a member */
1140         int max_penalty;                       /*!< Limit the members that can take this call to this penalty or lower */
1141         int min_penalty;                       /*!< Limit the members that can take this call to this penalty or higher */
1142         int linpos;                            /*!< If using linear strategy, what position are we at? */
1143         int linwrapped;                        /*!< Is the linpos wrapped? */
1144         time_t start;                          /*!< When we started holding */
1145         time_t expire;                         /*!< When this entry should expire (time out of queue) */
1146         int cancel_answered_elsewhere;         /*!< Whether we should force the CAE flag on this call (C) option*/
1147         struct ast_channel *chan;              /*!< Our channel */
1148         AST_LIST_HEAD_NOLOCK(,penalty_rule) qe_rules; /*!< Local copy of the queue's penalty rules */
1149         struct penalty_rule *pr;               /*!< Pointer to the next penalty rule to implement */
1150         struct queue_ent *next;                /*!< The next queue entry */
1151 };
1152
1153 struct member {
1154         char interface[AST_CHANNEL_NAME];    /*!< Technology/Location to dial to reach this member*/
1155         char state_exten[AST_MAX_EXTENSION]; /*!< Extension to get state from (if using hint) */
1156         char state_context[AST_MAX_CONTEXT]; /*!< Context to use when getting state (if using hint) */
1157         char state_interface[AST_CHANNEL_NAME]; /*!< Technology/Location from which to read devicestate changes */
1158         char membername[80];                 /*!< Member name to use in queue logs */
1159         int penalty;                         /*!< Are we a last resort? */
1160         int calls;                           /*!< Number of calls serviced by this member */
1161         int dynamic;                         /*!< Are we dynamically added? */
1162         int realtime;                        /*!< Is this member realtime? */
1163         int status;                          /*!< Status of queue member */
1164         int paused;                          /*!< Are we paused (not accepting calls)? */
1165         time_t lastcall;                     /*!< When last successful call was hungup */
1166         struct call_queue *lastqueue;        /*!< Last queue we received a call */
1167         unsigned int dead:1;                 /*!< Used to detect members deleted in realtime */
1168         unsigned int delme:1;                /*!< Flag to delete entry on reload */
1169         char rt_uniqueid[80];                /*!< Unique id of realtime member entry */
1170         unsigned int ringinuse:1;            /*!< Flag to ring queue members even if their status is 'inuse' */
1171 };
1172
1173 enum empty_conditions {
1174         QUEUE_EMPTY_PENALTY = (1 << 0),
1175         QUEUE_EMPTY_PAUSED = (1 << 1),
1176         QUEUE_EMPTY_INUSE = (1 << 2),
1177         QUEUE_EMPTY_RINGING = (1 << 3),
1178         QUEUE_EMPTY_UNAVAILABLE = (1 << 4),
1179         QUEUE_EMPTY_INVALID = (1 << 5),
1180         QUEUE_EMPTY_UNKNOWN = (1 << 6),
1181         QUEUE_EMPTY_WRAPUP = (1 << 7),
1182 };
1183
1184 enum member_properties {
1185         MEMBER_PENALTY = 0,
1186         MEMBER_RINGINUSE = 1,
1187 };
1188
1189 /* values used in multi-bit flags in call_queue */
1190 #define ANNOUNCEHOLDTIME_ALWAYS 1
1191 #define ANNOUNCEHOLDTIME_ONCE 2
1192 #define QUEUE_EVENT_VARIABLES 3
1193
1194 struct penalty_rule {
1195         int time;                           /*!< Number of seconds that need to pass before applying this rule */
1196         int max_value;                      /*!< The amount specified in the penalty rule for max penalty */
1197         int min_value;                      /*!< The amount specified in the penalty rule for min penalty */
1198         int max_relative;                   /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
1199         int min_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
1200         AST_LIST_ENTRY(penalty_rule) list;  /*!< Next penalty_rule */
1201 };
1202
1203 #define ANNOUNCEPOSITION_YES 1 /*!< We announce position */
1204 #define ANNOUNCEPOSITION_NO 2 /*!< We don't announce position */
1205 #define ANNOUNCEPOSITION_MORE_THAN 3 /*!< We say "Currently there are more than <limit>" */
1206 #define ANNOUNCEPOSITION_LIMIT 4 /*!< We not announce position more than <limit> */
1207
1208 struct call_queue {
1209         AST_DECLARE_STRING_FIELDS(
1210                 /*! Queue name */
1211                 AST_STRING_FIELD(name);
1212                 /*! Music on Hold class */
1213                 AST_STRING_FIELD(moh);
1214                 /*! Announcement to play when call is answered */
1215                 AST_STRING_FIELD(announce);
1216                 /*! Exit context */
1217                 AST_STRING_FIELD(context);
1218                 /*! Macro to run upon member connection */
1219                 AST_STRING_FIELD(membermacro);
1220                 /*! Gosub to run upon member connection */
1221                 AST_STRING_FIELD(membergosub);
1222                 /*! Default rule to use if none specified in call to Queue() */
1223                 AST_STRING_FIELD(defaultrule);
1224                 /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
1225                 AST_STRING_FIELD(sound_next);
1226                 /*! Sound file: "There are currently" (def. queue-thereare) */
1227                 AST_STRING_FIELD(sound_thereare);
1228                 /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
1229                 AST_STRING_FIELD(sound_calls);
1230                 /*! Sound file: "Currently there are more than" (def. queue-quantity1) */
1231                 AST_STRING_FIELD(queue_quantity1);
1232                 /*! Sound file: "callers waiting to speak with a representative" (def. queue-quantity2) */
1233                 AST_STRING_FIELD(queue_quantity2);
1234                 /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
1235                 AST_STRING_FIELD(sound_holdtime);
1236                 /*! Sound file: "minutes." (def. queue-minutes) */
1237                 AST_STRING_FIELD(sound_minutes);
1238                 /*! Sound file: "minute." (def. queue-minute) */
1239                 AST_STRING_FIELD(sound_minute);
1240                 /*! Sound file: "seconds." (def. queue-seconds) */
1241                 AST_STRING_FIELD(sound_seconds);
1242                 /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
1243                 AST_STRING_FIELD(sound_thanks);
1244                 /*! Sound file: Custom announce for caller, no default */
1245                 AST_STRING_FIELD(sound_callerannounce);
1246                 /*! Sound file: "Hold time" (def. queue-reporthold) */
1247                 AST_STRING_FIELD(sound_reporthold);
1248         );
1249         /*! Sound files: Custom announce, no default */
1250         struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
1251         unsigned int dead:1;
1252         unsigned int eventwhencalled:2;
1253         unsigned int ringinuse:1;
1254         unsigned int setinterfacevar:1;
1255         unsigned int setqueuevar:1;
1256         unsigned int setqueueentryvar:1;
1257         unsigned int reportholdtime:1;
1258         unsigned int wrapped:1;
1259         unsigned int timeoutrestart:1;
1260         unsigned int announceholdtime:2;
1261         unsigned int announceposition:3;
1262         int strategy:4;
1263         unsigned int maskmemberstatus:1;
1264         unsigned int realtime:1;
1265         unsigned int found:1;
1266         unsigned int relativeperiodicannounce:1;
1267         unsigned int autopausebusy:1;
1268         unsigned int autopauseunavail:1;
1269         enum empty_conditions joinempty;
1270         enum empty_conditions leavewhenempty;
1271         int announcepositionlimit;          /*!< How many positions we announce? */
1272         int announcefrequency;              /*!< How often to announce their position */
1273         int minannouncefrequency;           /*!< The minimum number of seconds between position announcements (def. 15) */
1274         int periodicannouncefrequency;      /*!< How often to play periodic announcement */
1275         int numperiodicannounce;            /*!< The number of periodic announcements configured */
1276         int randomperiodicannounce;         /*!< Are periodic announcments randomly chosen */
1277         int roundingseconds;                /*!< How many seconds do we round to? */
1278         int holdtime;                       /*!< Current avg holdtime, based on an exponential average */
1279         int talktime;                       /*!< Current avg talktime, based on the same exponential average */
1280         int callscompleted;                 /*!< Number of queue calls completed */
1281         int callsabandoned;                 /*!< Number of queue calls abandoned */
1282         int servicelevel;                   /*!< seconds setting for servicelevel*/
1283         int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
1284         char monfmt[8];                     /*!< Format to use when recording calls */
1285         int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
1286         int count;                          /*!< How many entries */
1287         int maxlen;                         /*!< Max number of entries */
1288         int wrapuptime;                     /*!< Wrapup Time */
1289         int penaltymemberslimit;            /*!< Disregard penalty when queue has fewer than this many members */
1290
1291         int retry;                          /*!< Retry calling everyone after this amount of time */
1292         int timeout;                        /*!< How long to wait for an answer */
1293         int weight;                         /*!< Respective weight */
1294         int autopause;                      /*!< Auto pause queue members if they fail to answer */
1295         int autopausedelay;                 /*!< Delay auto pause for autopausedelay seconds since last call */
1296         int timeoutpriority;                /*!< Do we allow a fraction of the timeout to occur for a ring? */
1297
1298         /* Queue strategy things */
1299         int rrpos;                          /*!< Round Robin - position */
1300         int memberdelay;                    /*!< Seconds to delay connecting member to caller */
1301         int autofill;                       /*!< Ignore the head call status and ring an available agent */
1302         
1303         struct ao2_container *members;             /*!< Head of the list of members */
1304         struct queue_ent *head;             /*!< Head of the list of callers */
1305         AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
1306         AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
1307 };
1308
1309 struct rule_list {
1310         char name[80];
1311         AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
1312         AST_LIST_ENTRY(rule_list) list;
1313 };
1314
1315 static AST_LIST_HEAD_STATIC(rule_lists, rule_list);
1316
1317 static struct ao2_container *queues;
1318
1319 static void update_realtime_members(struct call_queue *q);
1320 static struct member *interface_exists(struct call_queue *q, const char *interface);
1321 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
1322
1323 static void queue_transfer_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan);
1324
1325 static struct member *find_member_by_queuename_and_interface(const char *queuename, const char *interface);
1326 /*! \brief sets the QUEUESTATUS channel variable */
1327 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
1328 {
1329         int i;
1330
1331         for (i = 0; i < ARRAY_LEN(queue_results); i++) {
1332                 if (queue_results[i].id == res) {
1333                         pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
1334                         return;
1335                 }
1336         }
1337 }
1338
1339 static const char *int2strat(int strategy)
1340 {
1341         int x;
1342
1343         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1344                 if (strategy == strategies[x].strategy) {
1345                         return strategies[x].name;
1346                 }
1347         }
1348
1349         return "<unknown>";
1350 }
1351
1352 static int strat2int(const char *strategy)
1353 {
1354         int x;
1355
1356         for (x = 0; x < ARRAY_LEN(strategies); x++) {
1357                 if (!strcasecmp(strategy, strategies[x].name)) {
1358                         return strategies[x].strategy;
1359                 }
1360         }
1361
1362         return -1;
1363 }
1364
1365 static int autopause2int(const char *autopause)
1366 {
1367         int x;
1368         /*This 'double check' that default value is OFF */
1369         if (ast_strlen_zero(autopause)) {
1370                 return QUEUE_AUTOPAUSE_OFF;
1371         }
1372
1373         /*This 'double check' is to ensure old values works */
1374         if(ast_true(autopause)) {
1375                 return QUEUE_AUTOPAUSE_ON;
1376         }
1377
1378         for (x = 0; x < ARRAY_LEN(autopausesmodes); x++) {
1379                 if (!strcasecmp(autopause, autopausesmodes[x].name)) {
1380                         return autopausesmodes[x].autopause;
1381                 }
1382         }
1383
1384         /*This 'double check' that default value is OFF */
1385         return QUEUE_AUTOPAUSE_OFF;
1386 }
1387
1388 static int queue_hash_cb(const void *obj, const int flags)
1389 {
1390         const struct call_queue *q = obj;
1391
1392         return ast_str_case_hash(q->name);
1393 }
1394
1395 static int queue_cmp_cb(void *obj, void *arg, int flags)
1396 {
1397         struct call_queue *q = obj, *q2 = arg;
1398         return !strcasecmp(q->name, q2->name) ? CMP_MATCH | CMP_STOP : 0;
1399 }
1400
1401 #ifdef REF_DEBUG_ONLY_QUEUES
1402 #define queue_ref(q)                            _queue_ref(q, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1403 #define queue_unref(q)                          _queue_unref(q, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1404 #define queue_t_ref(q, tag)                     _queue_ref(q, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1405 #define queue_t_unref(q, tag)           _queue_unref(q, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1406 #define queues_t_link(c, q, tag)        __ao2_link_debug(c, q, 0, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1407 #define queues_t_unlink(c, q, tag)      __ao2_unlink_debug(c, q, 0, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1408
1409 static inline struct call_queue *_queue_ref(struct call_queue *q, const char *tag, const char *file, int line, const char *filename)
1410 {
1411         __ao2_ref_debug(q, 1, tag, file, line, filename);
1412         return q;
1413 }
1414
1415 static inline struct call_queue *_queue_unref(struct call_queue *q, const char *tag, const char *file, int line, const char *filename)
1416 {
1417         __ao2_ref_debug(q, -1, tag, file, line, filename);
1418         return NULL;
1419 }
1420
1421 #else
1422
1423 #define queue_t_ref(q, tag)                     queue_ref(q)
1424 #define queue_t_unref(q, tag)           queue_unref(q)
1425 #define queues_t_link(c, q, tag)        ao2_t_link(c, q, tag)
1426 #define queues_t_unlink(c, q, tag)      ao2_t_unlink(c, q, tag)
1427
1428 static inline struct call_queue *queue_ref(struct call_queue *q)
1429 {
1430         ao2_ref(q, 1);
1431         return q;
1432 }
1433
1434 static inline struct call_queue *queue_unref(struct call_queue *q)
1435 {
1436         ao2_ref(q, -1);
1437         return NULL;
1438 }
1439 #endif
1440
1441 /*! \brief Set variables of queue */
1442 static void set_queue_variables(struct call_queue *q, struct ast_channel *chan)
1443 {
1444         char interfacevar[256]="";
1445         float sl = 0;
1446
1447         ao2_lock(q);
1448
1449         if (q->setqueuevar) {
1450                 sl = 0;
1451                 if (q->callscompleted > 0) {
1452                         sl = 100 * ((float) q->callscompletedinsl / (float) q->callscompleted);
1453                 }
1454
1455                 snprintf(interfacevar, sizeof(interfacevar),
1456                         "QUEUENAME=%s,QUEUEMAX=%d,QUEUESTRATEGY=%s,QUEUECALLS=%d,QUEUEHOLDTIME=%d,QUEUETALKTIME=%d,QUEUECOMPLETED=%d,QUEUEABANDONED=%d,QUEUESRVLEVEL=%d,QUEUESRVLEVELPERF=%2.1f",
1457                         q->name, q->maxlen, int2strat(q->strategy), q->count, q->holdtime, q->talktime, q->callscompleted, q->callsabandoned,  q->servicelevel, sl);
1458
1459                 ao2_unlock(q);
1460         
1461                 pbx_builtin_setvar_multiple(chan, interfacevar); 
1462         } else {
1463                 ao2_unlock(q);
1464         }
1465 }
1466
1467 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
1468 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
1469 {
1470         struct queue_ent *cur;
1471
1472         if (!q || !new)
1473                 return;
1474         if (prev) {
1475                 cur = prev->next;
1476                 prev->next = new;
1477         } else {
1478                 cur = q->head;
1479                 q->head = new;
1480         }
1481         new->next = cur;
1482
1483         /* every queue_ent must have a reference to it's parent call_queue, this
1484          * reference does not go away until the end of the queue_ent's life, meaning
1485          * that even when the queue_ent leaves the call_queue this ref must remain. */
1486         queue_ref(q);
1487         new->parent = q;
1488         new->pos = ++(*pos);
1489         new->opos = *pos;
1490 }
1491
1492 /*! \brief Check if members are available
1493  *
1494  * This function checks to see if members are available to be called. If any member
1495  * is available, the function immediately returns 0. If no members are available,
1496  * then -1 is returned.
1497  */
1498 static int get_member_status(struct call_queue *q, int max_penalty, int min_penalty, enum empty_conditions conditions)
1499 {
1500         struct member *member;
1501         struct ao2_iterator mem_iter;
1502
1503         ao2_lock(q);
1504         mem_iter = ao2_iterator_init(q->members, 0);
1505         for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
1506                 if ((max_penalty && (member->penalty > max_penalty)) || (min_penalty && (member->penalty < min_penalty))) {
1507                         if (conditions & QUEUE_EMPTY_PENALTY) {
1508                                 ast_debug(4, "%s is unavailable because his penalty is not between %d and %d\n", member->membername, min_penalty, max_penalty);
1509                                 continue;
1510                         }
1511                 }
1512
1513                 switch (member->status) {
1514                 case AST_DEVICE_INVALID:
1515                         if (conditions & QUEUE_EMPTY_INVALID) {
1516                                 ast_debug(4, "%s is unavailable because his device state is 'invalid'\n", member->membername);
1517                                 break;
1518                         }
1519                         goto default_case;
1520                 case AST_DEVICE_UNAVAILABLE:
1521                         if (conditions & QUEUE_EMPTY_UNAVAILABLE) {
1522                                 ast_debug(4, "%s is unavailable because his device state is 'unavailable'\n", member->membername);
1523                                 break;
1524                         }
1525                         goto default_case;
1526                 case AST_DEVICE_INUSE:
1527                         if (conditions & QUEUE_EMPTY_INUSE) {
1528                                 ast_debug(4, "%s is unavailable because his device state is 'inuse'\n", member->membername);
1529                                 break;
1530                         }
1531                         goto default_case;
1532                 case AST_DEVICE_RINGING:
1533                         if (conditions & QUEUE_EMPTY_RINGING) {
1534                                 ast_debug(4, "%s is unavailable because his device state is 'ringing'\n", member->membername);
1535                                 break;
1536                         }
1537                         goto default_case;
1538                 case AST_DEVICE_UNKNOWN:
1539                         if (conditions & QUEUE_EMPTY_UNKNOWN) {
1540                                 ast_debug(4, "%s is unavailable because his device state is 'unknown'\n", member->membername);
1541                                 break;
1542                         }
1543                         /* Fall-through */
1544                 default:
1545                 default_case:
1546                         if (member->paused && (conditions & QUEUE_EMPTY_PAUSED)) {
1547                                 ast_debug(4, "%s is unavailable because he is paused'\n", member->membername);
1548                                 break;
1549                         } else if ((conditions & QUEUE_EMPTY_WRAPUP) && member->lastcall && q->wrapuptime && (time(NULL) - q->wrapuptime < member->lastcall)) {
1550                                 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);
1551                                 break;
1552                         } else {
1553                                 ao2_ref(member, -1);
1554                                 ao2_iterator_destroy(&mem_iter);
1555                                 ao2_unlock(q);
1556                                 ast_debug(4, "%s is available.\n", member->membername);
1557                                 return 0;
1558                         }
1559                         break;
1560                 }
1561         }
1562         ao2_iterator_destroy(&mem_iter);
1563
1564         ao2_unlock(q);
1565         return -1;
1566 }
1567
1568 struct statechange {
1569         AST_LIST_ENTRY(statechange) entry;
1570         int state;
1571         char dev[0];
1572 };
1573
1574 /*! \brief set a member's status based on device state of that member's state_interface.
1575  *
1576  * Lock interface list find sc, iterate through each queues queue_member list for member to
1577  * update state inside queues
1578 */
1579 static int update_status(struct call_queue *q, struct member *m, const int status)
1580 {
1581         m->status = status;
1582
1583         if (q->maskmemberstatus) {
1584                 return 0;
1585         }
1586
1587         /*** DOCUMENTATION
1588         <managerEventInstance>
1589                 <synopsis>Raised when a Queue member's status has changed.</synopsis>
1590                 <syntax>
1591                         <parameter name="Queue">
1592                                 <para>The name of the queue.</para>
1593                         </parameter>
1594                         <parameter name="Location">
1595                                 <para>The queue member's channel technology or location.</para>
1596                         </parameter>
1597                         <parameter name="MemberName">
1598                                 <para>The name of the queue member.</para>
1599                         </parameter>
1600                         <parameter name="StateInterface">
1601                                 <para>Channel technology or location from which to read device state changes.</para>
1602                         </parameter>
1603                         <parameter name="Membership">
1604                                 <enumlist>
1605                                         <enum name="dynamic"/>
1606                                         <enum name="realtime"/>
1607                                         <enum name="static"/>
1608                                 </enumlist>
1609                         </parameter>
1610                         <parameter name="Penalty">
1611                                 <para>The penalty associated with the queue member.</para>
1612                         </parameter>
1613                         <parameter name="CallsTaken">
1614                                 <para>The number of calls this queue member has serviced.</para>
1615                         </parameter>
1616                         <parameter name="LastCall">
1617                                 <para>The time this member last took call, expressed in seconds since 00:00, Jan 1, 1970 UTC.</para>
1618                         </parameter>
1619                         <parameter name="Status">
1620                                 <para>The numeric device state status of the queue member.</para>
1621                                 <enumlist>
1622                                         <enum name="0"><para>AST_DEVICE_UNKNOWN</para></enum>
1623                                         <enum name="1"><para>AST_DEVICE_NOT_INUSE</para></enum>
1624                                         <enum name="2"><para>AST_DEVICE_INUSE</para></enum>
1625                                         <enum name="3"><para>AST_DEVICE_BUSY</para></enum>
1626                                         <enum name="4"><para>AST_DEVICE_INVALID</para></enum>
1627                                         <enum name="5"><para>AST_DEVICE_UNAVAILABLE</para></enum>
1628                                         <enum name="6"><para>AST_DEVICE_RINGING</para></enum>
1629                                         <enum name="7"><para>AST_DEVICE_RINGINUSE</para></enum>
1630                                         <enum name="8"><para>AST_DEVICE_ONHOLD</para></enum>
1631                                 </enumlist>
1632                         </parameter>
1633                         <parameter name="Paused">
1634                                 <enumlist>
1635                                         <enum name="0"/>
1636                                         <enum name="1"/>
1637                                 </enumlist>
1638                         </parameter>
1639                 </syntax>
1640         </managerEventInstance>
1641         ***/
1642         manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
1643                 "Queue: %s\r\n"
1644                 "Location: %s\r\n"
1645                 "MemberName: %s\r\n"
1646                 "StateInterface: %s\r\n"
1647                 "Membership: %s\r\n"
1648                 "Penalty: %d\r\n"
1649                 "CallsTaken: %d\r\n"
1650                 "LastCall: %d\r\n"
1651                 "Status: %d\r\n"
1652                 "Paused: %d\r\n",
1653                 q->name, m->interface, m->membername, m->state_interface, m->dynamic ? "dynamic" : m->realtime ? "realtime" : "static",
1654                 m->penalty, m->calls, (int)m->lastcall, m->status, m->paused
1655         );
1656
1657         return 0;
1658 }
1659
1660 /*!
1661  * \internal \brief Determine if a queue member is available
1662  * \retval 1 if the member is available
1663  * \retval 0 if the member is not available
1664  */
1665 static int is_member_available(struct member *mem)
1666 {
1667         int available = 0;
1668
1669         switch (mem->status) {
1670                 case AST_DEVICE_INVALID:
1671                 case AST_DEVICE_UNAVAILABLE:
1672                         break;
1673                 case AST_DEVICE_INUSE:
1674                 case AST_DEVICE_BUSY:
1675                 case AST_DEVICE_RINGING:
1676                 case AST_DEVICE_RINGINUSE:
1677                 case AST_DEVICE_ONHOLD:
1678                         if (!mem->ringinuse) {
1679                                 break;
1680                         }
1681                         /* else fall through */
1682                 case AST_DEVICE_NOT_INUSE:
1683                 case AST_DEVICE_UNKNOWN:
1684                         if (!mem->paused) {
1685                                 available = 1;
1686                         }
1687                         break;
1688         }
1689
1690         return available;
1691 }
1692
1693 /*! \brief set a member's status based on device state of that member's interface*/
1694 static int handle_statechange(void *datap)
1695 {
1696         struct statechange *sc = datap;
1697         struct ao2_iterator miter, qiter;
1698         struct member *m;
1699         struct call_queue *q;
1700         char interface[80], *slash_pos;
1701         int found = 0;                  /* Found this member in any queue */
1702         int found_member;               /* Found this member in this queue */
1703         int avail = 0;                  /* Found an available member in this queue */
1704
1705         qiter = ao2_iterator_init(queues, 0);
1706         while ((q = ao2_t_iterator_next(&qiter, "Iterate over queues"))) {
1707                 ao2_lock(q);
1708
1709                 avail = 0;
1710                 found_member = 0;
1711                 miter = ao2_iterator_init(q->members, 0);
1712                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
1713                         if (!found_member) {
1714                                 ast_copy_string(interface, m->state_interface, sizeof(interface));
1715
1716                                 if ((slash_pos = strchr(interface, '/'))) {
1717                                         if (!strncasecmp(interface, "Local/", 6) && (slash_pos = strchr(slash_pos + 1, '/'))) {
1718                                                 *slash_pos = '\0';
1719                                         }
1720                                 }
1721
1722                                 if (!strcasecmp(interface, sc->dev)) {
1723                                         found_member = 1;
1724                                         update_status(q, m, sc->state);
1725                                 }
1726                         }
1727
1728                         /* check every member until we find one NOT_INUSE */
1729                         if (!avail) {
1730                                 avail = is_member_available(m);
1731                         }
1732                         if (avail && found_member) {
1733                                 /* early exit as we've found an available member and the member of interest */
1734                                 ao2_ref(m, -1);
1735                                 break;
1736                         }
1737                 }
1738
1739                 if (found_member) {
1740                         found = 1;
1741                         if (avail) {
1742                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Queue:%s_avail", q->name);
1743                         } else {
1744                                 ast_devstate_changed(AST_DEVICE_INUSE, "Queue:%s_avail", q->name);
1745                         }
1746                 }
1747
1748                 ao2_iterator_destroy(&miter);
1749
1750                 ao2_unlock(q);
1751                 queue_t_unref(q, "Done with iterator");
1752         }
1753         ao2_iterator_destroy(&qiter);
1754
1755         if (found) {
1756                 ast_debug(1, "Device '%s' changed to state '%d' (%s)\n", sc->dev, sc->state, ast_devstate2str(sc->state));
1757         } else {
1758                 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", sc->dev, sc->state, ast_devstate2str(sc->state));
1759         }
1760
1761         ast_free(sc);
1762         return 0;
1763 }
1764
1765 static void device_state_cb(const struct ast_event *event, void *unused)
1766 {
1767         enum ast_device_state state;
1768         const char *device;
1769         struct statechange *sc;
1770         size_t datapsize;
1771
1772         state = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
1773         device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
1774
1775         if (ast_strlen_zero(device)) {
1776                 ast_log(LOG_ERROR, "Received invalid event that had no device IE\n");
1777                 return;
1778         }
1779         datapsize = sizeof(*sc) + strlen(device) + 1;
1780         if (!(sc = ast_calloc(1, datapsize))) {
1781                 ast_log(LOG_ERROR, "failed to calloc a state change struct\n");
1782                 return;
1783         }
1784         sc->state = state;
1785         strcpy(sc->dev, device);
1786         if (ast_taskprocessor_push(devicestate_tps, handle_statechange, sc) < 0) {
1787                 ast_free(sc);
1788         }
1789 }
1790
1791 /*! \brief Helper function which converts from extension state to device state values */
1792 static int extensionstate2devicestate(int state)
1793 {
1794         switch (state) {
1795         case AST_EXTENSION_NOT_INUSE:
1796                 state = AST_DEVICE_NOT_INUSE;
1797                 break;
1798         case AST_EXTENSION_INUSE:
1799                 state = AST_DEVICE_INUSE;
1800                 break;
1801         case AST_EXTENSION_BUSY:
1802                 state = AST_DEVICE_BUSY;
1803                 break;
1804         case AST_EXTENSION_RINGING:
1805                 state = AST_DEVICE_RINGING;
1806                 break;
1807         case AST_EXTENSION_ONHOLD:
1808                 state = AST_DEVICE_ONHOLD;
1809                 break;
1810         case AST_EXTENSION_UNAVAILABLE:
1811                 state = AST_DEVICE_UNAVAILABLE;
1812                 break;
1813         case AST_EXTENSION_REMOVED:
1814         case AST_EXTENSION_DEACTIVATED:
1815         default:
1816                 state = AST_DEVICE_INVALID;
1817                 break;
1818         }
1819
1820         return state;
1821 }
1822
1823 static int extension_state_cb(char *context, char *exten, struct ast_state_cb_info *info, void *data)
1824 {
1825         struct ao2_iterator miter, qiter;
1826         struct member *m;
1827         struct call_queue *q;
1828         int state = info->exten_state;
1829         int found = 0, device_state = extensionstate2devicestate(state);
1830
1831         /* only interested in extension state updates involving device states */
1832         if (info->reason != AST_HINT_UPDATE_DEVICE) {
1833                 return 0;
1834         }
1835
1836         qiter = ao2_iterator_init(queues, 0);
1837         while ((q = ao2_t_iterator_next(&qiter, "Iterate through queues"))) {
1838                 ao2_lock(q);
1839
1840                 miter = ao2_iterator_init(q->members, 0);
1841                 for (; (m = ao2_iterator_next(&miter)); ao2_ref(m, -1)) {
1842                         if (!strcmp(m->state_context, context) && !strcmp(m->state_exten, exten)) {
1843                                 update_status(q, m, device_state);
1844                                 ao2_ref(m, -1);
1845                                 found = 1;
1846                                 break;
1847                         }
1848                 }
1849                 ao2_iterator_destroy(&miter);
1850
1851                 ao2_unlock(q);
1852                 queue_t_unref(q, "Done with iterator");
1853         }
1854         ao2_iterator_destroy(&qiter);
1855
1856         if (found) {
1857                 ast_debug(1, "Extension '%s@%s' changed to state '%d' (%s)\n", exten, context, device_state, ast_devstate2str(device_state));
1858         } else {
1859                 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",
1860                           exten, context, device_state, ast_devstate2str(device_state));
1861         }
1862
1863         return 0;
1864 }
1865
1866 /*! \brief Return the current state of a member */
1867 static int get_queue_member_status(struct member *cur)
1868 {
1869         return ast_strlen_zero(cur->state_exten) ? ast_device_state(cur->state_interface) : extensionstate2devicestate(ast_extension_state(NULL, cur->state_context, cur->state_exten));
1870 }
1871
1872 /*! \brief allocate space for new queue member and set fields based on parameters passed */
1873 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused, const char *state_interface, int ringinuse)
1874 {
1875         struct member *cur;
1876
1877         if ((cur = ao2_alloc(sizeof(*cur), NULL))) {
1878                 cur->ringinuse = ringinuse;
1879                 cur->penalty = penalty;
1880                 cur->paused = paused;
1881                 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
1882                 if (!ast_strlen_zero(state_interface)) {
1883                         ast_copy_string(cur->state_interface, state_interface, sizeof(cur->state_interface));
1884                 } else {
1885                         ast_copy_string(cur->state_interface, interface, sizeof(cur->state_interface));
1886                 }
1887                 if (!ast_strlen_zero(membername)) {
1888                         ast_copy_string(cur->membername, membername, sizeof(cur->membername));
1889                 } else {
1890                         ast_copy_string(cur->membername, interface, sizeof(cur->membername));
1891                 }
1892                 if (!strchr(cur->interface, '/')) {
1893                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
1894                 }
1895                 if (!strncmp(cur->state_interface, "hint:", 5)) {
1896                         char *tmp = ast_strdupa(cur->state_interface), *context = tmp;
1897                         char *exten = strsep(&context, "@") + 5;
1898
1899                         ast_copy_string(cur->state_exten, exten, sizeof(cur->state_exten));
1900                         ast_copy_string(cur->state_context, S_OR(context, "default"), sizeof(cur->state_context));
1901                 }
1902                 cur->status = get_queue_member_status(cur);
1903         }
1904
1905         return cur;
1906 }
1907
1908
1909 static int compress_char(const char c)
1910 {
1911         if (c < 32) {
1912                 return 0;
1913         } else if (c > 96) {
1914                 return c - 64;
1915         } 
1916         return c - 32;
1917 }
1918
1919 static int member_hash_fn(const void *obj, const int flags)
1920 {
1921         const struct member *mem = obj;
1922         const char *interface = (flags & OBJ_KEY) ? obj : mem->interface;
1923         const char *chname = strchr(interface, '/');
1924         int ret = 0, i;
1925
1926         if (!chname) {
1927                 chname = interface;
1928         }
1929         for (i = 0; i < 5 && chname[i]; i++) {
1930                 ret += compress_char(chname[i]) << (i * 6);
1931         }
1932         return ret;
1933 }
1934
1935 static int member_cmp_fn(void *obj1, void *obj2, int flags)
1936 {
1937         struct member *mem1 = obj1;
1938         struct member *mem2 = obj2;
1939         const char *interface = (flags & OBJ_KEY) ? obj2 : mem2->interface;
1940
1941         return strcasecmp(mem1->interface, interface) ? 0 : CMP_MATCH | CMP_STOP;
1942 }
1943
1944 /*!
1945  * \brief Initialize Queue default values.
1946  * \note the queue's lock  must be held before executing this function
1947 */
1948 static void init_queue(struct call_queue *q)
1949 {
1950         int i;
1951         struct penalty_rule *pr_iter;
1952
1953         q->dead = 0;
1954         q->retry = DEFAULT_RETRY;
1955         q->timeout = DEFAULT_TIMEOUT;
1956         q->maxlen = 0;
1957         q->announcefrequency = 0;
1958         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
1959         q->announceholdtime = 1;
1960         q->announcepositionlimit = 10; /* Default 10 positions */
1961         q->announceposition = ANNOUNCEPOSITION_YES; /* Default yes */
1962         q->roundingseconds = 0; /* Default - don't announce seconds */
1963         q->servicelevel = 0;
1964         q->ringinuse = 1;
1965         q->setinterfacevar = 0;
1966         q->setqueuevar = 0;
1967         q->setqueueentryvar = 0;
1968         q->autofill = autofill_default;
1969         q->montype = montype_default;
1970         q->monfmt[0] = '\0';
1971         q->reportholdtime = 0;
1972         q->wrapuptime = 0;
1973         q->penaltymemberslimit = 0;
1974         q->joinempty = 0;
1975         q->leavewhenempty = 0;
1976         q->memberdelay = 0;
1977         q->maskmemberstatus = 0;
1978         q->eventwhencalled = 0;
1979         q->weight = 0;
1980         q->timeoutrestart = 0;
1981         q->periodicannouncefrequency = 0;
1982         q->randomperiodicannounce = 0;
1983         q->numperiodicannounce = 0;
1984         q->autopause = QUEUE_AUTOPAUSE_OFF;
1985         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
1986         q->autopausedelay = 0;
1987         if (!q->members) {
1988                 if (q->strategy == QUEUE_STRATEGY_LINEAR || q->strategy == QUEUE_STRATEGY_RRORDERED) {
1989                         /* linear strategy depends on order, so we have to place all members in a single bucket */
1990                         q->members = ao2_container_alloc(1, member_hash_fn, member_cmp_fn);
1991                 } else {
1992                         q->members = ao2_container_alloc(37, member_hash_fn, member_cmp_fn);
1993                 }
1994         }
1995         q->found = 1;
1996
1997         ast_string_field_set(q, sound_next, "queue-youarenext");
1998         ast_string_field_set(q, sound_thereare, "queue-thereare");
1999         ast_string_field_set(q, sound_calls, "queue-callswaiting");
2000         ast_string_field_set(q, queue_quantity1, "queue-quantity1");
2001         ast_string_field_set(q, queue_quantity2, "queue-quantity2");
2002         ast_string_field_set(q, sound_holdtime, "queue-holdtime");
2003         ast_string_field_set(q, sound_minutes, "queue-minutes");
2004         ast_string_field_set(q, sound_minute, "queue-minute");
2005         ast_string_field_set(q, sound_seconds, "queue-seconds");
2006         ast_string_field_set(q, sound_thanks, "queue-thankyou");
2007         ast_string_field_set(q, sound_reporthold, "queue-reporthold");
2008
2009         if (!q->sound_periodicannounce[0]) {
2010                 q->sound_periodicannounce[0] = ast_str_create(32);
2011         }
2012
2013         if (q->sound_periodicannounce[0]) {
2014                 ast_str_set(&q->sound_periodicannounce[0], 0, "queue-periodic-announce");
2015         }
2016
2017         for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
2018                 if (q->sound_periodicannounce[i]) {
2019                         ast_str_set(&q->sound_periodicannounce[i], 0, "%s", "");
2020                 }
2021         }
2022
2023         while ((pr_iter = AST_LIST_REMOVE_HEAD(&q->rules,list))) {
2024                 ast_free(pr_iter);
2025         }
2026
2027         /* On restart assume no members are available.
2028          * The queue_avail hint is a boolean state to indicate whether a member is available or not.
2029          *
2030          * This seems counter intuitive, but is required to light a BLF
2031          * AST_DEVICE_INUSE indicates no members are available.
2032          * AST_DEVICE_NOT_INUSE indicates a member is available.
2033          */
2034         ast_devstate_changed(AST_DEVICE_INUSE, "Queue:%s_avail", q->name);
2035 }
2036
2037 static void clear_queue(struct call_queue *q)
2038 {
2039         q->holdtime = 0;
2040         q->callscompleted = 0;
2041         q->callsabandoned = 0;
2042         q->callscompletedinsl = 0;
2043         q->talktime = 0;
2044
2045         if (q->members) {
2046                 struct member *mem;
2047                 struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
2048                 while ((mem = ao2_iterator_next(&mem_iter))) {
2049                         mem->calls = 0;
2050                         mem->lastcall = 0;
2051                         ao2_ref(mem, -1);
2052                 }
2053                 ao2_iterator_destroy(&mem_iter);
2054         }
2055 }
2056
2057 /*!
2058  * \brief Change queue penalty by adding rule.
2059  *
2060  * Check rule for errors with time or fomatting, see if rule is relative to rest
2061  * of queue, iterate list of rules to find correct insertion point, insert and return.
2062  * \retval -1 on failure
2063  * \retval 0 on success
2064  * \note Call this with the rule_lists locked
2065 */
2066 static int insert_penaltychange(const char *list_name, const char *content, const int linenum)
2067 {
2068         char *timestr, *maxstr, *minstr, *contentdup;
2069         struct penalty_rule *rule = NULL, *rule_iter;
2070         struct rule_list *rl_iter;
2071         int penaltychangetime, inserted = 0;
2072
2073         if (!(rule = ast_calloc(1, sizeof(*rule)))) {
2074                 return -1;
2075         }
2076
2077         contentdup = ast_strdupa(content);
2078         
2079         if (!(maxstr = strchr(contentdup, ','))) {
2080                 ast_log(LOG_WARNING, "Improperly formatted penaltychange rule at line %d. Ignoring.\n", linenum);
2081                 ast_free(rule);
2082                 return -1;
2083         }
2084
2085         *maxstr++ = '\0';
2086         timestr = contentdup;
2087
2088         if ((penaltychangetime = atoi(timestr)) < 0) {
2089                 ast_log(LOG_WARNING, "Improper time parameter specified for penaltychange rule at line %d. Ignoring.\n", linenum);
2090                 ast_free(rule);
2091                 return -1;
2092         }
2093
2094         rule->time = penaltychangetime;
2095
2096         if ((minstr = strchr(maxstr,','))) {
2097                 *minstr++ = '\0';
2098         }
2099         
2100         /* The last check will evaluate true if either no penalty change is indicated for a given rule
2101          * OR if a min penalty change is indicated but no max penalty change is */
2102         if (*maxstr == '+' || *maxstr == '-' || *maxstr == '\0') {
2103                 rule->max_relative = 1;
2104         }
2105
2106         rule->max_value = atoi(maxstr);
2107
2108         if (!ast_strlen_zero(minstr)) {
2109                 if (*minstr == '+' || *minstr == '-') {
2110                         rule->min_relative = 1;
2111                 }
2112                 rule->min_value = atoi(minstr);
2113         } else { /*there was no minimum specified, so assume this means no change*/
2114                 rule->min_relative = 1;
2115         }
2116
2117         /*We have the rule made, now we need to insert it where it belongs*/
2118         AST_LIST_TRAVERSE(&rule_lists, rl_iter, list){
2119                 if (strcasecmp(rl_iter->name, list_name)) {
2120                         continue;
2121                 }
2122
2123                 AST_LIST_TRAVERSE_SAFE_BEGIN(&rl_iter->rules, rule_iter, list) {
2124                         if (rule->time < rule_iter->time) {
2125                                 AST_LIST_INSERT_BEFORE_CURRENT(rule, list);
2126                                 inserted = 1;
2127                                 break;
2128                         }
2129                 }
2130                 AST_LIST_TRAVERSE_SAFE_END;
2131         
2132                 if (!inserted) {
2133                         AST_LIST_INSERT_TAIL(&rl_iter->rules, rule, list);
2134                         inserted = 1;
2135                 }
2136
2137                 break;
2138         }
2139
2140         if (!inserted) {
2141                 ast_log(LOG_WARNING, "Unknown rule list name %s; ignoring.\n", list_name);
2142                 ast_free(rule);
2143                 return -1;
2144         }
2145         return 0;
2146 }
2147
2148 static void parse_empty_options(const char *value, enum empty_conditions *empty, int joinempty)
2149 {
2150         char *value_copy = ast_strdupa(value);
2151         char *option = NULL;
2152         while ((option = strsep(&value_copy, ","))) {
2153                 if (!strcasecmp(option, "paused")) {
2154                         *empty |= QUEUE_EMPTY_PAUSED;
2155                 } else if (!strcasecmp(option, "penalty")) {
2156                         *empty |= QUEUE_EMPTY_PENALTY;
2157                 } else if (!strcasecmp(option, "inuse")) {
2158                         *empty |= QUEUE_EMPTY_INUSE;
2159                 } else if (!strcasecmp(option, "ringing")) {
2160                         *empty |= QUEUE_EMPTY_RINGING;
2161                 } else if (!strcasecmp(option, "invalid")) {
2162                         *empty |= QUEUE_EMPTY_INVALID;
2163                 } else if (!strcasecmp(option, "wrapup")) {
2164                         *empty |= QUEUE_EMPTY_WRAPUP;
2165                 } else if (!strcasecmp(option, "unavailable")) {
2166                         *empty |= QUEUE_EMPTY_UNAVAILABLE;
2167                 } else if (!strcasecmp(option, "unknown")) {
2168                         *empty |= QUEUE_EMPTY_UNKNOWN;
2169                 } else if (!strcasecmp(option, "loose")) {
2170                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID);
2171                 } else if (!strcasecmp(option, "strict")) {
2172                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED | QUEUE_EMPTY_UNAVAILABLE);
2173                 } else if ((ast_false(option) && joinempty) || (ast_true(option) && !joinempty)) {
2174                         *empty = (QUEUE_EMPTY_PENALTY | QUEUE_EMPTY_INVALID | QUEUE_EMPTY_PAUSED);
2175                 } else if ((ast_false(option) && !joinempty) || (ast_true(option) && joinempty)) {
2176                         *empty = 0;
2177                 } else {
2178                         ast_log(LOG_WARNING, "Unknown option %s for '%s'\n", option, joinempty ? "joinempty" : "leavewhenempty");
2179                 }
2180         }
2181 }
2182
2183 /*! \brief Configure a queue parameter.
2184  * 
2185  * The failunknown flag is set for config files (and static realtime) to show
2186  * errors for unknown parameters. It is cleared for dynamic realtime to allow
2187  *  extra fields in the tables.
2188  * \note For error reporting, line number is passed for .conf static configuration,
2189  * for Realtime queues, linenum is -1.
2190 */
2191 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
2192 {
2193         if (!strcasecmp(param, "musicclass") || 
2194                 !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
2195                 ast_string_field_set(q, moh, val);
2196         } else if (!strcasecmp(param, "announce")) {
2197                 ast_string_field_set(q, announce, val);
2198         } else if (!strcasecmp(param, "context")) {
2199                 ast_string_field_set(q, context, val);
2200         } else if (!strcasecmp(param, "timeout")) {
2201                 q->timeout = atoi(val);
2202                 if (q->timeout < 0) {
2203                         q->timeout = DEFAULT_TIMEOUT;
2204                 }
2205         } else if (!strcasecmp(param, "ringinuse")) {
2206                 q->ringinuse = ast_true(val);
2207         } else if (!strcasecmp(param, "setinterfacevar")) {
2208                 q->setinterfacevar = ast_true(val);
2209         } else if (!strcasecmp(param, "setqueuevar")) {
2210                 q->setqueuevar = ast_true(val);
2211         } else if (!strcasecmp(param, "setqueueentryvar")) {
2212                 q->setqueueentryvar = ast_true(val);
2213         } else if (!strcasecmp(param, "monitor-format")) {
2214                 ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
2215         } else if (!strcasecmp(param, "membermacro")) {
2216                 ast_string_field_set(q, membermacro, val);
2217         } else if (!strcasecmp(param, "membergosub")) {
2218                 ast_string_field_set(q, membergosub, val);
2219         } else if (!strcasecmp(param, "queue-youarenext")) {
2220                 ast_string_field_set(q, sound_next, val);
2221         } else if (!strcasecmp(param, "queue-thereare")) {
2222                 ast_string_field_set(q, sound_thereare, val);
2223         } else if (!strcasecmp(param, "queue-callswaiting")) {
2224                 ast_string_field_set(q, sound_calls, val);
2225         } else if (!strcasecmp(param, "queue-quantity1")) {
2226                 ast_string_field_set(q, queue_quantity1, val);
2227         } else if (!strcasecmp(param, "queue-quantity2")) {
2228                 ast_string_field_set(q, queue_quantity2, val);
2229         } else if (!strcasecmp(param, "queue-holdtime")) {
2230                 ast_string_field_set(q, sound_holdtime, val);
2231         } else if (!strcasecmp(param, "queue-minutes")) {
2232                 ast_string_field_set(q, sound_minutes, val);
2233         } else if (!strcasecmp(param, "queue-minute")) {
2234                 ast_string_field_set(q, sound_minute, val);
2235         } else if (!strcasecmp(param, "queue-seconds")) {
2236                 ast_string_field_set(q, sound_seconds, val);
2237         } else if (!strcasecmp(param, "queue-thankyou")) {
2238                 ast_string_field_set(q, sound_thanks, val);
2239         } else if (!strcasecmp(param, "queue-callerannounce")) {
2240                 ast_string_field_set(q, sound_callerannounce, val);
2241         } else if (!strcasecmp(param, "queue-reporthold")) {
2242                 ast_string_field_set(q, sound_reporthold, val);
2243         } else if (!strcasecmp(param, "announce-frequency")) {
2244                 q->announcefrequency = atoi(val);
2245         } else if (!strcasecmp(param, "min-announce-frequency")) {
2246                 q->minannouncefrequency = atoi(val);
2247                 ast_debug(1, "%s=%s for queue '%s'\n", param, val, q->name);
2248         } else if (!strcasecmp(param, "announce-round-seconds")) {
2249                 q->roundingseconds = atoi(val);
2250                 /* Rounding to any other values just doesn't make sense... */
2251                 if (!(q->roundingseconds == 0 || q->roundingseconds == 5 || q->roundingseconds == 10
2252                         || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
2253                         if (linenum >= 0) {
2254                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
2255                                         "using 0 instead for queue '%s' at line %d of queues.conf\n",
2256                                         val, param, q->name, linenum);
2257                         } else {
2258                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
2259                                         "using 0 instead for queue '%s'\n", val, param, q->name);
2260                         }
2261                         q->roundingseconds=0;
2262                 }
2263         } else if (!strcasecmp(param, "announce-holdtime")) {
2264                 if (!strcasecmp(val, "once")) {
2265                         q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
2266                 } else if (ast_true(val)) {
2267                         q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
2268                 } else {
2269                         q->announceholdtime = 0;
2270                 }
2271         } else if (!strcasecmp(param, "announce-position")) {
2272                 if (!strcasecmp(val, "limit")) {
2273                         q->announceposition = ANNOUNCEPOSITION_LIMIT;
2274                 } else if (!strcasecmp(val, "more")) {
2275                         q->announceposition = ANNOUNCEPOSITION_MORE_THAN;
2276                 } else if (ast_true(val)) {
2277                         q->announceposition = ANNOUNCEPOSITION_YES;
2278                 } else {
2279                         q->announceposition = ANNOUNCEPOSITION_NO;
2280                 }
2281         } else if (!strcasecmp(param, "announce-position-limit")) {
2282                 q->announcepositionlimit = atoi(val);
2283         } else if (!strcasecmp(param, "periodic-announce")) {
2284                 if (strchr(val, ',')) {
2285                         char *s, *buf = ast_strdupa(val);
2286                         unsigned int i = 0;
2287
2288                         while ((s = strsep(&buf, ",|"))) {
2289                                 if (!q->sound_periodicannounce[i]) {
2290                                         q->sound_periodicannounce[i] = ast_str_create(16);
2291                                 }
2292                                 ast_str_set(&q->sound_periodicannounce[i], 0, "%s", s);
2293                                 i++;
2294                                 if (i == MAX_PERIODIC_ANNOUNCEMENTS) {
2295                                         break;
2296                                 }
2297                         }
2298                         q->numperiodicannounce = i;
2299                 } else {
2300                         ast_str_set(&q->sound_periodicannounce[0], 0, "%s", val);
2301                         q->numperiodicannounce = 1;
2302                 }
2303         } else if (!strcasecmp(param, "periodic-announce-frequency")) {
2304                 q->periodicannouncefrequency = atoi(val);
2305         } else if (!strcasecmp(param, "relative-periodic-announce")) {
2306                 q->relativeperiodicannounce = ast_true(val);
2307         } else if (!strcasecmp(param, "random-periodic-announce")) {
2308                 q->randomperiodicannounce = ast_true(val);
2309         } else if (!strcasecmp(param, "retry")) {
2310                 q->retry = atoi(val);
2311                 if (q->retry <= 0) {
2312                         q->retry = DEFAULT_RETRY;
2313                 }
2314         } else if (!strcasecmp(param, "wrapuptime")) {
2315                 q->wrapuptime = atoi(val);
2316         } else if (!strcasecmp(param, "penaltymemberslimit")) {
2317                 if ((sscanf(val, "%10d", &q->penaltymemberslimit) != 1)) {
2318                         q->penaltymemberslimit = 0;
2319                 }
2320         } else if (!strcasecmp(param, "autofill")) {
2321                 q->autofill = ast_true(val);
2322         } else if (!strcasecmp(param, "monitor-type")) {
2323                 if (!strcasecmp(val, "mixmonitor")) {
2324                         q->montype = 1;
2325                 }
2326         } else if (!strcasecmp(param, "autopause")) {
2327                 q->autopause = autopause2int(val);
2328         } else if (!strcasecmp(param, "autopausedelay")) {
2329                 q->autopausedelay = atoi(val);
2330         } else if (!strcasecmp(param, "autopausebusy")) {
2331                 q->autopausebusy = ast_true(val);
2332         } else if (!strcasecmp(param, "autopauseunavail")) {
2333                 q->autopauseunavail = ast_true(val);
2334         } else if (!strcasecmp(param, "maxlen")) {
2335                 q->maxlen = atoi(val);
2336                 if (q->maxlen < 0) {
2337                         q->maxlen = 0;
2338                 }
2339         } else if (!strcasecmp(param, "servicelevel")) {
2340                 q->servicelevel= atoi(val);
2341         } else if (!strcasecmp(param, "strategy")) {
2342                 int strategy;
2343
2344                 /* We are a static queue and already have set this, no need to do it again */
2345                 if (failunknown) {
2346                         return;
2347                 }
2348                 strategy = strat2int(val);
2349                 if (strategy < 0) {
2350                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
2351                                 val, q->name);
2352                         q->strategy = QUEUE_STRATEGY_RINGALL;
2353                 }
2354                 if (strategy == q->strategy) {
2355                         return;
2356                 }
2357                 if (strategy == QUEUE_STRATEGY_LINEAR) {
2358                         ast_log(LOG_WARNING, "Changing to the linear strategy currently requires asterisk to be restarted.\n");
2359                         return;
2360                 }
2361                 q->strategy = strategy;
2362         } else if (!strcasecmp(param, "joinempty")) {
2363                 parse_empty_options(val, &q->joinempty, 1);
2364         } else if (!strcasecmp(param, "leavewhenempty")) {
2365                 parse_empty_options(val, &q->leavewhenempty, 0);
2366         } else if (!strcasecmp(param, "eventmemberstatus")) {
2367                 q->maskmemberstatus = !ast_true(val);
2368         } else if (!strcasecmp(param, "eventwhencalled")) {
2369                 if (!strcasecmp(val, "vars")) {
2370                         q->eventwhencalled = QUEUE_EVENT_VARIABLES;
2371                 } else {
2372                         q->eventwhencalled = ast_true(val) ? 1 : 0;
2373                 }
2374         } else if (!strcasecmp(param, "reportholdtime")) {
2375                 q->reportholdtime = ast_true(val);
2376         } else if (!strcasecmp(param, "memberdelay")) {
2377                 q->memberdelay = atoi(val);
2378         } else if (!strcasecmp(param, "weight")) {
2379                 q->weight = atoi(val);
2380         } else if (!strcasecmp(param, "timeoutrestart")) {
2381                 q->timeoutrestart = ast_true(val);
2382         } else if (!strcasecmp(param, "defaultrule")) {
2383                 ast_string_field_set(q, defaultrule, val);
2384         } else if (!strcasecmp(param, "timeoutpriority")) {
2385                 if (!strcasecmp(val, "conf")) {
2386                         q->timeoutpriority = TIMEOUT_PRIORITY_CONF;
2387                 } else {
2388                         q->timeoutpriority = TIMEOUT_PRIORITY_APP;
2389                 }
2390         } else if (failunknown) {
2391                 if (linenum >= 0) {
2392                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
2393                                 q->name, param, linenum);
2394                 } else {
2395                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
2396                 }
2397         }
2398 }
2399
2400 /*!
2401  * \brief Find rt member record to update otherwise create one.
2402  *
2403  * Search for member in queue, if found update penalty/paused state,
2404  * if no member exists create one flag it as a RT member and add to queue member list.
2405 */
2406 static void rt_handle_member_record(struct call_queue *q, char *interface, struct ast_config *member_config)
2407 {
2408         struct member *m;
2409         struct ao2_iterator mem_iter;
2410         int penalty = 0;
2411         int paused  = 0;
2412         int found = 0;
2413         int ringinuse = q->ringinuse;
2414
2415         const char *config_val;
2416         const char *rt_uniqueid = ast_variable_retrieve(member_config, interface, "uniqueid");
2417         const char *membername = S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface);
2418         const char *state_interface = S_OR(ast_variable_retrieve(member_config, interface, "state_interface"), interface);
2419         const char *penalty_str = ast_variable_retrieve(member_config, interface, "penalty");
2420         const char *paused_str = ast_variable_retrieve(member_config, interface, "paused");
2421
2422         if (ast_strlen_zero(rt_uniqueid)) {
2423                 ast_log(LOG_WARNING, "Realtime field uniqueid is empty for member %s\n", S_OR(membername, "NULL"));
2424                 return;
2425         }
2426
2427         if (penalty_str) {
2428                 penalty = atoi(penalty_str);
2429                 if ((penalty < 0) && negative_penalty_invalid) {
2430                         return;
2431                 } else if (penalty < 0) {
2432                         penalty = 0;
2433                 }
2434         }
2435
2436         if (paused_str) {
2437                 paused = atoi(paused_str);
2438                 if (paused < 0) {
2439                         paused = 0;
2440                 }
2441         }
2442
2443         if ((config_val = ast_variable_retrieve(member_config, interface, realtime_ringinuse_field))) {
2444                 if (ast_true(config_val)) {
2445                         ringinuse = 1;
2446                 } else if (ast_false(config_val)) {
2447                         ringinuse = 0;
2448                 } else {
2449                         ast_log(LOG_WARNING, "Invalid value of '%s' field for %s in queue '%s'\n", realtime_ringinuse_field, interface, q->name);
2450                 }
2451         }
2452
2453         /* Find member by realtime uniqueid and update */
2454         mem_iter = ao2_iterator_init(q->members, 0);
2455         while ((m = ao2_iterator_next(&mem_iter))) {
2456                 if (!strcasecmp(m->rt_uniqueid, rt_uniqueid)) {
2457                         m->dead = 0;    /* Do not delete this one. */
2458                         ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
2459                         if (paused_str) {
2460                                 m->paused = paused;
2461                         }
2462                         if (strcasecmp(state_interface, m->state_interface)) {
2463                                 ast_copy_string(m->state_interface, state_interface, sizeof(m->state_interface));
2464                         }
2465                         m->penalty = penalty;
2466                         m->ringinuse = ringinuse;
2467                         found = 1;
2468                         ao2_ref(m, -1);
2469                         break;
2470                 }
2471                 ao2_ref(m, -1);
2472         }
2473         ao2_iterator_destroy(&mem_iter);
2474
2475         /* Create a new member */
2476         if (!found) {
2477                 if ((m = create_queue_member(interface, membername, penalty, paused, state_interface, ringinuse))) {
2478                         m->dead = 0;
2479                         m->realtime = 1;
2480                         ast_copy_string(m->rt_uniqueid, rt_uniqueid, sizeof(m->rt_uniqueid));
2481                         if (!log_membername_as_agent) {
2482                                 ast_queue_log(q->name, "REALTIME", m->interface, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
2483                         } else {
2484                                 ast_queue_log(q->name, "REALTIME", m->membername, "ADDMEMBER", "%s", paused ? "PAUSED" : "");
2485                         }
2486                         ao2_link(q->members, m);
2487                         ao2_ref(m, -1);
2488                         m = NULL;
2489                 }
2490         }
2491 }
2492
2493 /*! \brief Iterate through queue's member list and delete them */
2494 static void free_members(struct call_queue *q, int all)
2495 {
2496         /* Free non-dynamic members */
2497         struct member *cur;
2498         struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
2499
2500         while ((cur = ao2_iterator_next(&mem_iter))) {
2501                 if (all || !cur->dynamic) {
2502                         ao2_unlink(q->members, cur);
2503                 }
2504                 ao2_ref(cur, -1);
2505         }
2506         ao2_iterator_destroy(&mem_iter);
2507 }
2508
2509 /*! \brief Free queue's member list then its string fields */
2510 static void destroy_queue(void *obj)
2511 {
2512         struct call_queue *q = obj;
2513         int i;
2514
2515         free_members(q, 1);
2516         ast_string_field_free_memory(q);
2517         for (i = 0; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
2518                 if (q->sound_periodicannounce[i]) {
2519                         free(q->sound_periodicannounce[i]);
2520                 }
2521         }
2522         ao2_ref(q->members, -1);
2523 }
2524
2525 static struct call_queue *alloc_queue(const char *queuename)
2526 {
2527         struct call_queue *q;
2528
2529         if ((q = ao2_t_alloc(sizeof(*q), destroy_queue, "Allocate queue"))) {
2530                 if (ast_string_field_init(q, 64)) {
2531                         queue_t_unref(q, "String field allocation failed");
2532                         return NULL;
2533                 }
2534                 ast_string_field_set(q, name, queuename);
2535         }
2536         return q;
2537 }
2538
2539 /*!
2540  * \brief Reload a single queue via realtime.
2541  *
2542  * Check for statically defined queue first, check if deleted RT queue,
2543  * check for new RT queue, if queue vars are not defined init them with defaults.
2544  * reload RT queue vars, set RT queue members dead and reload them, return finished queue.
2545  * \retval the queue,
2546  * \retval NULL if it doesn't exist.
2547  * \note Should be called with the "queues" container locked.
2548 */
2549 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
2550 {
2551         struct ast_variable *v;
2552         struct call_queue *q, tmpq = {
2553                 .name = queuename,
2554         };
2555         struct member *m;
2556         struct ao2_iterator mem_iter;
2557         char *interface = NULL;
2558         const char *tmp_name;
2559         char *tmp;
2560         char tmpbuf[64];        /* Must be longer than the longest queue param name. */
2561
2562         /* Static queues override realtime. */
2563         if ((q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Check if static queue exists"))) {
2564                 ao2_lock(q);
2565                 if (!q->realtime) {
2566                         if (q->dead) {
2567                                 ao2_unlock(q);
2568                                 queue_t_unref(q, "Queue is dead; can't return it");
2569                                 return NULL;
2570                         } 
2571                         ast_log(LOG_WARNING, "Static queue '%s' already exists. Not loading from realtime\n", q->name);
2572                         ao2_unlock(q);
2573                         return q;
2574                 }
2575         } else if (!member_config) {
2576                 /* Not found in the list, and it's not realtime ... */
2577                 return NULL;
2578         }
2579         /* Check if queue is defined in realtime. */
2580         if (!queue_vars) {
2581                 /* Delete queue from in-core list if it has been deleted in realtime. */
2582                 if (q) {
2583                         /*! \note Hmm, can't seem to distinguish a DB failure from a not
2584                            found condition... So we might delete an in-core queue
2585                            in case of DB failure. */
2586                         ast_debug(1, "Queue %s not found in realtime.\n", queuename);
2587
2588                         q->dead = 1;
2589                         /* Delete if unused (else will be deleted when last caller leaves). */
2590                         queues_t_unlink(queues, q, "Unused; removing from container");
2591                         ao2_unlock(q);
2592                         queue_t_unref(q, "Queue is dead; can't return it");
2593                 }
2594                 return NULL;
2595         }
2596
2597         /* Create a new queue if an in-core entry does not exist yet. */
2598         if (!q) {
2599                 struct ast_variable *tmpvar = NULL;
2600                 if (!(q = alloc_queue(queuename))) {
2601                         return NULL;
2602                 }
2603                 ao2_lock(q);
2604                 clear_queue(q);
2605                 q->realtime = 1;
2606                 /*Before we initialize the queue, we need to set the strategy, so that linear strategy
2607                  * will allocate the members properly
2608                  */
2609                 for (tmpvar = queue_vars; tmpvar; tmpvar = tmpvar->next) {
2610                         if (!strcasecmp(tmpvar->name, "strategy")) {
2611                                 q->strategy = strat2int(tmpvar->value);
2612                                 if (q->strategy < 0) {
2613                                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
2614                                         tmpvar->value, q->name);
2615                                         q->strategy = QUEUE_STRATEGY_RINGALL;
2616                                 }
2617                                 break;
2618                         }
2619                 }
2620                 /* We traversed all variables and didn't find a strategy */
2621                 if (!tmpvar) {
2622                         q->strategy = QUEUE_STRATEGY_RINGALL;
2623                 }
2624                 queues_t_link(queues, q, "Add queue to container");
2625         }
2626         init_queue(q);          /* Ensure defaults for all parameters not set explicitly. */
2627
2628         memset(tmpbuf, 0, sizeof(tmpbuf));
2629         for (v = queue_vars; v; v = v->next) {
2630                 /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
2631                 if (strchr(v->name, '_')) {
2632                         ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
2633                         tmp_name = tmpbuf;
2634                         tmp = tmpbuf;
2635                         while ((tmp = strchr(tmp, '_'))) {
2636                                 *tmp++ = '-';
2637                         }
2638                 } else {
2639                         tmp_name = v->name;
2640                 }
2641
2642                 /* NULL values don't get returned from realtime; blank values should
2643                  * still get set.  If someone doesn't want a value to be set, they
2644                  * should set the realtime column to NULL, not blank. */
2645                 queue_set_param(q, tmp_name, v->value, -1, 0);
2646         }
2647
2648         /* Temporarily set realtime members dead so we can detect deleted ones. */
2649         mem_iter = ao2_iterator_init(q->members, 0);
2650         while ((m = ao2_iterator_next(&mem_iter))) {
2651                 if (m->realtime) {
2652                         m->dead = 1;
2653                 }
2654                 ao2_ref(m, -1);
2655         }
2656         ao2_iterator_destroy(&mem_iter);
2657
2658         while ((interface = ast_category_browse(member_config, interface))) {
2659                 rt_handle_member_record(q, interface, member_config);
2660         }
2661
2662         /* Delete all realtime members that have been deleted in DB. */
2663         mem_iter = ao2_iterator_init(q->members, 0);
2664         while ((m = ao2_iterator_next(&mem_iter))) {
2665                 if (m->dead) {
2666                         if (ast_strlen_zero(m->membername) || !log_membername_as_agent) {
2667                                 ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
2668                         } else {
2669                                 ast_queue_log(q->name, "REALTIME", m->membername, "REMOVEMEMBER", "%s", "");
2670                         }
2671                         ao2_unlink(q->members, m);
2672                 }
2673                 ao2_ref(m, -1);
2674         }
2675         ao2_iterator_destroy(&mem_iter);
2676
2677         ao2_unlock(q);
2678
2679         return q;
2680 }
2681
2682 /*!
2683  * note  */
2684
2685 /*!
2686  * \internal
2687  * \brief Returns reference to the named queue. If the queue is realtime, it will load the queue as well.
2688  * \param queuename - name of the desired queue
2689  *
2690  * \retval the queue
2691  * \retval NULL if it doesn't exist
2692  */
2693 static struct call_queue *find_load_queue_rt_friendly(const char *queuename)
2694 {
2695         struct ast_variable *queue_vars;
2696         struct ast_config *member_config = NULL;
2697         struct call_queue *q = NULL, tmpq = {
2698                 .name = queuename,
2699         };
2700         int prev_weight = 0;
2701
2702         /* Find the queue in the in-core list first. */
2703         q = ao2_t_find(queues, &tmpq, OBJ_POINTER, "Look for queue in memory first");
2704
2705         if (!q || q->realtime) {
2706                 /*! \note Load from realtime before taking the "queues" container lock, to avoid blocking all
2707                    queue operations while waiting for the DB.
2708
2709                    This will be two separate database transactions, so we might
2710                    see queue parameters as they were before another process
2711                    changed the queue and member list as it was after the change.
2712                    Thus we might see an empty member list when a queue is
2713                    deleted. In practise, this is unlikely to cause a problem. */
2714
2715                 queue_vars = ast_load_realtime("queues", "name", queuename, SENTINEL);
2716                 if (queue_vars) {
2717                         member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, SENTINEL);
2718                         if (!member_config) {
2719                                 ast_debug(1, "No queue_members defined in config extconfig.conf\n");
2720                                 member_config = ast_config_new();
2721                         }
2722                 }
2723                 if (q) {
2724                         prev_weight = q->weight ? 1 : 0;
2725                         queue_t_unref(q, "Need to find realtime queue");
2726                 }
2727
2728                 q = find_queue_by_name_rt(queuename, queue_vars, member_config);
2729                 ast_config_destroy(member_config);
2730                 ast_variables_destroy(queue_vars);
2731
2732                 /* update the use_weight value if the queue's has gained or lost a weight */
2733                 if (q) {
2734                         if (!q->weight && prev_weight) {
2735                                 ast_atomic_fetchadd_int(&use_weight, -1);
2736                         }
2737                         if (q->weight && !prev_weight) {
2738                                 ast_atomic_fetchadd_int(&use_weight, +1);
2739                         }
2740                 }
2741                 /* Other cases will end up with the proper value for use_weight */
2742         } else {
2743                 update_realtime_members(q);
2744         }
2745         return q;
2746 }
2747
2748 static int update_realtime_member_field(struct member *mem, const char *queue_name, const char *field, const char *value)
2749 {
2750         int ret = -1;
2751
2752         if (ast_strlen_zero(mem->rt_uniqueid)) {
2753                 return ret;
2754         }
2755
2756         if ((ast_update_realtime("queue_members", "uniqueid", mem->rt_uniqueid, field, value, SENTINEL)) > 0) {
2757                 ret = 0;
2758         }
2759
2760         return ret;
2761 }
2762
2763
2764 static void update_realtime_members(struct call_queue *q)
2765 {
2766         struct ast_config *member_config = NULL;
2767         struct member *m;
2768         char *interface = NULL;
2769         struct ao2_iterator mem_iter;
2770
2771         if (!(member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", q->name , SENTINEL))) {
2772                 /* This queue doesn't have realtime members. If the queue still has any realtime
2773                  * members in memory, they need to be removed.
2774                  */
2775                 ao2_lock(q);
2776                 mem_iter = ao2_iterator_init(q->members, 0);
2777                 while ((m = ao2_iterator_next(&mem_iter))) {
2778                         if (m->realtime) {
2779                                 ao2_unlink(q->members, m);
2780                         }
2781                         ao2_ref(m, -1);
2782                 }
2783                 ast_debug(3, "Queue %s has no realtime members defined. No need for update\n", q->name);
2784                 ao2_unlock(q);
2785                 return;
2786         }
2787
2788         ao2_lock(q);
2789
2790         /* Temporarily set realtime  members dead so we can detect deleted ones.*/
2791         mem_iter = ao2_iterator_init(q->members, 0);
2792         while ((m = ao2_iterator_next(&mem_iter))) {
2793                 if (m->realtime) {
2794                         m->dead = 1;
2795                 }
2796                 ao2_ref(m, -1);
2797         }
2798         ao2_iterator_destroy(&mem_iter);
2799
2800         while ((interface = ast_category_browse(member_config, interface))) {
2801                 rt_handle_member_record(q, interface, member_config);
2802         }
2803
2804         /* Delete all realtime members that have been deleted in DB. */
2805         mem_iter = ao2_iterator_init(q->members, 0);
2806         while ((m = ao2_iterator_next(&mem_iter))) {
2807                 if (m->dead) {
2808                         if (ast_strlen_zero(m->membername) || !log_membername_as_agent) {
2809                                 ast_queue_log(q->name, "REALTIME", m->interface, "REMOVEMEMBER", "%s", "");
2810                         } else {
2811                                 ast_queue_log(q->name, "REALTIME", m->membername, "REMOVEMEMBER", "%s", "");
2812                         }
2813                         ao2_unlink(q->members, m);
2814                 }
2815                 ao2_ref(m, -1);
2816         }
2817         ao2_iterator_destroy(&mem_iter);
2818         ao2_unlock(q);
2819         ast_config_destroy(member_config);
2820 }
2821
2822 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason, int position)
2823 {
2824         struct call_queue *q;
2825         struct queue_ent *cur, *prev = NULL;
2826         int res = -1;
2827         int pos = 0;
2828         int inserted = 0;
2829
2830         if (!(q = find_load_queue_rt_friendly(queuename))) {
2831                 return res;
2832         }
2833         ao2_lock(q);
2834
2835         /* This is our one */
2836         if (q->joinempty) {
2837                 int status = 0;
2838                 if ((status = get_member_status(q, qe->max_penalty, qe->min_penalty, q->joinempty))) {
2839                         *reason = QUEUE_JOINEMPTY;
2840                         ao2_unlock(q);
2841                         queue_t_unref(q, "Done with realtime queue");
2842                         return res;
2843                 }
2844         }
2845         if (*reason == QUEUE_UNKNOWN && q->maxlen && (q->count >= q->maxlen)) {
2846                 *reason = QUEUE_FULL;
2847         } else if (*reason == QUEUE_UNKNOWN) {
2848                 /* There's space for us, put us at the right position inside
2849                  * the queue.
2850                  * Take into account the priority of the calling user */
2851                 inserted = 0;
2852                 prev = NULL;
2853                 cur = q->head;
2854                 while (cur) {
2855                         /* We have higher priority than the current user, enter
2856                          * before him, after all the other users with priority
2857                          * higher or equal to our priority. */
2858                         if ((!inserted) && (qe->prio > cur->prio)) {
2859                                 insert_entry(q, prev, qe, &pos);
2860                                 inserted = 1;
2861                         }
2862                         /* <= is necessary for the position comparison because it may not be possible to enter
2863                          * at our desired position since higher-priority callers may have taken the position we want
2864                          */
2865                         if (!inserted && (qe->prio >= cur->prio) && position && (position <= pos + 1)) {
2866                                 insert_entry(q, prev, qe, &pos);
2867                                 inserted = 1;
2868                                 /*pos is incremented inside insert_entry, so don't need to add 1 here*/
2869                                 if (position < pos) {
2870                                         ast_log(LOG_NOTICE, "Asked to be inserted at position %d but forced into position %d due to higher priority callers\n", position, pos);
2871                                 }
2872                         }
2873                         cur->pos = ++pos;
2874                         prev = cur;
2875                         cur = cur->next;
2876                 }
2877                 /* No luck, join at the end of the queue */
2878                 if (!inserted) {
2879                         insert_entry(q, prev, qe, &pos);
2880                 }