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