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