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