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