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