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